Tuesday 18 December 2018

How can I parse JSON with C#?


var jData = "{\"validationErrors\":[{\"description\":\"Employer Registration Number not found.\",\"code\":\"1003\",\"path\":\"employerRegistrationNumber\"}]}";

 var varData = JObject.Parse(jData);
            var varValidationErrorDetails = varData["validationErrors"];
            var varValidationErrorDescription = varValidationErrorDetails[0]["description"];
            string strValidationErrorDescription = Convert.ToString(varValidationErrorDescription).Replace("\r\n", "").Trim();

Tuesday 10 July 2018

Auto Query Generator In MSSQL Server

Before explaining the script, I want to share the reason to write this script and how it is helping my peers. We have code standard on the database side. Below points are standards.
  • Need to maintain a separate stored procedure to every table
  • Don’t use * in the query instead specify the column
  • Use the correct data type and size of a column
  • Every parameter should be nullable in a stored procedure.

CREATE PROC [dbo].[USP_QueryCreationSupport] (@table_Name varchar(100))
AS
BEGIN
    DECLARE @InserCols NVARCHAR(max)
    DECLARE @Inserparam NVARCHAR(max)
    DECLARE @Insertquery NVARCHAR(max)
    DECLARE @Selectquery NVARCHAR(max)
    DECLARE @Update NVARCHAR(max)
    DECLARE @DeleteQuery NVARCHAR(max)

    SELECT '@' + c.NAME + Space(1) + Case cast(t.Name as nvarchar(40))
                                         WHEN 'nvarchar' THEN
                                             t.NAME + '(' + cast(c.max_length as nvarchar(30)) + ')'
                                         WHEN 'varchar' THEN
                                             t.NAME + '(' + cast(c.max_length as nvarchar(30)) + ')'
                                         WHEN 'char' THEN
                                             t.NAME + '(' + cast(c.max_length as nvarchar(30)) + ')'
                                         WHEN 'decimal' THEN
                                             t.NAME + '(18,2)'
                                         ELSE
                                             t.name
                                     end + ' = null,' AS Params
FROM sys.columns c
        inner join sys.types t
            ON c.user_type_id = t.user_type_id
    WHERE c.object_id = object_id(@table_Name)

    SET @InserCols =
    (
        select distinct
            (
                select sc.NAME + ','
                FROM sys.tables st
                    inner join sys.columns sc
                        ON st.object_id = sc.object_id
                WHERE st.NAME = @table_Name
                for xml path(''), type
            ).value('.', 'NVARCHAR(MAX)')
    )
    SELECT @InserCols = LEFT(@InserCols, Len(@InserCols) - 1)

    SET @Inserparam =
    (
        select distinct
            (
                select '@' + sc.NAME + ','
                FROM sys.tables st
                    inner join sys.columns sc
                        ON st.object_id = sc.object_id
                WHERE st.NAME = @table_Name
                for xml path(''), type
            ).value('.', 'NVARCHAR(MAX)')
    )


    SELECT @Inserparam = LEFT(@Inserparam, Len(@Inserparam) - 1)

    SET @Insertquery = 'insert into ' + @table_Name + ' (' + @InserCols + ')' + ' values ' + ' (' + @Inserparam + ')'

    SELECT @Insertquery AS InsertQuery


    SET @Update =
    (
        select distinct
            (
                select sc.NAME + '= @' + sc.NAME + ','
                FROM sys.tables st
                    inner join sys.columns sc
                        ON st.object_id = sc.object_id
                WHERE st.NAME = @table_Name
                for xml path(''), type
            ).value('.', 'NVARCHAR(MAX)')
    )

    SELECT @Update = LEFT(@Update, Len(@Update) - 1)

    SET @Update = 'Update ' + @table_Name + ' set ' + @Update

    SELECT @Update AS UpdateQuery

    SET @Selectquery = 'select ' + @InserCols + ' from ' + @table_Name

    SELECT @Selectquery AS SelectQuery
END

--Execute the stored procedure and pass your table name as a parameter.
EXECUTE dbo.[USP_QueryCreationSupport] @table_Name = 'settings'

Sunday 8 July 2018

SQL SERVER – Custom TRIM Function

ALTER FUNCTION [dbo].[fn_Trim](@String NVARCHAR(MAX))
RETURNS NVARCHAR(MAX)
BEGIN
    RETURN LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@String,CHAR(10),'[]'),CHAR(13),'[]'),char(9),'[]'),CHAR(32),'[]'),'][',''),'[]',CHAR(32))));
END

Monday 2 July 2018

Get All Primary Key In SQL

-- Let's get the columns of the Primary key into a CTE 
;WITH mycte 
     AS (SELECT Schema_name(o.schema_id)            AS 'Schema', 
                Object_name(i2.object_id)           AS 'TableName', 
                Stuff((SELECT ',' + Col_name(ic.object_id, ic.column_id) 
                       FROM   sys.indexes i1 
                              INNER JOIN sys.index_columns ic 
                                      ON i1.object_id = ic.object_id 
                                         AND i1.index_id = ic.index_id 
                       WHERE  i1.is_primary_key = 1 
                              AND i1.object_id = i2.object_id 
                              AND i1.index_id = i2.index_id 
                       FOR xml path('')), 1, 1, '') AS PK 
         FROM   sys.indexes i2 
                INNER JOIN sys.objects o 
                        ON i2.object_id = o.object_id 
         WHERE  i2.is_primary_key = 1 
                AND o.type_desc = 'USER_TABLE') 

-- Use this select to get the count, join to the CTE and get the column list 

SELECT Schema_name(o.schema_id)                    AS 'Schema', 
       Object_name(i.object_id)                    AS 'TableName', 
       Count(Col_name(ic.object_id, ic.column_id)) AS 'Primary_Key_Column_Count' 
       , 
       mycte.pk                                    AS 
       'Primary_Key_Columns' 
FROM   sys.indexes i 
       INNER JOIN sys.index_columns ic 
               ON i.object_id = ic.object_id 
                  AND i.index_id = ic.index_id 
       INNER JOIN sys.objects o 
               ON i.object_id = o.object_id 
       INNER JOIN mycte 
               ON mycte.tablename = Object_name(i.object_id) 
WHERE  i.is_primary_key = 1 
       AND o.type_desc = 'USER_TABLE' 
GROUP  BY Schema_name(o.schema_id), 
          Object_name(i.object_id), 
          mycte.pk   
ORDER  BY 'TableName' ASC   

Tuesday 13 March 2018

Ajax Call Freezes UI, Locked UI During Ajax Call

Solutions: 1. Change the logic to use asynchronous ajax calls.
This may require some re-factoring of the code and be time consuming
but is the best solution.

2. If decided to keep the ajax call synchronous then put this ajax call into
setTimeout to call it with delay and be able to show the animation of
any type (e.g. loading spinner) , this can be shown for some short moment
like 300 milliseconds before the UI will be locked by sync ajax call.

$('#go').click(function() { $(this).after('<div id="loading">Loading...</div>'); setTimeout(function() { $.ajax({ url: '/echo/html/', type: 'post', async: false, data: { html: '<p>AJAX DONE</p>', delay: 3 }, success: function(data) { console.log(data); $('#go').after(data); }, error: function() { alert('Error!'); }, complete: function() { $('#loading').remove(); } }); }, 0); });

Friday 9 February 2018

Truncate Database All Table In SqlServer

DECLARE @tablas TABLE(tableName nvarchar(100))

INSERT INTO @tablas
SELECT t.TABLE_SCHEMA+ '.'+t.TABLE_NAME FROM INFORMATION_SCHEMA.TABLES T

DECLARE @loopCounter INT
SELECT @loopCounter = 0
SELECT @loopCounter = COUNT(*) FROM INFORMATION_SCHEMA.TABLES

WHILE @loopCounter>0 
BEGIN
    SELECT TOP 1 @tableName = tableName FROM @tablas 
    DECLARE @sql NVARCHAR(500) = ''

    SET @sql = @sql +'Truncate table  '+ @tableName
    EXECUTE (@sql)
    SELECT @sql
    SET @loopCounter = @loopCounter-1   
    DELETE TOP (1) @tablas 
END

Wednesday 31 January 2018

Return Newly Inserted Row In Sql Server

CREATE TABLE #TT
(
    ID uniqueidentifier NOT NULL
        DEFAULT newID(),
    name varchar(20),
    AreaCode INT
)

INSERT INTO #TT
(
    Name,
    AreaCode
)
OUTPUT INSERTED.ID,
       INSERTED.Name,
       INSERTED.AreaCode
SELECT 'SS',
       1
UNION ALL
SELECT 'SS1',
       2

DROP TABLE #TT

Recompile All Table, Stored Procedures and Function In SQL Server

CREATE PROCEDURE [dbo].[spEXECsp_RECOMPILE]
AS
BEGIN
    DECLARE @TableName varchar(128)
    DECLARE @OwnerName varchar(128)
    DECLARE @CMD1 varchar(8000)
    DECLARE @TableListLoop int
    DECLARE @TableListTable table
    (
        UIDTableList int IDENTITY(1, 1),
        OwnerName varchar(128),
        TableName varchar(128)
    )

    INSERT INTO @TableListTable
    (
        OwnerName,
        TableName
    )
    SELECT u.[Name],
           o.[Name]
    FROM sys.objects o
        INNER JOIN sys.schemas u
            ON o.schema_id = u.schema_id
    WHERE o.type IN (   'U', -- table
                        'P', -- stored procedures
                        'FN' -- scalar functions
                    )
    ORDER BY u.[Name],
             o.[Name]

    SELECT @TableListLoop = MAX(UIDTableList)
    FROM @TableListTable

    WHILE @TableListLoop > 0
    BEGIN
        SELECT @TableName = TableName,
               @OwnerName = OwnerName
        FROM @TableListTable
        WHERE UIDTableList = @TableListLoop

        SELECT @CMD1 = 'EXEC sp_recompile ' + '[' + @OwnerName + '.' + @TableName + ']' + char(13)

        --PRINT @CMD1
        EXECUTE (@CMD1)

        SELECT @TableListLoop = @TableListLoop - 1
    END

    SELECT *
    FROM @TableListTable

    SET NOCOUNT OFF

END
------------------------------------------------------
--To run used
EXECUTE [dbo].spEXECsp_RECOMPILE

Thursday 25 January 2018

Custom serial number key generator in C# .NET

Create one class named RandomSNKGenerator

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace AppCode
{

    public enum SNKeyLength
    {
        SN16 = 16, SN20 = 20, SN24 = 24, SN28 = 28, SN32 = 32
    }
   /// <summary>
   /// Supports Only 12 Digit
   /// </summary>
    public enum SNKeyNumLength
    {
        SN4 = 4, SN8 = 8, SN12 = 12
    }
    public static class RandomSNKGenerator
    {
        private static string AppendSpecifiedStr(int length, string str, char[] newKey)
        {
            string
            newKeyStr = "";
            int k = 0;
            for (int i = 0; i < length; i++)
            {
                for(k = i; k < 4 + i; k++)
                {
                    newKeyStr += newKey[k];
                }
                if (k == length)
                {
                    break;
                }
                else
                {
                    i = (k) - 1;
                    newKeyStr += str;
                }
            }
            return newKeyStr;
        }

        public static string GetSerialKeyAlphaNumaric(SNKeyLength keyLength)
        {
            Guid newguid = Guid.NewGuid();
            string randomStr = newguid.ToString("N");
            string tracStr = randomStr.Substring(0,(int)keyLength);
            tracStr = tracStr.ToUpper();
            char[] newKey = tracStr.ToCharArray();
            string newSerialNumber = "";
            switch (keyLength)
            {
                case SNKeyLength.SN16:newSerialNumber = AppendSpecifiedStr(16, "-", newKey);
                    break;
                case SNKeyLength.SN20: newSerialNumber = AppendSpecifiedStr(20, "-", newKey);
                    break;
                case SNKeyLength.SN24: newSerialNumber = AppendSpecifiedStr(24, "-", newKey);
                    break;
                case SNKeyLength.SN28: newSerialNumber = AppendSpecifiedStr(28, "-", newKey);
                    break;
                case SNKeyLength.SN32: newSerialNumber = AppendSpecifiedStr(32, "-", newKey);
                    break;
            }

            return newSerialNumber;
        }

        public static string GetSerialKeyNumaric(SNKeyNumLength keyLength)
        {
            Random rn = new Random();
            double sd = Math.Round(rn.NextDouble() * Math.Pow(10, (int)keyLength) + 4);
            return sd.ToString().Substring(0, (int)keyLength);
        }
    }
}

------------------------------------------------------------
string serialNumber = RandomSNKGenerator.GetSerialKeyAlphaNumaric(SNKeyLength.SN16);

or if you want to generate random number only :

string serialNumberNumberOnly = RandomSNKGenerator.GetSerialKeyNumaric(SNKeyNumLength.SN12);
  string serialNumber = AppCode.RandomSNKGenerator.GetSerialKeyAlphaNumaric(SNKeyLength.SN20);

Tuesday 16 January 2018

Add a datarow in datatable at specified index

DataTable existingDataTable = GetMeDataFromSomeWhere();
//Add a new row to table
DataRow newRow = existingDataTable.NewRow();

newRow["ID"] = 999;
newRow["SomeColumn"] = "Manas Bhardwaj";

existingDataTable.Rows.Add(newRow);

//OR If nedd row add in a specific row 

existingDataTable.Rows.InsertAt(dr, 0);

Get all non-clustered indexes

DECLARE cIX CURSOR FOR     SELECT OBJECT_NAME(SI.Object_ID), SI.Object_ID, SI.Name, SI.Index_ID         FROM Sys.Indexes SI             ...