Translate

TSQL RaiseError from exception

Sunday, January 24, 2021 Category : 0

 
ALTER PROCEDURE [dbo].[usp_GetErrorInfo]  
AS  

DECLARE @ErrorNumber INT
SET @ErrorNumber=ERROR_NUMBER()

DECLARE @ErrorSeverity INT
SET @ErrorSeverity=ERROR_SEVERITY()

DECLARE @ErrorState INT
SET @ErrorState=ERROR_STATE()

DECLARE @ErrorLine INT
SET @ErrorLine=ERROR_LINE()

DECLARE @ErrorMessage NVARCHAR(max)
SET @ErrorMessage=ERROR_MESSAGE()

--SELECT  
    
--    ERROR_NUMBER() AS ErrorNumber  
--    ,ERROR_SEVERITY() AS ErrorSeverity  
--    ,ERROR_STATE() AS ErrorState  
--    ,ERROR_PROCEDURE() AS ErrorProcedure  
--    ,ERROR_LINE() AS ErrorLine  
--    ,ERROR_MESSAGE() AS ErrorMessage;  


RAISERROR (@ErrorMessage, -- Message text.  
               @ErrorSeverity, -- Severity.  
               @ErrorState -- State.  
               ); 

TSQL Table NONCLUSTERED Indexing example

Category : 0

 if index already exists then it will rebuild elase generate a new one.




IF NOT EXISTS (
SELECT *
FROM sys.indexes
WHERE name='IX_StyleSize' AND object_id = OBJECT_ID('dbo.StyleSize') )

BEGIN
        PRINT 'index not found stylesize'

        BEGIN TRY
           
       
               
        BEGIN TRANSACTION
       
        CREATE NONCLUSTERED INDEX IX_StyleSize ON dbo.StyleSize
            (
            GroupID,
            PrdID,
            BTID,
            CBTID,
            SSID,
            sBarcode,
            SupID
            ) WITH ( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
       
        ALTER TABLE dbo.StyleSize SET (LOCK_ESCALATION = TABLE)
    
        --COMMIT

        END TRY
        BEGIN catch
            IF @@TRANCOUNT > 0 
                ROLLBACK TRANSACTION; 
            EXECUTE usp_GetErrorInfo; 
        END CATCH
        
        IF @@TRANCOUNT > 0 
            COMMIT TRANSACTION;

END
ELSE
BEGIN

    BEGIN TRY
       
        PRINT 'index found on stylesize rebuilding...'

        BEGIN TRANSACTION
            ALTER INDEX ALL ON dbo.StyleSize REBUILD;
        COMMIT TRANSACTION


        PRINT 'stylesize index rebuild successfull....'   
    END TRY
    BEGIN CATCH
        IF @@TRANCOUNT > 0 
            ROLLBACK TRANSACTION; 
        --EXECUTE usp_GetErrorInfo; 
        EXEC usp_GetErrorInfo
    END CATCH
    
END


Char Increment Autogenerate Max Value

Tuesday, December 8, 2020 Category : 0

 This method take a string as input and it sequentially increment like excel header


 class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(GetMax("BAA"));
            Console.ReadLine();
        }

        private static string GetMax(string maxvalue)
        {
            int minAsci = 65;
            int maxAsci = 90;

            int len = maxvalue.Length;

            int[] charAscii = new int[len];
            for (int i = 0; i < len; i++)
            {
                charAscii[i] = (int) maxvalue[i];
            }

            bool needChangePrevious = false;
            for (int i = len; i > 0; i--)
            {
                if (i == len)
                {
                    if (charAscii[i-1] < maxAsci)
                    {
                        charAscii[i-1]++;
                    }
                    else
                    {
                        charAscii[i-1] = minAsci;
                        needChangePrevious = true;
                    }
                }
                else
                {
                    if (needChangePrevious)
                    {
                        if (charAscii[i-1] < maxAsci)
                        {
                            charAscii[i-1]++;
                            needChangePrevious = false;
                        }
                        else
                        {
                            charAscii[i-1] = minAsci;
                            needChangePrevious = true;
                        }
                    }
                }
            }

            string newMax = "";
            if (maxvalue == "")
            {
                newMax = "A";
            }
            else if (needChangePrevious == false)
            {
                for (int i = 0; i < len; i++)
                {
                   newMax += (char)charAscii[i] ;
                }
            }
            else if (needChangePrevious == true)
            {
                newMax = "A";
                for (int i = 0; i < len; i++)
                {
                    newMax += (char)charAscii[i];
                }
            }

            return newMax;
        }
    }

AngularJs ASP.NET WepApi File Upload

Sunday, November 1, 2020 Category : , 0

 AngularJs Code:


 var formData = new FormData();
      
        formData.append('files', data);
        formData.append('fileName', data.name);

        return $http({
            url: _urlBase + 'api/app/CustomerExcelUpload',
            method: 'POST',
            //data: JSON.stringify(data),
            processData: false,
            contentType: false,
            data: (formData),
            headers: { 'content-type': undefined, 'Authorization': username + ':' + password }
                    //, transformRequest: angular.identity
            });



ASP.NET WebApi (4.5)


  [HttpPost]
        [Route("api/app/CustomerExcelUpload")]
        public async Task<IHttpActionResult> CustomerExcelUpload()
        {
            //HttpResponseMessage result = null;
            ResponseObj responsobj = new ResponseObj();
            responsobj.COUNT = 0;
            responsobj.CODE = 0;

            try
            {
                

                if (HttpContext.Current.Request.Files.AllKeys.Any())
                {
                    // Get the uploaded image from the Files collection
                    var httpPostedFile = HttpContext.Current.Request.Files["files"];
                    var httpFileName = HttpContext.Current.Request.Form["fileName"];

                    if (httpPostedFile != null)
                    {
                        // Validate the uploaded image(optional)

                        // Get the complete file path
                        var fileSavePath = System.IO.Path.Combine(HttpContext.Current.Server.MapPath("~/upload_doc"), httpPostedFile.FileName);

                        // Save the uploaded file to "UploadedFiles" folder
                        httpPostedFile.SaveAs(fileSavePath);
                    }
                }

                responsobj.Message = "OK";
                responsobj.Success = true;
                responsobj.CODE = 0;
                return Content(HttpStatusCode.OK, responsobj);

            }
            catch (Exception ex)
            {
                Log.Debug("Bad Request");
                responsobj.Message = ex.Message;
                responsobj.Success = false;
                responsobj.CODE = 2;
                return Content(HttpStatusCode.OK, responsobj);

            }
        }



<system.web>
  <httpRuntime executionTimeout="240000" maxRequestLength="2147483647" />
</system.web>

<security>
  <requestFiltering>
    <requestLimits maxAllowedContentLength="4294967295"/>
  </requestFiltering>
</security>

ASP.NET C# File Download

Saturday, July 18, 2020 Category : 0

HttpContext.Current.Response.ContentType = "application/x-download";
                HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=RosterFormat.xlsx");
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.WriteFile(path);
                HttpContext.Current.Response.End();

SQL Date Loop For Each Month

Thursday, July 2, 2020 Category : 0


 DECLARE @FromDate DATETIME
 SET @FromDate='01/01/2020'

 DECLARE @ToDate DATETIME
 SET @ToDate= CONVERT(DATETIME, CAST(  DATEPART(MONTH,GETDATE()) AS NVARCHAR(50) ) + '/01/' + CAST( DATEPART(YEAR,GETDATE()) AS NVARCHAR(50)) ,101 )

 DECLARE @TableName NVARCHAR(50)

 WHILE (@FromDate <= @ToDate)
 BEGIN

     SET @TableName = 'Sales'+ CAST( DATEPART(YEAR,@FromDate) AS NVARCHAR(50)) + RIGHT('00'+ISNULL( CAST( DATEPART(MONTH,@FromDate) AS NVARCHAR(50)) ,''),2)
     PRINT @TableName

     SET @FromDate = DATEADD(MONTH,1,@FromDate)
 END

Powered by Blogger.