Thursday, September 28, 2017

Extracting substring between two characters OR Delimeters using TSQL,SQLServer 2008

sample values in that Username column:-
1)  <Name=test>
2)  <Name=testKing>
3)  <Name=King>

Sql Query
select SUBSTRING(loginname,CHARINDEX('=',Username )+1,CHARINDEX('>',Username )-CHARINDEX('=',Username )-1)
Result 
  1. test
  2. testKing
  3. King

Log record changes in SQL server in an audit table

1) Create AUDIT Table.

IF NOT EXISTS
      (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[Audit]')
               AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
       CREATE TABLE Audit
               (Type CHAR(1),
               TableName VARCHAR(128),
               PK VARCHAR(1000),
               FieldName VARCHAR(128),
               OldValue VARCHAR(1000),
               NewValue VARCHAR(1000),
               UpdateDate datetime,
               UserName VARCHAR(128))
GO


2) CREATE an UPDATE Trigger on the GUESTS Table as follows.

CREATE TRIGGER TR_GUESTS_AUDIT ON GUESTS FOR UPDATE
AS

DECLARE @bit INT ,
       @field INT ,
       @maxfield INT ,
       @char INT ,
       @fieldname VARCHAR(128) ,
       @TableName VARCHAR(128) ,
       @PKCols VARCHAR(1000) ,
       @sql VARCHAR(2000), 
       @UpdateDate VARCHAR(21) ,
       @UserName VARCHAR(128) ,
       @Type CHAR(1) ,
       @PKSelect VARCHAR(1000)


--You will need to change @TableName to match the table to be audited. 
-- Here we made GUESTS for your example.
SELECT @TableName = 'GUESTS'

-- date and user
SELECT         @UserName = SYSTEM_USER ,
       @UpdateDate = CONVERT (NVARCHAR(30),GETDATE(),126)

-- Action
IF EXISTS (SELECT * FROM inserted)
       IF EXISTS (SELECT * FROM deleted)
               SELECT @Type = 'U'
       ELSE
               SELECT @Type = 'I'
ELSE
       SELECT @Type = 'D'

-- get list of columns
SELECT * INTO #ins FROM inserted
SELECT * INTO #del FROM deleted

-- Get primary key columns for full outer join
SELECT @PKCols = COALESCE(@PKCols + ' and', ' on') 
               + ' i.' + c.COLUMN_NAME + ' = d.' + c.COLUMN_NAME
       FROM    INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk ,

              INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
       WHERE   pk.TABLE_NAME = @TableName
       AND     CONSTRAINT_TYPE = 'PRIMARY KEY'
       AND     c.TABLE_NAME = pk.TABLE_NAME
       AND     c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME

-- Get primary key select for insert
SELECT @PKSelect = COALESCE(@PKSelect+'+','') 
       + '''<' + COLUMN_NAME 
       + '=''+convert(varchar(100),
coalesce(i.' + COLUMN_NAME +',d.' + COLUMN_NAME + '))+''>''' 
       FROM    INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk ,
               INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
       WHERE   pk.TABLE_NAME = @TableName
       AND     CONSTRAINT_TYPE = 'PRIMARY KEY'
       AND     c.TABLE_NAME = pk.TABLE_NAME
       AND     c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME

IF @PKCols IS NULL
BEGIN
       RAISERROR('no PK on table %s', 16, -1, @TableName)
       RETURN
END

SELECT         @field = 0, 
       @maxfield = MAX(ORDINAL_POSITION) 
       FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @TableName
WHILE @field < @maxfield
BEGIN
       SELECT @field = MIN(ORDINAL_POSITION) 
               FROM INFORMATION_SCHEMA.COLUMNS 
               WHERE TABLE_NAME = @TableName 
               AND ORDINAL_POSITION > @field
       SELECT @bit = (@field - 1 )% 8 + 1
       SELECT @bit = POWER(2,@bit - 1)
       SELECT @char = ((@field - 1) / 8) + 1
       IF SUBSTRING(COLUMNS_UPDATED(),@char, 1) & @bit > 0
                                       OR @Type IN ('I','D')
       BEGIN
               SELECT @fieldname = COLUMN_NAME 
                       FROM INFORMATION_SCHEMA.COLUMNS 
                       WHERE TABLE_NAME = @TableName 
                       AND ORDINAL_POSITION = @field
               SELECT @sql = '
INSERT INTO AUDIT (    Type, 
               TableName, 
               PK, 
               FieldName, 
               OldValue, 
               NewValue, 
               UpdateDate, 
               UserName)
select ''' + @Type + ''',''' 
       + @TableName + ''',' + @PKSelect
       + ',''' + @fieldname + ''''
       + ',convert(varchar(1000),d.' + @fieldname + ')'
       + ',convert(varchar(1000),i.' + @fieldname + ')'
       + ',''' + @UpdateDate + ''''
       + ',''' + @UserName + ''''
       + ' from #ins i full outer join #del d'
       + @PKCols
       + ' where i.' + @fieldname + ' <> d.' + @fieldname 
       + ' or (i.' + @fieldname + ' is null and  d.'
                                + @fieldname
                                + ' is not null)' 
       + ' or (i.' + @fieldname + ' is not null and  d.' 
                                + @fieldname
                                + ' is null)' 
               EXEC (@sql)
       END
END


GO

SQL Server : trigger how to read value for Insert, Update, Delete

Logical Tables in Sql Server

Data Manipulation Language (DML) Triggers have access to the two special logical Tables named INSERTED and DELETED. These are the temporary tables managed by Sql Server. Structure of these tables will be same as that of the table on which the DML action is fired and holds the old and new values of the rows which are modified by the DML statement.

DELETED logical table will hold the rows which are deleted from the trigger table (i.e. the table on which the trigger is defined) by the DELETE or UPDATE operation. An UPDATE DML operation is internally executed as first the deletion of the existing record and then insertion of the new record.

INSERTED logical table will hold the rows which are inserted by the INSERT and UPDATE statement.

SELECT
  CASE WHEN inserted.primaryKey IS NULL THEN 'This is a delete'
       WHEN  deleted.primaryKey IS NULL THEN 'This is an insert'
                                        ELSE 'This is an update'
  END  as Action,
  *
FROM
  inserted
FULL OUTER JOIN
  deleted
    ON inserted.primaryKey = deleted.primaryKey

Wednesday, September 27, 2017

how to select a particular tab from other page using JQuery..?

<ul class="nav nav-tabs" id="MyTabs">
        <li><a href="#tab1">Flight</a></li>
        <li id="liHotels"><a href="#tab2">Hotels</a></li>
        <li><a href="#tab3">International Flight</a></li>
        <li id="liRail"><a href="#tab4">Rail</a></li>
        <li><a href="#tab5">Bus</a></li>
</ul>

<div id="tab1" class="tab_content">1</div>
<div id="tab2" class="tab_content">2</div>
<div id="tab3" class="tab_content">3</div>
<div id="tab4" class="tab_content">4</div>
<div id="tab5" class="tab_content">5</div>


<script type="text/javascript">
 $(document).ready(function () {
 // to get Querystring  Parameter Value On Page URL
  // http://www.example.com?searchTab=hotel
if (getParameterByName('searchTab') == 'hotel' ) {             
           
                // To Activate Hotels Tab
                $('#MyTabs li').removeClass("active");
                $('#liHotels').addClass("active");
                $('#MyTabs a[href="#tab2"]').attr("aria-expanded", "true");
                $('#tab2').addClass('tab_content active in');

                // To Remove all Tabs except Hotel Tab
                $('#tab1').removeClass();
                $('#tab3').removeClass();
                $('#tab4').removeClass();
                $('#tab5').removeClass();
                $('#tab1').addClass('tab_content');
                $('#tab3').addClass('tab_content');
                $('#tab4').addClass('tab_content');
                $('#tab5').addClass('tab_content');
            }

});

   function getParameterByName(name, url) {
            if (!url) {
                url = window.location.href;
            }
            name = name.replace(/[\[\]]/g, "\\$&");
            var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
                results = regex.exec(url);
            if (!results) return null;
            if (!results[2]) return '';
            return decodeURIComponent(results[2].replace(/\+/g, " "));
        }
<script type="text/javascript">

Tuesday, September 19, 2017

How the traditional ASP.NET application works

When the user sends a request to IIS, it validates the requested file extension & creates an application domain where the app can run. Later HttpApplication object is created once after all the HTTP object such as HttpContext, HttpRequest and HttpResponse are created. Then the request is processed by the two prominent pillars called HttpModule and HttpHandlers.


Thursday, September 14, 2017

Resizing image using asp.net c#

            #region "Image Resize to 250* 250"
                try
                {
                    // Get the path of the original Image
                    string OriginalImageUrlPath="~/Testimage/TestImage.jpg"
                    string displayedImg = Server.MapPath(OriginalImageUrlPath);
                    FileInfo fi = new FileInfo(displayedImg);
                     //fi.Name="TestImage.jpg";
                    // Get the path of the Thumb folder
                    string ThumbnailImagepath = (@"~/Testimage/Thumbnail" + "/") + fi.Name;
                    string displayedImgThumb = Server.MapPath(ThumbnailImagepath );

                    // Get the original image file name
                    string imgFileName = System.IO.Path.GetFileName(displayedImg);
                    //imgFileName="TestImage.jpg";
                    // Load original image
                    System.Drawing.Image myimg = System.Drawing.Image.FromFile(displayedImg);

                    // Get the thumbnail 250X 250px
                    myimg = myimg.GetThumbnailImage(250, 250, null, IntPtr.Zero);

                    // Save the new thumbnail image
                    myimg.Save(displayedImgThumb, myimg.RawFormat);

                    Console.WriteLine("Success");
                }
                catch(Exception ex)
                {
                     Console.WriteLine("Fail");
                }
                #endregion

Getting “A potentially dangerous Request.Path value was detected from the client (&)”

Solution :
   Checked URL

Correct :  http://www.example.com/test.aspx?param1=test&param2=king

Incorrect : http://www.example.com/test.aspx&param1=test&param2=king


Solve that by changing the line
from
<a href="/Sample/Question/5&jobId=2&type=additional" /> 
to
<a href="/Sample/Question/?id=5&jobId=2&type=additional" />

Change default Port on Next.js app

 If any other app or process is running on port 3000 , you will get this error in your terminal Port 3000 is already in use. error Command f...