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);

Friday, November 16, 2012

Synonyms in SQL Server



SQL Server 2005 introduces the concept of a synonym. A synonyms is a single-part name which can replace multi part name in SQL Statement. Use of synonyms cuts down typing long multi part server name and can replace it with one synonyms. It also provides an abstractions layer which will protect SQL statement using synonyms from changes in underlying objects (tables etc).

A synonym is an identifier that can be used to refer an object from the data base that is having a very long name. Thus instead of using the long name every time we can have the alias or synonym. It gives us and extra layer of security as we have only the Abstract of the object in the form of name which helps us if the underlying object is changed or modified.
We can refer the synonym to perform operations on the base object. We can also use a synonym to refer objects on a linked server, thereby masking the server name.

CREATE SYNONYM statement:

CREATE SYNONYM [schema_name.]synonym_name FOR object_name


To create a synonym,

USE UrDBName;
GO
CREATE SYNONYM MySyn
FOR UrDBName.ObjectNsame
GO

Use Synonyms :

USE test;
GO
SELECT * FROM MySyn;
GO


To drop a synonym, all you need to do is execute the DROP SYNONYM command followed by the synonym name or right-click the synonym and select delete from the context menu.

DROP SYNONYM [schema].SynonymName

Synonyms can be created on only following objects.
  • Assembly (CLR) Stored Procedure
  • Assembly (CLR) Table-valued Function
  • Assembly (CLR) Scalar Function
  • Assembly (CLR) Aggregate Functions
  • Replication-filter-procedure
  • Extended Stored Procedure
  • SQL Scalar Function
  • SQL Table-valued Function
  • SQL Inline-table-valued Function
  • SQL Stored Procedure
  • View
  • Table (User-defined)
Additionally SYNONYMS can be used only to change data of object not the schema of the object. SYNONYMS can be used with only SELECT, UPDATE, INSERT, DELETE, EXECUTE commands.
Now when writing the stored procedure instead of having to write out that entire alias every time you accessed the table you can just use the alias Clients. Furthermore, if you ever change the location or the name of the production database location all you need to do is modify one synonym instead of having to modify all of the stored procedures which reference the old server.


Benefits
  • SYNONYMs provide a layer of abstraction over the referenced object
  • Allow changes to complicated (multi part) and lengthy names with a simplified alias as a same server resident object.
  • Provides flexibility for changing the location of objects without changing existing code.
  • SYNONYMs can be created in the same database to provide backward compatibility for older applications in case of drop or rename of objects.
  • SYNONYMs can be useful if you give the front-end query tools like spreadsheets and Access linked tables direct links in to the tables.
Limitations
  • SYNONYMs are loosely bound to the referenced objects. So you can delete a SYNONYM without getting any warning that it is being referenced by any other database object.
  • Chaining is not allowed. It means that you can not create SYNONYM of a SYNONYM.
  • Obviously consumes possible object names, as you can not create a table with the same name of a synonym
  • The object for which the SYNONYM is being created is checked at run time. It is not checked at creation time. So this means that if you make any related error e.g. spelling error, the synonym will created, but you will get an error while accessing the object.
  • SYNONYM can not be referenced in a DDL statement

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