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 HttpContextHttpRequest 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" />

Friday, September 8, 2017

Auto generate serial no in gridview

<asp:TemplateField HeaderText="Serial No.">
        <ItemTemplate>
           <p>  <%#Container.DataItemIndex+1+ "." %></p>
        </ItemTemplate>
    </asp:TemplateField>

Result: 
   Serial No.
    1.
    2.
    3.

Thursday, September 7, 2017

Bind Html.DropDownList with static items


Method 1:
 @Html.LabelFor(m => m.Name, new { @class = "control-label" })
                    @{
                        var listItems = new List<System.Web.Mvc.SelectListItem>();
                        listItems.Add(new SelectListItem { Text = "name1", Value = "1" });
                        listItems.Add(new SelectListItem { Text = "name2", Value = "2" });
                        listItems.Add(new SelectListItem { Text = "name3", Value = "3" });
                    }
                    @Html.DropDownListFor(m => m.Name, listItems)


Method 2:

@{
            var domainsList = new SelectList(new []
            {
                new SelectListItem { Text = ".Com", Value = ".com", Selected = true },
                new SelectListItem { Text = ".Shopping", Value = ".shopping"},
                new SelectListItem { Text = ".Org", Value = ".org"},
                new SelectListItem { Text = ".Net", Value = ".net"},
                new SelectListItem { Text = ".AE", Value = ".ae"},
                new SelectListItem { Text = ".Info", Value = ".info"},
            }, "Value", "Text");
        }
        @Html.DropDownList("TopLevelDomains", domainsList)

Method 3:

It is a best practice not to create the SelectList in the view. You should create it in the controller and pass it using the ViewData.

Example:

var list = new SelectList(new []
{
    new { ID = "1", Name = "name1" },
    new { ID = "2", Name = "name2" },
    new { ID = "3", Name = "name3" },
},
"ID", "Name", 1);

ViewData["list"]=list;
return View();
you pass to the constratctor: the IEnumerable objec,the value field the text field and the selected value.

in the View:

<%=Html.DropDownList("list",ViewData["list"] as SelectList) %>

Tuesday, September 5, 2017

Visual Studio Expand/Collapse keyboard shortcuts

Collapse to definitions

CTRL + M + O

Expand all outlining

CTRL + M + X

Expand or collapse everything

CTRL + M + L



 comment on web.config?

(1)    you can use

    <--! comment line -->

(2) u just select the line which you want to comment and press

    ctl K + C combination to comment that line...

    to  uncomment ctl K + U combination is used.

Table Valued Parameters in Entity Framework

Table Valued Parameters (TVPs) were introduced in SQL Server 2008. TVPs allow passing multiple rows of data to the server. It can be passed to a Stored Procedure as a parameter. It improves the performance of the application since it prevents several round trips to the server for saving the records in the database. Prior to TVPs we need to pass the data by delimiting with some characters and for doing that we need to write some logic for SQL Server for separating the data.

TVPs are stored in Tempdb and can be created and destroyed automatically behind the scenes.
We can have select or join against TVP.
It is similar to temp tables, table variables or CTEs.
It can be passed from client to server over a network.
Creating TVP in SQL Server

We will first create a table and then create a type of that. I have created a table named Books as in the following:

CREATE TABLE [dbo].[Books](
   [BookId] [int] NOT NULL,
   [BookName] [varchar](50) NOT NULL,
   [AuthorName] [varchar](50) NOT NULL,
   [Email] [varchar](80) NOT NULL,
   [DateCreated] [datetime] NOT NULL,
   CONSTRAINT [PK_Books] PRIMARY KEY CLUSTERED
   (
      [BookId] ASC
   )
)
GO
Now we will create a TVP for the preceding table.

Create Type BooksUDT as Table
(
BookID int,
BookName varchar(50),
AuthorName varchar(50),
Email varchar(80)
)
I have not created a DateCreated column in the TVP since I want this column value to be the latest depending on my SQL Server date. Now I will create a Stored Procedure that will accept this table value parameter as parameter and save multiple rows into the database.

Create proc usp_SaveBooks

@books dbo.BooksUDT Readonly
as
Begin
insert into dbo.Books Select *,SYSDATETIME() from @books
End
At this point we have completed all the work at the SQL Server side. Now we will create a C# Console project and send the table value parameter from C# to SQL Server. Once the project has been created we will add a reference of Entity Framework and refer to our database. Now I will create a datatable that will represent our TVP and will add rows in that. Then we will create one parameter of type SqlParameter to which that datatable will be assigned.

var bookdt = new DataTable();
bookdt.Columns.Add("bookId", typeof(int));
bookdt.Columns.Add("BookName", typeof(string));
bookdt.Columns.Add("AuthorName", typeof(string));
bookdt.Columns.Add("Email", typeof(string));
bookdt.Rows.Add(1, "C#", " C# test", "Csharp@gmail.com");
bookdt.Rows.Add(2, "ASP.NET", " ASP.NETtest", "aspnet@gmail.com");
bookdt.Rows.Add(3, "SQl Server", " SQl Server test", "sql@gmail.com");
bookdt.Rows.Add(4, "OOPS", " OOPS test", "oops@gmail.com");
 
var parameter = new SqlParameter("@books", SqlDbType.Structured);
parameter.Value = bookdt;
parameter.TypeName = "dbo.BooksUDT";
Then we will call the Stored Procedure by passing that SQL parameter to that.

using (SampleDbEntities db = new SampleDbEntities())
{
db.Database.ExecuteSqlCommand("exec dbo.usp_SaveBooks @books", parameter);
}
Disadvantages of Table Value Parameter

TVPs are read-only; once created they cannot get changed
The Output keyword cannot be used with them
To change the schema of a TVP we need to recreate it
Statistics are not maintained on TVPs

Friday, September 1, 2017

To update URL or query strings using javascript/jQuery without reloading the page

Syntax
 replaceUrl(window.location.href, "BookName", "DotNet");


function replaceUrl(uri, key, value) {
            debugger;
            var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
            var separator = uri.indexOf('?') !== -1 ? "&" : "?";
            if (uri.match(re)) {
                window.history.replaceState("", "Title Name", uri.replace(re, '$1' + key + "=" + value + '$2'));
            }
            else {
                window.history.replaceState("", "Title Name", uri + separator + key + "=" + value);
            }
        }

window.history.replaceState

var replaceState_tmp = window.history.replaceState.constructor;
window.history.replaceState.constructor = function(obj, title, url){
    var title_ = document.getElementsByTagName('title')[0];
    if(title_ != undefined){
        title_.innerHTML = title;
    }else{
        var title__ = document.createElement('title');
        title__.innerHTML = title;
        var head_ = document.getElementsByTagName('head')[0];
        if(head_ != undefined){
            head_.appendChild(title__);
        }else{
            var head__ = document.createElement('head');
            document.documentElement.appendChild(head__);
            head__.appendChild(title__);
        }
    }
    replaceState_tmp(obj,title, url);
}


history.pushState(null, null, link.href);

The history.pushState() function takes three parameters:

    1.state can be any JSON data structure. It is passed back to the popstate event hander,

   2.title can be any string. This parameter is currently unused by major browsers. If you want to set the page title, you should store it in the state argument and set it manually in your popstate callback.

     3.url can be, well, any URL. This is the URL you want to appear in the browser’s location bar.


var myURL = document.location;
document.location = myURL + "?a=parameter";
The location object has a number of useful properties too:

hash            Returns the anchor portion of a URL
host            Returns the hostname and port of a URL
hostname        Returns the hostname of a URL
href            Returns the entire URL
pathname        Returns the path name of a URL
port            Returns the port number the server uses for a URL
protocol        Returns the protocol of a URL
search          Returns the query portion of a URL

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...