Wednesday, November 1, 2017

sp_executesql

Executes a Transact-SQL statement or batch that can be reused many times, or one that has been built dynamically. The Transact-SQL statement or batch can contain embedded parameters.

Syntax:
 EXECUTE sp_executesql 
          N'SELECT * FROM Book 
          WHERE BookID= @bookid', 
          N'@bookId int', 
          @bookId= 100;  

MEAN Stack

 MEAN Stack a combination of open source JavaScript framework

MEAN is actually combination of 3 JavaScript frameworks and a NoSQL or document based Database technology

M is for MongoDB

MongoDB is an open source, document-oriented database designed with both scalability and developer agility in mind. Instead of storing your data in tables and rows as you would with a relational database, in MongoDB you store JSON-like documents with dynamic schemas.

E is for ExpressJS

Express.js is a Node.js web application server framework, designed for building single-page, multi-page, and hybrid web applications. It is the de facto standard server framework for node.js.

A is for AngularJS

AngularJS is a structural framework for dynamic web apps. It lets you use HTML as your template language and lets you extend HTML's syntax to express your application's components clearly and succinctly.Angular's data binding and dependency injection eliminate much of the code you would otherwise have to write.

N is for NodeJS

nodejs.org. Node.js is an open-source, cross-platform runtime environment for developing server-side web applications. Node.js applications are written in JavaScript and can be run within the Node.js runtime on OS X, Microsoft Windows, Linux, FreeBSD, NonStop, IBM AIX, IBM System z and IBM.


MEAN is

The term MEAN stack refers to a collection of JavaScript based technologies used to develop web applications. MEAN is an acronym for MongoDB, ExpressJS, AngularJS and Node.js. From client to server to database, MEAN is full stack JavaScript.


Monday, October 9, 2017

How to Find Database Changes in SQL Server

-- Find Stored Procedure Changes

SELECT create_date, modify_date, name FROM sys.procedures
ORDER BY modify_date DESC

-- Find user Defined function Changes
SELECT name, create_date, modify_date
FROM sys.objects
WHERE type = 'fn' ORDER BY modify_date DESC


SELECT * FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE = N'FUNCTION' and ROUTINE_SCHEMA = N'dbo'
order by  LAST_ALTERED desc

SELECT * FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE = N'FUNCTION' and ROUTINE_SCHEMA = N'dbo'
order by  CREATED desc






-- Find modified and new added columns list from particular table In sql server 2008

 SELECT
    OBJECT_NAME(sc.[object_id]) as [table]
    ,sc.[name] as [column]
    ,so.modify_date
    ,so.create_date
  FROM [sys].[columns] sc
  JOIN [sys].[objects] so
  ON sc.[object_id] = so.[object_id]
  ORDER BY so.modify_date DESC, so.create_date ASC

-- Find Count Of User Defined Table and Stored Procedure in particular Database.

SELECT
    CASE TYPE
        WHEN 'U'
            THEN 'User Defined Tables'
        WHEN 'S'
            THEN 'System Tables'
        WHEN 'IT'
            THEN 'Internal Tables'
        WHEN 'P'
            THEN 'Stored Procedures'
        WHEN 'PC'
            THEN 'CLR Stored Procedures'
        WHEN 'X'
            THEN 'Extended Stored Procedures'
    END,
    COUNT(*)   
FROM SYS.OBJECTS
WHERE TYPE IN ('U', 'P', 'PC', 'S', 'IT', 'X')
GROUP BY TYPE

---
How to identify all stored procedures referring a particular table


select distinct [Table Name] = o.Name, [Found In] = sp.Name, sp.type_desc
  from sys.objects o inner join sys.sql_expression_dependencies  sd on o.object_id = sd.referenced_id
                inner join sys.objects sp on sd.referencing_id = sp.object_id
                    and sp.type in ('P', 'FN')
  where o.name = 'TestTable'
  order by sp.Name



Find all stored procedures that reference a specific column in some table


SELECT DISTINCT OBJECT_NAME(OBJECT_ID),
object_definition(OBJECT_ID)
FROM sys.Procedures
WHERE object_definition(OBJECT_ID) LIKE '%' + 'ColumnName' + '%'
GO

Find all table names with column name?

SELECT DISTINCT OBJECT_NAME(OBJECT_ID),
object_definition(OBJECT_ID)
FROM sys.Procedures
WHERE object_definition(OBJECT_ID) LIKE '%' + 'ColumnName' + '%'
GO


Need to list all triggers in SQL Server database with table name and table's schema

SELECT
     sysobjects.name AS trigger_name
    ,USER_NAME(sysobjects.uid) AS trigger_owner
    ,s.name AS table_schema
    ,OBJECT_NAME(parent_obj) AS table_name
    ,OBJECTPROPERTY( id, 'ExecIsUpdateTrigger') AS isupdate
    ,OBJECTPROPERTY( id, 'ExecIsDeleteTrigger') AS isdelete
    ,OBJECTPROPERTY( id, 'ExecIsInsertTrigger') AS isinsert
    ,OBJECTPROPERTY( id, 'ExecIsAfterTrigger') AS isafter
    ,OBJECTPROPERTY( id, 'ExecIsInsteadOfTrigger') AS isinsteadof
    ,OBJECTPROPERTY(id, 'ExecIsTriggerDisabled') AS [disabled]
FROM sysobjects

INNER JOIN sysusers
    ON sysobjects.uid = sysusers.uid

INNER JOIN sys.tables t
    ON sysobjects.parent_obj = t.object_id

INNER JOIN sys.schemas s
    ON t.schema_id = s.schema_id

WHERE sysobjects.type = 'TR'
EDIT: Commented out join to sysusers for query to work on AdventureWorks2008.

SELECT
     sysobjects.name AS trigger_name
    ,USER_NAME(sysobjects.uid) AS trigger_owner
    ,s.name AS table_schema
    ,OBJECT_NAME(parent_obj) AS table_name
    ,OBJECTPROPERTY( id, 'ExecIsUpdateTrigger') AS isupdate
    ,OBJECTPROPERTY( id, 'ExecIsDeleteTrigger') AS isdelete
    ,OBJECTPROPERTY( id, 'ExecIsInsertTrigger') AS isinsert
    ,OBJECTPROPERTY( id, 'ExecIsAfterTrigger') AS isafter
    ,OBJECTPROPERTY( id, 'ExecIsInsteadOfTrigger') AS isinsteadof
    ,OBJECTPROPERTY(id, 'ExecIsTriggerDisabled') AS [disabled]
FROM sysobjects
/*
INNER JOIN sysusers
    ON sysobjects.uid = sysusers.uid
*/
INNER JOIN sys.tables t
    ON sysobjects.parent_obj = t.object_id

INNER JOIN sys.schemas s
    ON t.schema_id = s.schema_id
WHERE sysobjects.type = 'TR'
EDIT 2: For SQL 2000

SELECT
     o.name AS trigger_name
    ,'x' AS trigger_owner
    /*USER_NAME(o.uid)*/
    ,s.name AS table_schema
    ,OBJECT_NAME(o.parent_obj) AS table_name
    ,OBJECTPROPERTY(o.id, 'ExecIsUpdateTrigger') AS isupdate
    ,OBJECTPROPERTY(o.id, 'ExecIsDeleteTrigger') AS isdelete
    ,OBJECTPROPERTY(o.id, 'ExecIsInsertTrigger') AS isinsert
    ,OBJECTPROPERTY(o.id, 'ExecIsAfterTrigger') AS isafter
    ,OBJECTPROPERTY(o.id, 'ExecIsInsteadOfTrigger') AS isinsteadof
    ,OBJECTPROPERTY(o.id, 'ExecIsTriggerDisabled') AS [disabled]
FROM sysobjects AS o
/*
INNER JOIN sysusers
    ON sysobjects.uid = sysusers.uid
*/
INNER JOIN sysobjects AS o2
    ON o.parent_obj = o2.id

INNER JOIN sysusers AS s
    ON o2.uid = s.uid

WHERE o.type = 'TR'

Need to list all triggers in SQL Server database with table name and table's schema

SELECT
     sysobjects.name AS trigger_name
    ,USER_NAME(sysobjects.uid) AS trigger_owner
    ,s.name AS table_schema
    ,OBJECT_NAME(parent_obj) AS table_name
    ,OBJECTPROPERTY( id, 'ExecIsUpdateTrigger') AS isupdate
    ,OBJECTPROPERTY( id, 'ExecIsDeleteTrigger') AS isdelete
    ,OBJECTPROPERTY( id, 'ExecIsInsertTrigger') AS isinsert
    ,OBJECTPROPERTY( id, 'ExecIsAfterTrigger') AS isafter
    ,OBJECTPROPERTY( id, 'ExecIsInsteadOfTrigger') AS isinsteadof
    ,OBJECTPROPERTY(id, 'ExecIsTriggerDisabled') AS [disabled]
FROM sysobjects

INNER JOIN sysusers
    ON sysobjects.uid = sysusers.uid

INNER JOIN sys.tables t
    ON sysobjects.parent_obj = t.object_id

INNER JOIN sys.schemas s
    ON t.schema_id = s.schema_id

WHERE sysobjects.type = 'TR'
EDIT: Commented out join to sysusers for query to work on AdventureWorks2008.

SELECT
     sysobjects.name AS trigger_name
    ,USER_NAME(sysobjects.uid) AS trigger_owner
    ,s.name AS table_schema
    ,OBJECT_NAME(parent_obj) AS table_name
    ,OBJECTPROPERTY( id, 'ExecIsUpdateTrigger') AS isupdate
    ,OBJECTPROPERTY( id, 'ExecIsDeleteTrigger') AS isdelete
    ,OBJECTPROPERTY( id, 'ExecIsInsertTrigger') AS isinsert
    ,OBJECTPROPERTY( id, 'ExecIsAfterTrigger') AS isafter
    ,OBJECTPROPERTY( id, 'ExecIsInsteadOfTrigger') AS isinsteadof
    ,OBJECTPROPERTY(id, 'ExecIsTriggerDisabled') AS [disabled]
FROM sysobjects
/*
INNER JOIN sysusers
    ON sysobjects.uid = sysusers.uid
*/ 
INNER JOIN sys.tables t
    ON sysobjects.parent_obj = t.object_id

INNER JOIN sys.schemas s
    ON t.schema_id = s.schema_id
WHERE sysobjects.type = 'TR'
EDIT 2: For SQL 2000

SELECT
     o.name AS trigger_name
    ,'x' AS trigger_owner
    /*USER_NAME(o.uid)*/
    ,s.name AS table_schema
    ,OBJECT_NAME(o.parent_obj) AS table_name
    ,OBJECTPROPERTY(o.id, 'ExecIsUpdateTrigger') AS isupdate
    ,OBJECTPROPERTY(o.id, 'ExecIsDeleteTrigger') AS isdelete
    ,OBJECTPROPERTY(o.id, 'ExecIsInsertTrigger') AS isinsert
    ,OBJECTPROPERTY(o.id, 'ExecIsAfterTrigger') AS isafter
    ,OBJECTPROPERTY(o.id, 'ExecIsInsteadOfTrigger') AS isinsteadof
    ,OBJECTPROPERTY(o.id, 'ExecIsTriggerDisabled') AS [disabled]
FROM sysobjects AS o
/*
INNER JOIN sysusers
    ON sysobjects.uid = sysusers.uid
*/ 
INNER JOIN sysobjects AS o2
    ON o.parent_obj = o2.id

INNER JOIN sysusers AS s
    ON o2.uid = s.uid

WHERE o.type = 'TR'

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

Thursday, August 31, 2017

Base64 encoding and decoding(btoa & atob)

Base64 is a group of similar binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation.

In JavaScript there are two functions respectively for decoding and encoding base64 strings:
atob()
btoa()

In these APIs, for mnemonic purposes, the "b" can be considered to stand for "binary", and the "a" for "ASCII"

The atob() function decodes a string of data which has been encoded using base-64 encoding.

Conversely, the btoa() function creates a base-64 encoded ASCII string from a "string" of binary data.

Both atob() and btoa() work on strings

Syntax
var encodedData = scope.btoa(stringToEncode);

Parameters
stringToEncode
A string whose characters each represent a single byte of binary data to be encoded into ASCII.
Return value
A string containing the Base64 representation of stringToEncode.

Example

var encodedData = window.btoa('Hello, world'); // encode a string
var decodedData = window.atob(encodedData); // decode the string

how to call javascript function in c#

Home.aspx.cs

protected void BtnLogin_click(object sender,eventargs e)
{

//when i click this button i need to call javascript function
    System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append(@"<script language="'javascript'">");
            sb.Append(@"JavaScriptFunctionName();");
            sb.Append(@"</script>");
       System.Web.UI.ScriptManager.RegisterStartupScript(this, this.GetType(), "JSName",     sb.ToString(), false);

}


Home.aspx

<script type="text/javascript">
function JavaScriptFunctionName()
{
 alert('Called JS function.');
}
</script>



Thursday, August 24, 2017

To Get HTTP-specific information about the current request.

HttpContext

ASP.NET core infrastructure is built around HttpApplication class
which has a reference to System.Web.HttpContext (System.Web) class’s instance in its Context property.

The problem with this is that it has no base class and isn't virtual,
and hence is unusable for testing (cannot mock it).
It's recommended to not pass it around as function arguments, instead pass around variables of type HttpContextBase.

HttpContextBase

This is the (new to c# 3.5) replacement to HttpContext.
Since it is abstract, it is now mockable.
The idea is that your functions that expect to be passed a context should expect to receive one of these.
It is concretely implemented by HttpContextWrapper.

ASP.NET MVC on the other hand uses System.Web.HttpContextBase.Controller class has Context property of type System.Web.HttpContextBase.
Idea behind introducing the new HttpContextBase instead of HttpContext is to allow unit-testing due to HttpContextBase is an abstract class.

HttpContextWrapper

Encapsulates the HTTP intrinsic object that contains HTTP-specific information about an individual HTTP request.

Also new in C# 3.5 - this is the concrete implementation of HttpContextBase.
To create one of these in a normal webpage, use new HttpContextWrapper(HttpContext.Current).

The idea is that to make your code unit-testable,
you declare all your variables and function parameters to be of type HttpContextBase,
and use an IOC framework .
In normal code, castle is to inject the equivalent of 'new HttpContextWrapper(HttpContext.Current)',
whereas in test code you're to be given a mock of HttpContextBase.


But sometimes we may need to convert HttpContext into HttpContextBase and vice versa.
E.g. when we have common logic which is being used from HttpApplication and from MVC controllers.

Getting HttpContext from HttpContextBase’s instance is easy:
HttpContext httpContext = httpContextBase.ApplicationInstance.Context;

To get HttpContextBase from HttpContext we have to wrap it in HttpContextWrapper:
HttpContextBase abstractContext = new System.Web.HttpContextWrapper(context);

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