Saturday, 10 November 2012

Insert, Select, Update and Delete Records in a Single Stored Procedure Using SQL Server



Sometimes there is a need to insert, select, update and delete records from a table using a single Stored Procedure instead of creating separate Stored Procedures for each operation.
Suppose I have one .aspx web page in which I need a to insert, select, update and delete records. To do that instead of creating four Stored Procedures to perform these tasks I will create a single Stored Procedure to satisfy my requirements and I will access it in code behind according to the action performed by the end user on a button click.
I have written this article specially focusing on newcomers and anyone new to SQL Stored Procedures so let us start with a basic introduction.
What is Stored Procedure?

A Stored Procedure is a group of logical SQL statements to perform a specific task such as insert, select, update and delete operations on a table and so on which is stored in a SQL database.
Creating a Stored Procedure
Before creating a Stored Procedure, we will create one table named employee in the SQL database which looks as in the following image.
I have set the primary key on the id column for the Identy specification.
 

 


 



Now we have a table to perform these operations. Now let us start to create the Stored Procedure.
The Stored Procedure is created using the keyword Create Procedure followed by the procedure name. Let us create the Stored Prcedure named EmpEntry as given below.
create Procedure EmpEntry
(
 --variable  declareations

@Action Varchar (10),                             --to perform operation according to string passed to this varible such as Insert,update,delete,select    
@id
int=null,                                   --id to perform specific task
@Fname Varchar (50)=null,                     -- for FirstName
@MName Varchar (50)=null,                    -- for MName
@Lname Varchar (50)=null                      -- for LastName
)
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
---exec EmpEntry @Action='delete' ,@Fname='S',@MName='R',@Lname='M',@id='13'  --added by vithal wadje on 18-10-2012 for Csharp contribution
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
as
Begin
  SET NOCOUNT ON;
If @Action='Insert'   --used to insert records
Begin
Insert Into
 employee (FirstName,MName,LastName)values(@Fname,@MName,@Lname)
End  
else if @Action='Select'   --used to Select records
Begin
select *from
employee
end

else if
@Action='Update'  --used to update records
Begin
 update employee set FirstName=@Fname,MName=@MName,LastName=@Lname where id=@id
 End
 Else If
@Action='delete'  --used to delete records
 Begin
 delete from employee where id=@id
 end
 End

In the above Stored Procedure throught comments I have clearly explained which block is used for which purpose, so I have briefly explained it again. I have used @Action variable and assigned the string to them and according to the parameter passed to the Stored Procedure the particular block will be executed because I have kept these blocks or conditions in nested If else if conditional statements.
 "The most important thing is that I have assigned null to each variable to avoid the effect on the parameter passed to the Stored Procedure because we are passing a different number of parameters but not the same number of parameters to the Stored Procedure to perform these tasks." 
After creating this Stored Procedure, now let us use it.
To execute the Stored Procedure EmpEntry that we created we need to use the keyword exec followed by the procedure name and the parameter list. I have explained how to use it below.
Inserting the Records into the Employee table that we created with the EmpEntry procedure; see:
exec EmpEntry @Action='Insert' ,@Fname='vithal',@MName='G',@Lname='Wadje'
After running this query the records will be inserted into the table employee. To see the records inserted into the table the run following query:
select * from employee

the output will be as shown in the following:

 

 

Their are two records you have seen because I have executed the procedure two times.
  • Selecting Records From table
exec EmpEntry @Action='Select'
The output will be as follows:
 

 


 
  • Updating Records of table
  •  
exec EmpEntry @Action='Update' ,@Fname='Manish',@MName='Kapil',@Lname='Sawant',@id=2
After executing the above query the id number 2 record will be updated in the table.
To see, run the query: select * from employee
The output will be as shown in the following:

  • Deleting the Records from table
exec EmpEntry @Action='delete' ,@id=2
After executing the above query the id number 2 record will be deleted from the table.
To see, run the query: select * from employee
The output will be as shown in the following:

 

Thursday, 27 September 2012

Concurrency in WCF

What are the different concurreny modes available in WCF?
1. Single
2. Reentrant
3. Multiple


Are WCF services protected from concurrent access by default?
Yes, WCF services are protected from concurrent access by default, as the concurrency mode of a WCF service is set to Single by default.


Explain Single Concurrency Mode?
In a Single concurrency mode only one request is processed by the same service instance. A lock is acquired while a request is processed by a service instance. Other threads, if any, are queued, until they timeout. Once the lock is released when the current request completes, next thread in the queue can then access the objects. 
What effect does Single concurreny mode setting have on PerCall, PerSession and Singleton services?
PerCall services and Single Concurreny mode : A new service instance is allocated for each thread. Here, concurrency is not an issue and Single mode setting has no impact on the throughput and concurrent calls can be processed.

PerSession services and Single Concurreny mode : Service instances are protected against multithreaded clients. Single mode impacts throughput of single client but multiple clients can get through and concurrent calls can be processed.

Singleton services and Single Concurreny mode : Service instances are protected against any concurrent calls. Single concurrency mode impacts throughput of singleton. Multiple threads and clients cannot get through and no concurrent calls can be processed.
  


Explain Reentrant Concurrency Mode?
Reentrant concurrency mode is useful when services issue callbacks to clients, If callback operations are not one-way. Services release the acquired lock upon exit to make the callback and another thread is able to acquire the lock. In this case, return from callback will queue.


What effect does Reentrant concurreny mode setting have on PerCall, PerSession and Singleton services?
PerCall services and Reentrant Concurreny mode : In a case where PerCall services may need reentrancy, if we set the concurrency mode to Single, deadlock is guaranteed, where as if it is In Reentrant mode, we will have no problem.

PerSession services and Reentrant Concurreny mode : PerSession services allow a multithreaded client to access the service instance

Singleton services and Reentrant Concurreny mode : Singleton services allow any threads to access the service instance


What is the effect of Multiple concurrency mode on PerSession services with multithreaded clients?
PerSession services with multithreaded clients can have increased throughput, with Multiple concurrency mode, as no locks are acquired when requests are being processed by a service instance. However, care should be taken to protect shared resources.


What are different .NET multithreading techniques available to protect a shared resource?
1. Monitor
2. Mutex
3. Semaphore
4. ReadWriterLock
5. Interlocked


What are the factors that can influence overall throughput for a service, when multiple concurrency mode is enabled?
1. Instancing mode
2. Concurrency mode
3. Throttling behavior


What is ServiceThrottleBehavior?
ServiceThrottleBehavior provides several settings for throughput control, as shown below.

MaxConcurrentCalls: Maximum concurrent requests allowed. The default is 16 .

MaxConcurrentInstances: Maximum concurrent service instances allowed . The default is int.MaxValue.

MaxConcurrentSessions: Maximum concurrent active sessions. This includes transport, reliable, secure, and application sessions. The default is 10.

Instance Modes In WCF

What are the instancing modes available in wcf?
1. Percall
2. PerSession
3. Single

What are the advantages of using Percall instancing mode in WCF?
In a Percall instance mode, a new service object is created for each call. The following are the advantages and Disadvantages of Percall instance mode.

Advantages:
Less memory consumption
Service instances are freed
Concurrency is not an issue
PerCall services increase overall throughput

Disadvantages:
State not maintained between calls

What are the four session types available in WCF?
Transport session
Reliable sessions
Secure sessions
Application sessions

What are the advantages and disadvantages of using PerSession instancing mode in WCF?
A new service object gets created for each client/proxy. The following are the advantages and Disadvantages of PerSession instance mode.

Advantages:
State maintained by service instance

Disadvantages:
Less throughput, greater memory consumption
Concurrency issues for multithreaded clients

Name a few bindings that can support PerSession instancing mode?
1. NetTcpBinding
2. NetNamedPipeBinding
3. WSHttpBinding
4. WSFederationHttpBinding
5. WSDualHttpBinding

What is the default Application Session timeout in WCF?
Session lifetime lasts 10 minutes by default, for Application Session.

What are the advantages and disadvantages of using Single, Instancing mode in WCF?
In a single instancing mode, a single service object is created for all calls from all clients and sessions This type of wcf service is also called as singleton service. The following are the advantages and Disadvantages of Single instance mode.

Advantages:
State maintained by service instance

Disadvantages:
Least throughput
Potentially greater memory consumption
Concurrency issues

What are the general guidelines for choosing an instancing mode?
In general, for scalability and throughput, prefer to use PerCall services where ever possible. Use PerSession services only when necessary, but keep in mind the overhead of sessions and session timeouts. Try to avoid singletons almost always.Singleton services, could be useful on client machines for shared functionality. These are only general guidelines, and your selection depends on what you are trying to achieve.
 

Message Pattern In WCF

What are the different message exchanging patterns available in WCF?
There are 3 main different message exchanging patterns available in WCF.
1. Request-Reply - In the request-reply pattern, a client application sends a message to a WCF service and then waits for a reply. This is the classic and most commonly used message exchange pattern in WCF.
2. One-Way - In a one way message exchange pattern no response is sent back, even if there is an exception. In the one-way message exchange pattern, a client application sends a message to a WCF service but the service does not send a reply message to the client. You can use this pattern when a client requests the service take an action but does not need to wait for a reply.
3. Duplex - In the request/reply and one-way message exchange patterns, only the client can initiate communication. In the duplex pattern, both the client and the service can initiate communication. The client calls a method of the service. The service can then use a client callback to call a method in the client. You can use this pattern when you want the service to send a notification or alert to the client after the client has called the service.

What is the default message exchange pattern used in WCF?
Request/Reply

How do you setup a one way operation?
Set OperationContractAttribute's IsOneWay property to true. An example is shown below.



What is MTOM?
MTOM stands for Message Transmission Optimization Mechanism and is an Interoperable standard that reduces the overhead of large binary data transfera. Removes bloat and processing overhead of base64 encoded data. Improves overall message transfer performance.

Method OverLoading In WCF

Can you overload methods in a WCF service?

Yes, it is possible to overload methods in a WCF service, but the names of the exposed operation contracts must be unique. To achieve this we can use the Name property of OperationContractAttribute. Let us understand this with an example.

If I have the WCF service designed as shown below, the service compiles without any issues. When we try to run the service, we will get InvalidOperationException.






o correct this we can use the Name property of OperationContractAttribute as shown below. After this change, the service works fine both at compile and runtime.







Forms Authentication in Asp,Net

What is the advantage of using Forms authentication?
The advantage of using Forms authentication is that users do not have to be member of a domain-based network to have access to your application. Another advantage is that many Web applications, particularly commercial sites where customers order products, want to have access to user information. Forms authentication makes these types of applications easier to create.

List the steps to use Forms authentication in a web application?
1.Set the authentication mode in Web.config to Forms.
2.Create a Web form to collect logon information.
3.Create a file or database to store user names and passwords.
4.Write code to add new users to the user file or database.
5.Write code to authenticate users against the user file or database.

What happens when someone accesses a Web application that uses Forms authentication?
When someone accesses a Web application that uses Forms authentication, ASP.NET displays the logon Web form specified in Web.config. Once a user is authorized, ASP.NET issues an authorization certificate in the form of a cookie that persists for an amount of time specified by the authentication settings in Web.config.




What is the difference between Windows authentication and Forms authentication?
The difference between Windows authentication and Forms authentication is that in Forms authentication your application performs all the authentication and authorization tasks. You must create Web forms and write code to collect user names and passwords and to check those items against a list of authorized users.

What is the use of mode attribute in authentication element in a web.config file?
You use the mode attribute to specify the type of authentication your web application is using. Set the mode attribute to forms to enable Forms authentication.

What is the use of name attribute and loginUrl attribute of a forms element in a web.config file?
Name attribute of forms element is used to set the name of the cookie in which to store the user’s credential. The default is .authaspx. If more than one application on the server is using Forms authentication, you need to specify a unique cookie name for each application.
loginUrl attribute of forms element is used to set the name of the Web form to display if the user has not already been authenticated. If omitted, the default is Default.aspx.

What is protection attribute in a forms element used for in web.config file?
The protection attribute of a forms element of web.config file is used for setting how ASP.NET protects the authentication cookie stored on the user’s machine. The default is All, which performs encryption and data validation. Other possible settings are Encryption, Validation, and None.

What is timeout attribute in a forms element used for in web.config file?
Timeout attribute is used to set the number of minutes the authentication cookie persists on the user’s machine. The default is 30, indicating 30 minutes. ASP.NET renews the cookie automatically if it receives a request from the user and more than half of the allotted time has expired.

In which namespace the FormsAuthentication class is present?
System.Web.Security namespace

Which method checks the user name and password against the user list found in the credentials element of Web.config?
The FormsAuthentication class’s Authenticate method checks the user name and password against the user list found in the credentials element of Web.config.

Which method can be used to remove forms authentication cookie?
Use the signout() method of FormsAuthentication class to sign out when the user has finished with the application or when you want to remove the authentication cookie from his or her machine. For example, the following code ends the user’s access to an application and requires him or her to sign back in to regain access
FormsAuthentication.SignOut();

What is the advantage of Authenticating Users with a Database?
You can authenticate users based on a list in Web.config. The FormsAuthentication class’s Authenticate method is set up to read from web.config file automatically. That’s fine if user names and passwords are created and maintained by a system administrator, but if you allow users to create their own user names or change their passwords, you’ll need to store that information outside the Web.config file. This is because changing Web.config at run time causes the Web application to restart, which resets any Application state and Session state variables used by the application.

What are the advantages of storing user names and passwords in a database rather than a file?
You can store user names and passwords in any type of file; however, using a database has the following significant advantages:
1. User names can be used as primary keys to store other information about the user.
2. Databases can provide high performance for accessing user names and passwords.
3. Adding, modifying, and accessing records are standardized through SQL.

Can you encrypt user names and passwords stored in a file or a database?
Yes, you encrypt user names and passwords stored in a file or a database. You can encrypt them using the FormsAuthentication class’s HashPasswordForStoringInConfigFile method. This method uses the SHA1 or MD5 algorithms to encrypt data, as shown below:
Password = FormsAuthentication.HashPasswordForStoringInConfigFile(Password, "SHA1");

Can you change authentication type in a subfolder's web.config file?
Authentication type (Windows, Forms, or Passport) can be set only at the application’s root folder. To change authentication type in a subfolder's web.config file, you must create a new Web application project and application starting point for that subfolder.

How can you control access to subfolders in a web application?
The authorization settings in the Web.config file apply hierarchically within the folder structure of a Web application. For instance, you might want to allow all users access to the root folder of a Web application but restrict access to Web forms (and tasks) available from a subfolder. To do this, set the authentication type in the root folder’s Web.config file, and then use the authorization element in the subfolder’s Web.config file to restrict access.

Security -Windows Authentication

What is the difference between Authentication and Authorization?
Authentication is the process of identifying users. Authorization is the process of granting access to those users based on identity. Together, authentication and authorization provide the means to keeping your Web application secure from intruders.

What is Anonymous access?
Anonymous access is the way most public Web sites work. Sites containing public information allow anyone to see that information, so they don’t authenticate users. ASP.NET Web applications provide anonymous access to resources on the server by impersonation. Impersonation is the process of assigning a user account to an unknown user.

What is the account that is associated with Anonymous access?
By default, the anonymous access account is named IUSER_machinename. You use that account to control anonymous users’ access to resources on the server.

What is the default user account under which an ASP.NET web application run on a web server?
Under the default settings, ASP.NET uses the ASPNET account to run the Web application. This means that if the application attempts to perform any tasks that are not included in the ASPNET account’s privileges, a security exception will occur and access will be denied.

How do you restrict the access of anonymous users?
You restrict the access of anonymous users by setting Windows file permissions. To be secure, your server must use the Microsoft Windows NT file system (NTFS). The earlier FAT or FAT32 file systems do not provide file-level security.
What are the 3 major ways to authenticate and authorize users within an ASP.NET Web application?
Windows authentication :
Identifies and authorizes users based on the server’s user list. Access to resources on the server is then granted or denied based on the user account’s privileges. This works the same way as regular Windows network security.
Forms authentication : Directs users to a logon Web form that collects user name and password information, and then authenticates the user against a user list or database that the application maintains.
Passport authentication : Directs new users to a site hosted by Microsoft so that they can register a single user name and password that will authorize their access to multiple Web sites. Existing users are prompted for their Microsoft Passport user name and password, which the application then authenticates from the Passport user list.

What is the namespace where all security related classes are present?
System.Web.Security

What type of authentication can be used for Public Internet Web application?
Anonymous access. This is the common access method for most Web sites. No logon is required, and you secure restricted resources using NTFS file permissions.

What type of authentication can be used for Intranet Web application?
Windows authentication. Windows authentication authenticates network users through the domain controller. Network users have access to Web application resources as determined by their user privileges on the server.

What type of authentication can be used for Private corporate Web application?
Windows authentication. Corporate users can access the Web application using their corporate network user names and passwords. User accounts are administered using the Windows network security tools.

What type of authentication can be used for Commercial Web application?
Forms authentication. Applications that need to collect shipping and billing information should implement Forms authentication to gather and store customer information.

What type of authentication can be used for Multiple commercial Web applications?
Passport authentication. Passport authentication allows users to sign in once through a central authority. The user’s identity is then available to any application using the Passport SDK. Customer information is maintained in a Passport profile, rather than in a local database.

Can you use ASP.NET Authentication with HTM and HTML Files?
The three ASP.NET authentication modes apply to files that are part of the Web application. That includes Web forms (.aspx), modules (.asax), and other resources that are processed through the Web application’s executable. It does not automatically include HTML pages (.htm or .html). Those pages are handled by Internet Information Services (IIS), rather than ASP.NET. If you want to authenticate users who access HTML pages from within your Web application using Windows, Forms, or Passport authentication modes, you must map those files to the ASP.NET executable.

Wednesday, 26 September 2012

What is a DLL Hell In .NET?

1. I have 2 applications, A1 and A2 installed on my computer.

2. Both of these applications use shared assembly shared.dll

3. Now, I have a latest version of Application - A2 available on the internet.

4. I download the latest version of A2 and install it on my machine.

5. This new installation has over written Shared.dll, which is also used by Application - A1.

6. Application - A2 works fine, but A1 fails to work, because the newly installed Shared.dll is not backward compatible.

So, DLL HELL is a problem where one application will install a new version of the shared component that is not backward compatible with the version already on the machine, causing all the other existing applications that rely on the shared component to break. With .NET versioning we donot have DLL HELL problem any more.

How is the Dll Problem Solved In .Net? 

In dot net all the shared assemblies are usually in the GAC. GAC stands for Global Assembly Cache. The path for GAC is C:\[OperatingSystemDirectory]\assembly. For example on my computer the path is C:\WINDOWS\assembly. The image below shows the shared assemblies in the GAC.



Only strong named assemblies can be copied into GAC. Strong named assemblies in .NET has 4 pieces in its name as listed below.
1. Simple Textual Name
2. Version Number
3. Culture
4. Public Key Token

All these four pieces put together, is called as the fully qualified name of the assembly. In the GAC image above Accessibility assembly has a version of 2.0.0.0.

 Now consider the example below:
1. I have 2 applications, Application - A1 and Application - A2 which relies on the shared assembly Accessibility.dll (Version 2.0.0.0) as shown in the image below.



2. Now, I have a latest version of Application - A2 available on the internet.

3. I download the latest version of A2 and install it on my machine.
4. This new installation copies a newer version of Accessibility.dll into the GAC with version 3.0.0.0.
5. So, in the GAC we now have 2 versions of Accessibility.dll.
6. Application - A1 continues to use Accessibility.dll (version 2.0.0.0) and Application - A2 uses Accessibility.dll (version 3.0.0.0)
7. So, now the assemblies are able to reside side by side in the GAC. For this reason dot net assemblies are also said to be supporting side by side execution.

Monday, 10 September 2012

Genarating Sample report using Crystal reports in .net





Introduction:

In this article I will explain how to create crystal reports example in asp.net.

Description:

Crystal Report is standard reporting tool for visual studio by using these we can display reports regarding employee details and display charts etc and crystal reports need minimal coding to display result. 

To implement crystal reports first design the table in database and give name UserInfomation

ColumnName
DataType
UserId
Int(set identity property=true)
UserName
varchar(50)
FirstName
Varchar(50)
LastName
varchar(50)
Location
varchar(50)

After completion of table creation enter some dummy data because we need to use that data to populate reports.

Now Open visual studio and create new website after that right click on your website and select Add new item in that select Crystal Report and click Add
 
After that add crystal report then it will prompt Crystal Report Gallery window in that select blank solution and click OK


A blank report will create in our application now click on CrystalReports menu under that select Database under that select Database Expert
 
After click on Database Expert now Database Expert wizard will open in that select Create New Section >> select OLE DB (ADO) >> in that click on + sign of OLE DB (ADO)


Now select Microsoft OLE DB Provider for SQL Server and click Next (Here we can select SQL Native client option also but sometimes during deployment if servers not contains this native client it will throw error).
 

Now enter SQL Server name, username, password and required database and click Next


After enter credentials for your required database click Next then click Finish (Here for my database I didn’t set any credentials for that reason I didn’t enter userid and password details don’t get confused).

After click Finish now our database loaded in OLEDB (ADO) section >> select your database >> select dbo >> select required tables


Now open tables in that select required table and move to selected tables section and click OK



After that Database Fields in Field Explorer populated with our required data table now drag and drop the required fields from data table to reports Details section

https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjZQiUCd-QVYc8Jb53-RxnZ3OGDUoE8WPlXyWiMTN9o3AGSEXMgPrpzMOJKdV7EuX02UOPjIFlImnOESyups8C760VBTwlvoZBeF5l3it5FWxIq8iakIXZWVNN0U_VJTkG1INILJCw8p_g/s640/FieldExplorer.png
Now open your Default.aspx page drag and drop CrystalReportViewer control from Reporting tab.


Now select CrystalReportViewer and click on smart tag in right hand side and Choose new Report Source


Whenever we click on New report source one window will open in that select crystal report for Report Source from the available reports in dropdownlist and click OK.


After assign available report to CrystalReportViewer control check your code that would be like this

<%@ Register Assembly="CrystalDecisions.Web, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304" Namespace="CrystalDecisions.Web" TagPrefix="CR" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Crystal Report Sample</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server" AutoDataBind="True" ReportSourceID="CrystalReportSource1" />
<CR:CrystalReportSource ID="CrystalReportSource1" runat="server">
<Report FileName="CrystalReport.rpt">
</Report>
</CR:CrystalReportSource>
</div>
</form>
</body>
</html>
Now run your application your report will be like this


In case your report prompt window for UserName and password before we access data in that situation we need to set those details in code behind instead of assign crystal report to CrystalReportViewer control

Drag and drop CrystalReportViewer control click on right side smart tag of your CrystalReportViewer control and uncheck EnableDatabaseLogonPrompt


Our aspx code will be like this

<%@ Register Assembly="CrystalDecisions.Web, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304" Namespace="CrystalDecisions.Web" TagPrefix="CR" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Crystal Report Sample</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server" AutoDataBind="True" ReportSourceID="CrystalReportSource1" />
<CR:CrystalReportSource ID="CrystalReportSource1" runat="server">
<Report FileName="CrystalReport.rpt">
</Report>
</CR:CrystalReportSource>
</div>
</form>
</body>
</html>
Now Open your code behind file and set database connection settings and assign reports to the control before that first add following namespaces


using System;
using CrystalDecisions.CrystalReports.Engine;
After add namespaces write the following code in page load event

C# code


protected void Page_Load(object sender, EventArgs e)
{
ReportDocument reportdocument = new ReportDocument();
reportdocument.Load(Server.MapPath("CrystalReport.rpt"));
reportdocument.SetDatabaseLogon("username","password","SureshDasari","MySampleDB");
CrystalReportViewer1.ReportSource = reportdocument;
}