31 October 2016

Data Annotations

routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "myuser", action = "Index", id = UrlParameter.Optional }
);

using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations.Schema;

[Required]
[StringLength(20, MinimumLength = 4, ErrorMessage = "Must be at least 4 characters long.")]
[Remote("checkusername", "myuser")]
public string username { get; set; }

[Required]
public string firstname { get; set; }

public string lastname { get; set; }

[Required]
public string address { get; set; }

[Required]
[DataType(DataType.PhoneNumber)]
[StringLength(10, MinimumLength = 10, ErrorMessage = "{0}: it should be 10 digits")]
public Nullable phone { get; set; }

[Required(ErrorMessage = "{0} required")]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email")]
[RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", ErrorMessage = "Invalid email")]
[Remote("checkemail", "myuser", ErrorMessage = "Already in use!")]
[StringLength(100, ErrorMessage = "{0}: 100 is the limit")]
public string email { get; set; }

public Nullable isactive { get; set; }

[Required]
[DataType(DataType.Password)]
public string password { get; set; }

[Required]
[NotMapped]
[System.ComponentModel.DataAnnotations.Compare("password", ErrorMessage = "Password doesn't match.")]
[DataType(DataType.Password)]
public string confirmpassword { get; set; }

public JsonResult checkusername(string username)
{
var data = db.users.Where(p => p.username.Equals(username, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();

if (data != null)
{
return Json("Sorry, this name already exists", JsonRequestBehavior.AllowGet);
}
else
{
return Json(true, JsonRequestBehavior.AllowGet);
}
}

public JsonResult checkemail(string email)
{
var result = true;
var user = db.users.Where(x => x.email == email).FirstOrDefault();

if (user != null)
result = false;

return Json(result, JsonRequestBehavior.AllowGet);
}

18 August 2016

Difference between GET and POST

Both perform same action only. Using both we can able to transfer data from one application to another. Using get method we can able to view the information in URL itself, but using post we can able to transfer data over networks, so this is very secure. Post method data we can’t get it directly. But Get method data we can get easily.

We can’t able to transfer bulk of data using GET method. But using post method we can able to transfer bulk of data. Compare to GET method POST method is secure.

Self-join queries

Self-Join is a type of join which is used to join the same table by creating the second instance of the same table. So we join 2 instances of the same table in case of self-join. This type of join is used when there is the requirement to get the referenced data which is available in the same table.
e.g. A table contains EmpId, Ename and ManagerId
As the manager id is also an employee id. Now if we want that who is the manager of which employee. In this situation, we need to create the instance of the same table and get the required data as:

SELECT EMPID, ENAME, ENAME AS [MANAGER NAME]
FROM EMP E1, EMP E2
WHERE E1.EMPID= E2.MANAGERID

Anonymous methods in C#

The concept of anonymous method was introduced in C# 2.0. An anonymous method is inline unnamed method in the code. It is created using the delegate keyword and doesn’t required name and return type. Hence we can say, an anonymous method has only body without name, optional parameters and return type. An anonymous method behaves like a regular method and allows us to write inline code in place of explicitly named methods.



A Simple Anonymous Method Example


delegate int MathOp(int a, int b);
class Program
{
//delegate for representing anonymous method
delegate int del(int x, int y);

static void Main(string[] args)
{
//anonymous method using delegate keyword
del d1 = delegate(int x, int y) { return x * y; };

int z1 = d1(2, 3);
Console.WriteLine(z1);
}
}
//output:
6

Key points about anonymous method



  1. A variable, declared outside the anonymous method can be accessed inside the anonymous method.

  2. A variable, declared inside the anonymous method can’t be accessed outside the anonymous method.

  3. We use anonymous method in event handling.

  4. An anonymous method, declared without parenthesis can be assigned to a delegate with any signature.

  5. Unsafe code can’t be accessed within an anonymous method.

  6. An anonymous method can’t access the ref or out parameters of an outer scope.


Anonymous Method as an Event Handler


 <form id="form1" runat="server">
< div align="center">
<h2>Anonymous Method Example</h2>
<br />
<asp:Label ID="lblmsg" runat="server" ForeColor="Green" Font-Bold="true"></asp:Label>
<br /><br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" />
<asp:Button ID="btnCancel" runat="server" Text="Cancel" />
</div>
</form>


protected void Page_Load(object sender, EventArgs e)
{
// Click Event handler using Regular method
btnCancel.Click += new EventHandler(ClickEvent);
// Click Event handler using Anonymous method
btnSubmit.Click += delegate { lblmsg.Text=
"Submit Button clicked using Anonymous method"; };
}
protected void ClickEvent(object sender, EventArgs e)
{
lblmsg.Text="Cancel Button clicked using Regular method";
}

11 August 2016

Interview questions

http://pawantechit.blogspot.in/2013/03/interview-question-for-3-6-year.html

http://www.interviewquestionspdf.com/2014/09/aspnet-interview-questions-and-answers.html

https://www.udemy.com/understand-nodejs/

https://www.udemy.com/learn-angularjs/

https://www.udemy.com/design-and-develop-a-killer-website-with-html5-and-css3/

User id : aagrawal ksl

Pwd: password234

http://www.dotnetspider.com/resources/44635-Interview-Questions-3-6-years-experienced-Net-professional.aspx

http://www.aspdotnet-suresh.com/2010/05/interview-questions-in-aspnetcnetsql.html

http://pawantechit.blogspot.in/2013/03/interview-question-for-3-6-year.html

http://pluralsight.com/training/Player?author=scott-allen&name=mvc4-building-m2-controllers&mode=live&clip=0&course=mvc4-building

http://www.dotnet-tricks.com/Tutorial/mvclist

08 August 2016

Stored procedure vs inline query

Stored procedures are precompiled and cached so the performance is much better.

The choice of choosing stored procedures will not be performance but it will be more from the aspect of security and maintenance. Below are some of the points where stored procedures are definitely a plus over inline SQL.

Abstraction


By putting all your SQL code into a stored procedure, your application is completely abstracted from the field names, tables names, etc. So when you make changes in the SQL, you have less impact in your C# code.

Security


This is the best part where stored procedures again score, you can assign execution rights on users and roles.



Maintenance ease


Now because we have centralized our stored procedures any issue like fixing defects and other changes can be easily done in a stored procedure and it will be reflected across the installed clients. At least we do not need to compile and deploy DLLs and EXEs.

Centralized tuning


If we know we have a slow running stored procedure, we can isolate it and the DBA guys can performance tune it separately.

Cursors, temp table complications


Simple TSQLs are OK. But what if you have a bunch of statements with IF, ELSE, Cursors, etc? For those kind of scenarios, again stored procedures are very handy.

06 August 2016

State management

A new instance of the Web page class is created each time the page is posted to the server. In traditional Web programming, this would typically mean that all information associated with the page and the controls on the page would be lost with each round trip.

To overcome this inherent limitation of traditional Web programming, ASP.NET includes several options. These features are as follows:

  • View state

  • Control state

  • Hidden fields

  • Cookies

  • Query strings

  • Application state

  • Session state

  • Profile Properties


 

https://msdn.microsoft.com/en-us/library/75x4ha6s.aspx

return types in mvc

Return View

This is a most common and very frequently used type. We see that we can pass eight parameters when we return the view. We can specify the view name explicitly or may not.
Return View

Return partial View

The concept of a partial view is very similar to the master page concept in Web Form applications. The partial view is nothing but  pagelet, that we can return from the controller and that merges with the main view and generates one concrete HTML page.


Return partial View

It may take 4 parameters to render in the partial view.

Redirect

This is equivalent to Response.redirect() or Server.Transfer() functions. It takes the URL path to be redirect , though we can use Response.Redirect() or Server.Transfer() in MVC too.


Redirect

Redirect To Action

Sometimes it is necessary to call another action after completion of one action, this is very similar to a function call in traditional function oriented programming or Object Oriented Programming. It may take 6 parameters. The first parameter is very simple, only action name.


Redirect To Action

Return content

This is useful when we want to return a small amount of strings from a controller/action. It takes three parameters. The first one is a simple string and the remaining two are strings with little information.


Return content

Return JSON

This is very useful when we don't want an entire HTML page but only want a value. Generally in AJAX-based single-page applications we do not load an entire page again and again but load fresh data from the DB using AJAX. In this scenario we can return only a JSON object and in the success function of jQuery ajax (let's assume we are using the jQuery library to implement AJAX) we can just manipulate data.


Return json

Return JavaScript

When we wanted to return a JavaScript string , we may use this function. It takes only one parameter, the string only.


Return JavaScript

Return File

We are allowed to return a binary file if needed from a controller. It takes 6 parameters maximum.


Return File

user control vs custom control in c#


























































Custom ControlUser Control
A loosely coupled control w.r.t code and UIA tightly coupled control w.r.t code and UI
Derives from ControlDerives from UserControl
Defines UI in a ResourceDictionaryDefines UI as normal XAML
UI is skinableChild controls are skinable
Has dynamic layoutHas static layout
UI can be changed in different projectsUI is fixed and can't have different looks in different project
Has full toolbox support, Jst drag n drop from toolboxCan't be added to the toolbox, Jst drag n drop from sol’n explorer to page(aspx)
Defines a single controlDefines a set of controls
More flexibleNot very flexible like a Custom Control
Reusability of control (extend functionality of existing control), Designed so that it can be used by more than one applicationReusability web page, Designed for single-application scenarios
Compiled into dllNot compiled into dll
Creation is similar to the way Web Forms pages are created; well-suited for rapid application development (RAD)Writing involves lots of code because there is no designer support

Button, CheckBox, TextBox etc., even a UserControl is nothing but a Custom Control. You can easily load them inside a XAML page.

Custom Controls are compiled into a DLL assembly and can be reused in multiple places very easily. You have total control over the code, thus gives you more flexibility to extend the behaviour. Once you build and add a reference of the custom control in your project, you can find it in the toolbox. Thus, you will be able to drag and drop the control in your Design view and start working with it very easily.

  • When you have a rapid and fixed content in your UI, use UserControl.

  • When you want to separate some basic functionality of your main view to some smaller pieces with reusability, use UserControl.

  • When you want to use your control in different projects and each project may want to change the look, use CustomControl.

  • When you want to implement some additional functionality for a control, create a CustomControl derived from the base control.

  • When you want to apply themes to your controls, use CustomControl.

  • When you want to add toolbox support for your control, so that your user will be able to do drag and drop to the designer, use CustomControl.


For user control:
<%@ Register TagPrefix="UC" TagName="TestControl" Src="test.ascx" %>

For custom control:

<%@ Register TagPrefix="CC " Namespace=" CustomServerControlsLib " Assembly="CustomServerControlsLib " %>

 

05 August 2016

Linq query on datatable

var results = from myRow in myDataTable.AsEnumerable()
where myRow.Field<int>("RowNo") == 1
select myRow;

03 June 2016

Drop vs Truncate vs Delete in SqlServer

Drop Command: If we want to destroy the existing tables present in the database we use the Drop Command.

DROP TABLE Students

Truncate Command: Removes all rows from a table. TRUNCATE TABLE is functionally the same as the DELETE statement with no WHERE clause specified.

TRUNCATE TABLE Students

The difference between Truncate and Delete is:

  • Truncate table is faster in execution.

  • Truncate will reset the identity function if present on the table to initial value again which will not happen in delete.


 

Url.Action vs Url.RouteUrl

Url.RouteUrl allows you to specify a particular route by name. This will force the usage of that route.

If you have multiple routes with similar parameters the Action method may pick a wrong one - it works based on the order of route definitions. This may take place when your routes have optional parameters.

Lazy loading/Deferred loading in Entity frame work

One of the important functions of Entity Framework is lazy loading. Lazy loading means delaying the loading of related data with its parent object, until you specifically request for it.


you can also turn off lazy loading for a particular property or an entire context. To turn off lazy loading for a particular property, do not make it virtual. To turn off lazy loading for all entities in the context, set its configuration property to false:



public partial class SchoolDBEntities : DbContext
{
    public SchoolDBEntities(): base("name=SchoolDBEntities")
    {
        this.Configuration.LazyLoadingEnabled = false;
    }
}

Below are the advantages of lazy loading:




  • Minimizes start up time of the application.

  • Application consumes less memory because of on-demand loading.

  • Unnecessary database SQL execution is avoided.


The only one disadvantage is that the code becomes complicated. As we need to do checks if the loading is needed or not, there is a slight decrease in performance.


 

Events in the Global.asax file

The Global.asax file, also known as the ASP.NET application file, is an optional file that contains code for responding to application-level events raised by ASP.NET or by HttpModules and session-level events.


The following are some of the important events in the Global.asax file.




  • Application_Init

  • Application_Start

  • Session_Start

  • Application_BeginRequest

  • Application_EndRequest

  • Application_AuthenticateRequest

  • Application_Error

  • Session_End

  • Application_End


The purpose of these event handlers is discussed in this section below.


Application_Init


The Application_Init event is fired when an application initializes the first time.


Application_Start


The Application_Start event is fired the first time when an application starts.


Session_Start


The Session_Start event is fired the first time when a user’s session is started. This typically contains for session initialization logic code.


Application_BeginRequest


The Application_BeginRequest event is fired each time a new request comes in.


Application_EndRequest


The Application_EndRequest event is fired when the application terminates.


Application_AuthenticateRequest


The Application_AuthenticateRequest event indicates that a request is ready to be authenticated. If you are using Forms Authentication, this event can be used to check for the user's roles and rights.


Application_Error


The Application_Error event is fired when an unhandled error occurs within the application.


Session_End


The Session_End Event is fired whenever a single user Session ends or times out.


Application_End


The Application_End event is last event of its kind that is fired when the application ends or times out. It typically contains application cleanup logic.


Application_Start/End events are called only once.


Encrypt ViewState info

View State:
The ViewState is used in retaining values between multiple requests for the same page. Viewstate is stored on page it self in encoded form. When an ASP.NET page is processed, the current state of the page and controls is hashed into a string and saved in the page as a hidden field. If the data is too long for a single field, then ASP.NET performs view state chunking (new in ASP.NET 2.0) to split it across multiple hidden fields. The following code sample demonstrates how view state adds data as a hidden form within a Web page’s HTML:


<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE” value="/wEPDwUKMTIxNDIyOTM0Mg9kFgICAw9kFgICAQ8PFgIeBFRleHQFEzQvNS8yMDA2IDE6Mzc6MTEgUE1kZGROWHn/rt75XF/pMGnqjqHlH66cdw==" />


The ViewState is stored in a hidden field with an ID __VIEWSTATE. This is nothing but a Base64 encoded string, and is not an encrypted string. So it can be easily decoded.


The main reasons for using Base64 encoding are as follows:




  1. Base64 makes a string suitable for HTTP transfers

  2. It makes it a little harder to read


But, after decoding the string (viewstate data), we can see the exact data that is stored inside the ViewState.


Solution


There are two different ways in which you can prevent someone from decrypting ViewState data.




  1. You can make sure that the ViewState information is tamper-proof by using "hash codes". You can do this by adding EnableViewStateMAC=true in your page directive. MAC stands for "Message Authentication Code".


When we use EnableViewStateMac="True", during ViewState save, ASP.NET internally uses a hash code. This hash code is a cryptographically strong checksum. This is added with the ViewState content and stored in a hidden filed. During postback, the checksum data is verified again by ASP.NET. If there is a mismatch, the postback will be rejected.




  1. The second option is to set ViewStateEncryptionMode="Always" with your page directives. This will encrypt the ViewState data.


ViewStateEncryptionMode has three different options that can be set:




  • Always: encrypt the View State always.

  • Auto: encrypt if a control requests for encryption. For this to happen, the control must call thePage.RegisterRequiresViewStateEncryption() method.

  • Never: Never encrypt the ViewState.


<system.web>
<pages enableViewStateMac="true">
                viewStateEncryptionMode="Always">
</pages>
</system.web>

Session State Modes in Asp.Net

Session


Web is stateless, which means a new instance of a web page class is re-created each time the page is posted to the server.


HTTP is a stateless protocol, it can't hold client information on a page. If the user inserts some information and move to the next page, that data will be lost and the user would not be able to retrieve that information.


What do we need here? We need to store information. Session provides a facility to store information on server memory. It can support any type of object to store along with our own custom objects. For every client, session data is stored separately, which means session data is stored on a per client basis


Advantages:




  • It helps maintain user state and data all over the application.

  • It is easy to implement and we can store any kind of object.

  • Stores client data separately.

  • Session is secure and transparent from the user.


Disadvantages:




  • Performance overhead on large volumes of data/user, because session data is stored in server memory.

  • Overhead involved in serializing and de-serializing session data, because in the case of StateServer and SQLServer session modes, we need to serialize the objects before storing them.


Storing and retrieving values from Session


Session["UserName"] = txtUser.Text; //Storing UserName in Session


DataSet _MyDs = (DataSet)Session["DataSet"]; //Retrieving Dataset from Session


Session ID




  • Client hits the web site and information is stored in the session.

  • Server creates a unique session ID for that client and stores it in the Session State Provider.

  • The client requests for some information with the unique session ID from the server.

  • Server looks in the Session Providers and retrieves the serialized data from the state server and type casts the object.


Session Mode and State Provider


In ASP.NET, there are the following session modes available:




  • InProc

  • StateServer

  • SQLServer

  • Custom


When ASP.NET requests for information based on the session ID, the session state and its corresponding provider are responsible for sending the proper information




























Session State ModeState Provider
InProcIn-memory object
StateServerAspnet_state.exe
SQLServerDatabase
CustomCustom provider

Apart from that, there is another mode Off. If we select this option, the session will be disabled for the application.



<system.web>
    <sessionState cookieless="UseCookies" mode="Off"
stateNetworkTimeout="10800" timeout="10"/>
</system.web>

Or from server side: Session.TimeOut=30;


InProc Session Mode


This is the default session mode in ASP.NET. This is the best session mode for web application performance. It can be very helpful for a small web site and where the number of users is very less.


Advantages:




  • It stores session information in the current Application Domain So it is easily and quickly available.

  • There is not requirement of serialization to store data in InProc session mode.

  • Implementation is very easy, similar to using the ViewState.


Disadvantages:




  • If the worker process or application domain/server is recycled/restarted, all session data will be lost.

  • Though it is the fastest, more session data and more users can affect performance.

  • We can't use it in web garden scenarios, and not suitable for web farm scenarios.


StateServer Session Mode


This is also called Out-Proc session mode. StateServer uses a stand-alone Windows Service (aspnet_state.exe) which is independent of IIS and can also be run on a separate server.


This server may run on the same system, but it's outside of the main application. So, if you restart your ASP.NET process, your session data will still be alive. It is useful in web farm and web garden scenarios.


You can start this service from the command prompt just by typing "net start aspnet_state".


This approach has several disadvantages due to serialization of the data before storing in StateServer session mode and de-serialization, it also increases the cost of data access.


For the StateServer setting, we need to specify the stateConnectionString. This will identify the system that is running the state server. By default, stateConnectionString used the IP 127.0.0.1 (localhost) and port 42424. And require stateNetworkTimeout.



<sessionState cookieless="UseCookies" mode="StateServer" 
sqlConnectionString="data source=127.0.0.1; Trusted_Connection=yes"
stateConnectionString="tcpip=127.0.0.1:42424" stateNetworkTimeout="10800"
timeout="10"/>

SQLServer Session Mode


To setup SQL Server, we need these SQL scripts:




  • For installing: InstallSqlState.sql

  • For uninstalling: UninstallSQLState.sql


Advantages:




  • This session mode provides us more secure and reliable session management in ASP.NET.

  • session data is serialized and stored in A SQL Server database (centralized location), is easily accessible from other applications.

  • Provides more security

  • Session data not affected if we restart IIS.

  • Very useful in web farms and web garden scenarios.

  • We can use SQLServer session mode when we need to share session between two different applications.


Disadvantages:




  • Processing is very slow in nature.

  • session storage method is the overhead related with data serialization and de-serialization.

  • As the session data is handled in a different server, we have to take care of SQL Server. It should be always up and running.


Configuration for SQLServer Session Mode


Step 1: From command prompt, go to your Framework version directory. E.g.:c:\windows\microsoft.net\framework\<version>.


Step 2: Run the aspnet_regsql command with the following parameters:
































ParametersDescription
-ssaddAdd support for SQLServer mode session state.
-sstype pP stands for Persisted. It persists the session data on the server.
-SServer name.
-UUser name.
-PPassword.

aspnet_regsql -d <SQLDATABASENAME> -S <SQLSERVERNAME> -U <USERNAME> -P <PASSWORD> -ssadd -sstype c


Step 3: Open SQL Server Management Studio, check if a new database ASPState has been created, and there should be two tables:




  • ASPStateTempApplications

  • ASPStateTempSessions


Custom Session Mode


Custom session gives full control to us to create everything, even the session ID. You can write your own algorithm to generate session IDs.


We can use Custom session mode in the following cases:




  • We want to store session data in a place other than SQL Server.

  • When we have to use an existing table to store session data.

  • When we need to create our own session ID.


What configuration do we need for it?


We need to configure our web.config like this:



<sessionState mode=”Custom” customProvider=”AccessProvider”>
<providers>
       <add name=”AccessProvider” type=”CustomDataType”/>
</providers>
</sessionState>

Advantages:




  • We can use an existing table for storing session data. This is useful when we have to use an existing database.

  • It's not dependent on IIS, so restarting the web server does not have any effect on session data.

  • We can crate our own algorithm for generating session ID.


Disadvantages:




  • Processing of data is very slow.

  • Creating a custom state provider is a low-level task that needs to be handled carefully to ensure security.


It is always recommended to use a third party provider rather than create your own.


Session Event


These are events in the global.asax file of your web application. When a new session initiates, the session_start event is raised, and the Session_End event raised when a session is abandoned or expires.



void Session_Start(object sender, EventArgs e)
{
    // Code that runs when a new session is started
}
void Session_End(object sender, EventArgs e)
{
    // Code that runs when a session ends.
}

Removing Session




























MethodDescription
Session.Remove(strSessionName);Removes an item from the session state collection.
Session.RemoveAll()Removes all items from the session collection.
Session.Clear()Remove all items from session collection. Note: There is no difference between Clear and RemoveAll. RemoveAll()callsClear() internally.
Session.Abandon()Cancels the current session.

Enabling and disabling Session


For performance optimization, we can enable or disable session. We can enable and disable session state in two ways:




  • Page level

  • Application level


Page level


We can disable session state in page level using the EnableSessionState attribute in the Page directive.


<% Page Language="C#" EnableSessionState="False"


This will disable the session activities for that particular page.


The same way, we can make it read-only also. This will permit to access session data but will not allow writing data on session.


<% Page Language="C#" EnableSessionState="ReadOnly"


Application level


Session state can be disabled for the entire web application using the EnableSessionState property inWeb.Config.


<system.web>
<pages enableSessionState="false"/>
</system.web>


Generally we use page level because some pages may not require any session data or may only read session data.


Summary




  • The in-process (InProc) session provider is the fastest because of everything being stored inside memory. Session data will be lost if we restart the web server or if the worker process is recycled. You can use this in small web applications where the number of users is less. Do not use InProc in web farms.

  • In StateServersession mode, session data is maintained by exe. It keeps session data out of the web server. So any issues with the web server does not affect session data. You need to serialized an object before storing data in StateServer session. We can use this safely in web farms.

  • SQLServersession modes store data in SQL Server. We need to provide the connection string. Here we also need to serialize the data before storing it to session. This is very useful in production environments with web farms.

  • We can use a Customprovider for custom data sources or when we need to use an existing table to store session data. We can also create custom session IDs in Custom mode. But it is not recommended to create your own custom provider. It is recommended to use a third party provider.


 

28 May 2016

Types of Stored Procedures in SqlServer

Stored procedure is a precompiled set of one or more SQL statements that is stored on Sql Server. stored Procedures is that they are executed on the server side, to reduce the network traffic.


Types of Stored Procedures




  1. System Defined Stored Procedure


These stored procedures are already defined in Sql Server. These are physically stored in hidden Sql Server. These procedure starts with the sp_ prefix. Hence we don't use this prefix when naming user-defined procedures.  Its manage SQL Server through administrative tasks. These are in master and msdb database. Here is a list of some useful system defined procedure.


































System ProcedureDescription
sp_rename

 
It is used to rename an database object like stored procedure,views,table etc.
sp_changeowner

 
It is used to change the owner of an database object.
sp_helpIt provides details on any database object.
sp_helpdb

 
It provide the details of the databases defined in the Sql Server.
sp_helptext

 
It provides the text of a stored procedure reside in Sql Server
sp_depends

 
It provide the details of all database objects that depends on the specific database object.


  1. Extended Procedure


These are Dynamic-link libraries (DLL's) that are executed outside the SQL Server environment. They are identified by the prefix xp_ Extended procedures provide an interface to external programs for various maintenance activities. These are stored in Master database


Ex. EXEC xp_logininfo 'BUILTIN\Administrators'




  1. User Defined Stored Procedure


These procedures are created by user for own actions and stored in the current database




  1. CLR Stored Procedure


CLR stored procedure are special type of procedure that are based on the CLR (Common Language Runtime) in .net framework. CLR integration of procedure was introduced with SQL Server 2008 and allow for procedure to be coded in one of .NET languages




  1. Temporary Stored procedures


The temporary stored procedures have names prefixed with the # symbol. Temporary stored procedures stored in the tempdb databases. These procedures are automatically dropped when the connection terminates between client and server




  1. Remote Stored Procedures


The remote stored procedures are procedures that are created and stored in databases on remote servers. These remote procedures can be accessed from various servers, provided the users have the appropriate permission


     7. Dynamic Stored Procedures


Sp_executesql can be used to call any statement or batch, not just a stored procedure. Executing SQL statements that are built "on the fly" is referred to asdynamic SQL. You can use either sp_executesql or the EXECUTE command to execute your dynamic SQL statements.



DECLARE @string NVARCHAR(100)  
SELECT @string = 'select * from authors'
EXEC sp_executesql @string --or EXEC(@string)

27 May 2016

Async call

$.ajax({
type: 'POST',
url: "webMethods.asmx/fngetuser",
data: "{'userid':'" + userid + "'}",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
 async: true,
success: function (msg) {
$('[id$="Label1"]').html(msg.d[0]);
$('[id*=ur_]').removeAttr('checked');
},
error: function (msg, a, b) { alert('swe'); }
});


$.getJSON("@Url.Action("GetLat", "Location")", { addr: varaddr },
function (msg) {
if (msg !== null && msg.Lat != 0) { }
else { alert('Invalid address'); }
});

18 May 2016

Variance in Delegates

When you assign a method to a delegate, covariance and contravariance provide flexibility for matching with method signature.


Covariance permits a method to have return type as more derived than that defined in the delegate.


Contravariance permits a method that has parameter types that are less derived than those in the delegate type.


 

26 April 2016

Allow only alphanumeric in textbox using javascript and regular expression

function validate(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
var regex = /^[0-9a-zA-Z\s\b]+$/;
if (!regex.test(key)) {
theEvent.returnValue = false;
if (theEvent.preventDefault)
theEvent.preventDefault();
}
}

<asp:TextBox ID="txtVal" runat="server" onKeyPress="validate(e);"></asp:TextBox>

var re = /^-?\d+$/;
var matches = re.test(args.Value);

function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;

return true;
}

16 March 2016

Extending using Extension methods

static class MyExtensionMethods
{
public static int Negate(this int value)
{
return -value;
}

public static int Multiply(this int value, int multiplier)
{
return value * multiplier;
}
}

static void Main(string[] args)
{
// Passing arguments in extension methods
int i3 = 10;
Console.WriteLine(i3.Multiply(2));
}

14 March 2016

Stored Procedure vs Function














































Stored ProcedureFunction
Return type is not must, Can return zero, single or multiple values or table(s)Return type is must, and it can return one value which is mandatory. UDFs that return tables can be treated as another rowset. This can be used in JOINs with other tables.
SP can have input/output parametersSupport only input parameters
Allow Select as well as DML statements.

Allow Select but not DML statements.


Note: In case of multi-table valued functions it can contain DML statements affecting Table Variables.


Stored procedure can execute function.Function cannot execute stored procedure.
Cannot be the part of Select query as a column.Can be the part of select query as a column
Stored Procedures cannot be embedded in the SQL statements like WHERE/HAVING/SELECTFunctions can embedded in the SQL statements like WHERE/HAVING/SELECT
We can use exception handling using Try....Catch block in SP.We can’t use Try....Catch block in UDF
We can use transactions in SPWe can’t user transaction in UDF
Can have up-to 21000 input parametersUDF can have up-to 1023 input parameters

Why we can't execute stored procedure inside a function?

Answer:

  1. Stored Procedure may contain DML statements.

  2. Function can't contain DML statements.
    So executing Function inside stored procedure will never break rule 1.
    But executing stored procedure inside function may break rule no 2.


Functions are computed values and cannot perform permanent environmental changes to SQL Server (i.e. no INSERT or UPDATE statements allowed). It returns error like “Invalid use of a side-effecting operator 'INSERT' within a function.” So ultimately strict rule is made by Sql team: we can't execute stored procedures inside function.

05 February 2016

Read XML Data for datasource

using System.Xml.Linq;

<?xml version="1.0" encoding="utf-8" ?>
<StatusTypes>
<StatusType Name ="All" value="0"/>
<StatusType Name ="Over-vote" value="1"/>
<StatusType Name ="Mixed Status" value="2"/>
<StatusType Name ="Not Received" value="3"/>
<StatusType Name ="Over Reported" value="4"/>
<StatusType Name ="Under Reported" value="5"/>
<StatusType Name ="In Balance" value="6"/>
</StatusTypes>

string fullName = HttpContext.Current.Server.MapPath(
"~/Modules/Pxy/StatusDataSource.xml");
XDocument doc = XDocument.Load(fullName);
return (from d in doc.Root.Elements("StatusType")
select new KeyValuePair<string,int>( d.Attribute("Name").Value, int.Parse( d.Attribute("value").Value))
).ToList();

statusDataSource DataSource = new statusDataSource();
if (ddlStatus.Items.Count > 0)
ddlStatus.Items.Clear();

ddlStatus.DataSource = null;
foreach (KeyValuePair<string, int> St in DataSource.Status)
ddlStatus.Items.Add(new ListItem(St.Key, St.Value.ToString()));