Monday, 28 July 2014

How to Use Web Services in ASP.NET application

Web Services is service which is available over the web. A Web Service is used to implement the specific functionality to Execute the business logic codes of  the application . This technologies allowed  to developer to create a specific component once (make only logic code) so that they can share it across the multiple application by multiple developers. Before the Web Services , we were using two technology which are given below:-
  • Component object model (COM)
  • Distributed Component object model (DCOM)
This technology is helpful to use one application to another application.However ,there were some fundamental difficulties in using these components. One such difficulty was that these components needed to be physically distributed and Explicitly registered on each client machine.
Today,Web Services overcome these difficulties as they can be shared (distributed) among multiple website without the need to install them on each individual client machines.
There are some advantages of web services over COM and DCOM Technologies.
  • Web Services are very simple in use.
  • Web Services do not carry any state information,so that multiple request can be processed simultaneously.
  • Web Services are enforcing trusted connection between the server and the client.
  • Web Services can easily use in caching feature of asp.net.
  • With the help of Web Services,we can easily integrate asp.net web application with third party systems.
  • Web Services is useful in security purpose as ssl and window authentication of asp.net application.
Examples of Web Services 
There are some example of Web Services which are given below:-
     1. ) Suppose we want to host a website(asp.net,php ,java etc) on the server that calculate the simple interest.For this, we can use a web service to calculate the simple interest.In this scenario,we do not need to write  codes  in the website for calculating the simple interest. We do not put calculating simple interest code inside the website,for this we can create a Web Service which can calculate the simple interest.Here Our website performs two things,
  • Take input from client side (end user) using Text Box.
  • Display the output to the client end ( Calculating the simple interest by the Web Service).
     2. )  Preparing the pay slip for employee by a company
     3. )  Display the weather report on the  website
     4. ) Calculate the simple interest and income tax of the banks and income tax departments.
     5. ) Display the New News (Notification) Headlines on the website.

Real Life Example of Web Services
I think almost every people know about TV and TV channels. There are many company which manufactures TV as
  • Sony
  • Samsung
  • LG
  • Vediocon 
  • Others
There are some service providers (TV Channels) which provide the services as
  • Airtel Digital
  • Dish
  • Reliance Digital
  • Tata sky
  • Vediocon d2h
  • Sun direct
  • others
Similarly we can compare TV --to-> Website and TV Channels (services) --to->Web Services.
Here peoples are using different TV and Channels to use the services.They are not facing any type of problems by using this different TV and TV Channels.Same concepts are used in website and web services also. Similarly we can use different website (asp.net ,php, java, etc) and different web services for performing any task. We can use any web services in different platform.Web services are used XML language for communication to the website .You already know XML is platform independent .
There are some standard used by web services in ASP.NET which are given below:-
     1. )  HTTP :- It is known as  Hyper Text Transfer Protocol .All Internet protocols follow some rules.It is a connection less protocol.This protocol is used to transmit the data between web services and it users (website),Such as HTTP-GET and HTTP-POST.A web service can use any remote procedure call (RPC) protocols,such as DCOM (Distributed component object model ) or Common object Request Broker Architecture (CORBA),to transmit data HTTP-GET and HTTP-POST protocols used by the web services to transmit the data over the Internet.By default HTTP-GET and HTTP-POST bindings are not enabled to Remote web service invocation.
  2. )  XML :- It is known as Extensible Markup Language.It is a standard used by all web services to transfer the data.It is platform independent.So that e can use web services on any website without facing platform compatibility problem.
Note:-You can define an XML web service as a unit of code that can be invoked via HTTP Requests.
3. )  WSDL :- It is Known as Web Service Description Language.It is a standard used by the web service to describe what a web service can do.
WSDL is a XML-based language that defines web services.Every web service holds WSDL document that specifies the location of the web service and list of all the services that the web service can perform. A WSDL document is a simple XML document that containing different XML elements to define  a web service. I will show you all these standard when i will implement web service in below section of this page.
There are some elements in WSDL Document which are given below:-
  • Type :- It describe the all data types used in web service.
  • Message :- It is describe the message which are used to communicate from one point to another when data is passed by the web service.
  • Binding : - It describes the all protocols which are used by the web service.
  • Port Type :- It describes the links of input and output message.
  • Port :- It describe the address for binding the specific client port (end user port).
  • Service :- It describes all services such as binding URL ,Port etc. 
4. )  SOAP :-It is known as Simple object access protocol.It is a standard used by the web service to send the response (or request) message to the application (website).It is completely XML based protocol.SOAP provides a complete set of rules for messaging.One of the great advantage of using  a SOAP message is that ,it is not restricted to any one operating system.
5. )  DISCO.exe :- It is known as the web service discovery tool,It is used for publishing and discovering web services.This tool is helpful to discover URL of all the web services located on a web server and creates a list of them in a file,called DISCO file (with .disco extension).
Note:- This file mostly can be accessed by clients (users) to know about these kinds of services an organization provides.
6. )  UDDI :- It is known as Universal Description,Discovery and Integration .UDDI includes four types of services.
  • Web service
  • Business
  • Binding
  • Specifications
UDDI is a central Directory where web services offered by different organization are published.It is Built into the .net platform.It is platform Independent.
Features of UDDI
  • It stores the information of web services.
  • It uses W3C & IETF standards (ex. XML,HTTP,DNS etc.).
  • It uses SOAP for communication.
  • It uses WSDL to describe interfaces to web services.
Advantages of Web Services 
  • It enhance the security feature of any website.
  • It takes less processing time to calculate the logic code.
  • It can easily handle multiple request at a time simultaneously.
  • It is compatible to communicate with different platform.
  • It follows XML ,HTTP Standards.
In this tutorial i am going to implement web service at different ways in .NET Application.Which are given below:-
How to call web services from the client end
There are some steps to implement web service concepts in asp.net application.In this application ,i have create a web service which can calculate Addition,Subtraction, Multiplication, Division and modulus operations.When user put two inputs on the website using Text Box then this web service calculate the operations(Addition,Subtraction........) and send output to the website(client end),after that website display that output in script or Label.
Step -1 First open your visual studio --> File -->New -->Select ASP.NET Empty Website and select Visual C# from left window -->OK-->Now Open Solution Explorer-->Now Right click on website --> Add New Items --> Select web service & Visual C# --> Write your web service's name (calculationservices.asmx) --> click Add button as shown below:-


create_service
Step -2 Now Write the C# logic codes for calculation under [WebMethod] as given below:-
01using System;
02using System.Collections.Generic;
03using System.Linq;
04using System.Web;
05using System.Web.Services;
06 
07/// <summary>
08/// Summary description for calculationservices
09/// </summary>
10[WebService(Namespace = "http://tempuri.org/")]
11[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
12// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
13// [System.Web.Script.Services.ScriptService]
14public class calculationservices : System.Web.Services.WebService {
15 
16    public calculationservices () {
17 
18        //Uncomment the following line if using designed components
19        //InitializeComponent();
20    }
21    [WebMethod]
22    public string msdotnet()
23    {
24        return "welcome to www.msdotnet.co.in";
25    }
26    [WebMethod]
27    public int add(int i, int j)
28    {
29        return i + j;
30    }
31 
32    [WebMethod]
33    public int substract(int i, int j)
34    {
35        return i - j;
36    }
37    [WebMethod]
38    public int multiply(int i, int j)
39    {
40        return i * j;
41    }
42 
43    [WebMethod]
44    public int Division(int i, int j)
45    {
46        return i / j;
47    }
48 
49    [WebMethod]
50    public int modulos(int i, int j)
51    {
52        return i % j;
53    }
54     
55}
Step -3 Now Run this web services (calculationservices.asmx) -->Now copy the Browser's URL as shown below:-


run_service

Note :- You can paste this URL on Notepad,MS Word etc. so that you can use this URL ,when we will configure the web service on website.

Step -4 Now you can calculate your services(Addition,Subtraction,Multiplication,Division and modulus ) -->click Division link or others as show below:-


calculation


Step -5 Now click Invoke Button -->you will see ,output will show in XML Document format using SOAP Protocol.


SOAP _out

Note :- You can calculate (test) all result  using this method, your service is working or not.
Step -6  Now open your visual studio again--> File -->New -->Select ASP.NET Empty Website and select Visual C# from left window -->OK-->Now Open Solution Explorer-->Now Right click on website --> Add New Web Form (webservice.aspx) --> Drag and drop Label ,Text Box and Button control on the Form as shown below:- 


Web Form

Note :-
  • web service extension --> .asmx
  • Web Form Extension -->.aspx
  • Disco File Extension -->.disco
Step -7 Now open your solution Explorer -->Right Click on your application (website) -->Add Web Reference -->Paste web service URL here (Which i have already copied in step 3) -->Click Next Arrow as show below:-


URL

Note :- You can copy the URL by Run the web service again.

Step -8 Now Write the web service'Name (myservice) -->Click Add Reference Button.
as shown below :-
webservice_name

Step -9 You will see ,there are some files are added in your application(when we complete the web service configuration) as shown below:-


we_files

Note:- See above image carefully:-

  • Include a Name space in webservice.aspx.cs file as Using myservice;
  • Create object of calculationservices in webservice.aspx.cs file as calculationservices obj = new calculationservices();.
Step -10 Now write the c# codes on button click in webservice.aspx.cs file as given below:-
01using System;
02using System.Web;
03using System.Web.UI;
04using System.Web.UI.WebControls;
05using myservices;
06public partial class webservice : System.Web.UI.Page
07{
08    protected void Page_Load(object sender, EventArgs e)
09    {
10 
11    }
12    protected void Button1_Click(object sender, EventArgs e)
13    {
14        calculationservices obj = new calculationservices();
15        //you can use below without include Namespace(using myservice;)
16        //myservices.calculationservices obj = new myservices.calculationservices();
17        int sum =obj.add(Convert.ToInt32(TextBox1.Text), Convert.ToInt32(TextBox2.Text));
18        Label1.Text = "Your addition Result =" + sum.ToString();
19        //you can use below script instead of Label control
20        //Response.Write("<script> alert(" + sum + ")</script>");
21    }
22    protected void Button2_Click(object sender, EventArgs e)
23    {
24        calculationservices obj = new calculationservices();
25        int sub = obj.substract(Convert.ToInt32(TextBox1.Text), Convert.ToInt32(TextBox2.Text));
26        Label1.Text = "Your Substraction Result =" +sub.ToString();
27        //you can use below script instead of Label1 control
28        //Response.Write("<script> alert(" + sub + ")</script>");
29    }
30    protected void Button3_Click(object sender, EventArgs e)
31    {
32        calculationservices obj = new calculationservices();
33        int mult = obj.multiply(Convert.ToInt32(TextBox1.Text), Convert.ToInt32(TextBox2.Text));
34        //Response.Write("<script> alert(" + mult + ")</script>");
35        Label1.Text = "Your Multiplication Result =" +mult.ToString();
36    }
37    protected void Button4_Click(object sender, EventArgs e)
38    {
39        calculationservices obj = new calculationservices();
40        int div = obj.Division(Convert.ToInt32(TextBox1.Text), Convert.ToInt32(TextBox2.Text));
41        Label1.Text = "Your Divison Result =" + div.ToString();
42        //you can use below script instead of Label1 control
43        //Response.Write("<script> alert(" + div + ")</script>");
44    }
45    protected void Button5_Click(object sender, EventArgs e)
46    {
47        calculationservices obj = new calculationservices();
48        int mod = obj.modulos(Convert.ToInt32(TextBox1.Text), Convert.ToInt32(TextBox2.Text));
49        Label1.Text = "Your Modulos Result =" + mod.ToString();
50        //you can use below script instead of Label control
51        //Response.Write("<script> alert(" + mod + ")</script>");
52    }
53}
Step -11 Now Run the Application (webservice.aspx) (press F5) -->Enter the Text Box Fields -->press each button( Add, Subtract......... )as shown below:-
web service _output

Thursday, 24 July 2014

To Date IS Always Greater Than From Date

<head>
<title>jQuery UI Datepicker - Select a Date Range</title>
<link type="text/css" href="c ss/ui-lightness/jquery-ui-1.8.19.custom.css" rel="stylesheet" />
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.19.custom.min.js"></script>
<script type="text/javascript">
$(function() {
var dates = $("#txtFrom, #txtTo").datepicker({
minDate: '0',
maxDate: '+7D',
onSelect: function(selectedDate) {
var option = this.id == "txtFrom" ? "minDate" : "maxDate",
instance = $(this).data("datepicker"),
date = $.datepicker.parseDate(
instance.settings.dateFormat ||
$.datepicker._defaults.dateFormat,
selectedDate, instance.settings);
dates.not(this).datepicker("option", option, date);
},dateFormat: "dd/mm/yy"
});
});
</script>
<style type="text/css">
.ui-datepicker { font-size:6pt !important}
</style>
</head>




<body>
<form id="form1" runat="server">
<div class="demo">
<label for="from">From</label>
<asp:TextBox ID="txtFrom" runat="server"/>
<label for="to">to</label>
<asp:TextBox ID="txtTo" runat="server"/>
</div>
</form>
</body>

Wednesday, 16 July 2014

State Management in ASP.NET

As we know Web pages are based on the HTTP Protocol which is a stateless protocol, means that there is no information about the request, such as where they are coming from i.e. whether the request is from the same client or from a new client. Since the page is created each time, the page is requested then destroyed. So we can say that the state is not maintained between client requests by default.
ASP.NET developers use various available technologies for State Management. We can classify them as client side state management or server side state management.

statemgmt1.gif
CLIENT SIDE STATE MANAGEMENT:

View State:

ViewState is an approach to saving data for the user. Because of the stateless nature of web pages, regular page member variables will not maintain their values across postbacks. ViewState is the mechanism that allows state values to be preserved across page postbacks and by default, EnableViewState property will be set to true. In a nutsheell, ViewState:
  • Stores values per control by key name, like a Hashtable.
  • Tracks changes to a View State value's initial state.
  • Serializes and Deserializes saved data into a hidden form field on the client.
  • Automatically restores View State data on postbacks.

    statemgmt2.gif

Sample:
//To Save Information in View State
ViewState.Add ("NickName", "Dolly");
//Retrieving View state
String strNickName = ViewState ["NickName"];

Here is a simple example of using the "ViewState" property to carry values between postbacks.
Code Example:

public int SomeInteger {
    get {
        object o = ViewState["SomeInteger"];
        if (o != null) return (int)o;
        return 0;
        //a default    }
    set { ViewState["SomeInteger"] = value; }
}


Control State:

The purpose of the control state repository is to cache data necessary for a control to properly function. ControlState is essentially a private ViewState for your control only, and it is not affected when ViewState is turned off. ControlState is used to store small amounts of critical information. Heavy usage of ControlState can impact the performance of application because it involves serialization and deserialization for its functioning.

There are two methods you have to implement in your custom control.
  • Load Control State
  • Save Control State

    statemgmt3.gif
Code Example:
public class ControlStateWebControl : Control{    #region Members
    private string _strStateToSave;
    #endregion
    #region
Methods
    protected override void OnInit(EventArgs e)
    {
        Page.RegisterRequiresControlState(this);
        base.OnInit(e);
    }
    protected override object SaveControlState()
    {
        return _strStateToSave;
    }
    protected override void LoadControlState(object state)
    {
        if (state != null)
        {
            _strStateToSave = state.ToString();
        }
    }
 
    #endregion}Hidden Fields:
A Hidden control is the control which does not render anything on the web page at client browser but can be used to store some information on the web page which can be used on the page. Hidden fields are used to store data at the page level. These fields are not rendered by the browser, rather it's just like a standard control for which you can set its properties. If you use hidden fields, it is best to store only small amounts of frequently changed data on the client.

statemgmt4.gif
Sample:
//Declaring a hidden variableprotected HtmlInputHidden hidNickName;
//Populating hidden variablehidNickName.Value = "Page No 1";
//Retrieving value stored in hidden field.string str = hidNickName.Value;
Code Example:
protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)|
        Label1.Text = string.Format("Clicked {0} times", HiddenField1.Value);
}
protected void Button1_Click(object sender, EventArgs e)
{
    HiddenField1.Value = (Convert.ToInt32(HiddenField1.Value) + 1).ToString();

    Label1.Text = string.Format("Clicked {0} times", HiddenField1.Value);
}


Cookies:
A cookie is a small amount of data which is either stored at client side in text file or in memory of the client browser session. Cookies are always sent with the request to the web server and information can be retrieved from the cookies at the web server. Every time a user visits a website, cookies are retrieved from the user machine and help identify the user.

Cookies are useful for storing small amounts of frequently changed information on the client. The information is sent with the request to the server.

statemgmt5.gif
Sample:
 // Creating a cookiemyCookie.Values.Add("muffin", "chocolate");
myCookie.Values.Add("babka", "cinnamon");
// Adding Cookie to CollectionResponse.Cookies.Add(myCookie);
// Getting Values stored in a cookieResponse.Write(myCookie["babka"].ToString());
// Setting cookie pathmyCookie.Path = "/forums";
// Setting domain for a cookiemyCookie.Domain = "forums.geekpedia.com";
// Deleting a cookiemyCookie.Expires = DateTime.Now.AddDays(-1);
Code Example:
//Storing value in cookieHttpCookie cookie = new HttpCookie("NickName");
cookie.Value = "David";
Request.Cookies.Add(cookie);
//Retrieving value in cookieif (Request.Cookies.Count > 0 && Request.Cookies["NickName"] != null)
         lblNickName.Text = "Welcome" + Request.Cookies["NickName"].ToString();
else         lblNickName.Text = "Welcome Guest";

Query String:
A Query string is used to pass the values or information form one page to another page. They are passed along with URL in clear text. Query strings provide a simple but limited way of maintaining some state information. When surfing the internet you should have seen weird internet addresses such as:

http://www.localhost.com/Webform2.aspx?name=ABC&lastName=XYZ

This HTML address uses a QueryString property to pass values between pages.

statemgmt6.gif
Syntax:
Request.QueryString(variable)[(index)|.Count]
Code Example:
using System;using System.Web.UI;
public partial class _Default : Page{
    protected void Page_Load(object sender, EventArgs e)
    {
        string v = Request.QueryString["param"];
        if (v != null)
        {
            Response.Write("param is ");
            Response.Write(v);
        }
        string x = Request.QueryString["id"];
        if (x != null)
        {
            Response.Write("   id detected");
        }
    }
}

SERVER SIDE STATE MANAGEMENT:

Application State:
Application State is used to store information which is shared among users of the ASP.Net web application. Application state is stored in the memory of the windows process which is processing user requests on the web server. Application state is useful in storing a small amount of often-used data. If application state is used for such data instead of frequent trips to the database, then it increases the response time/performance of the web application.

In classic ASP, an application object is used to store connection strings. It's a great place to store data that changes infrequently.

statemgmt7.gif
Code Example 1:
//Stroing information in application statelock (this)
{
       Application["NickName"] = "Nipun";
}
//Retrieving value from application statelock (this)
{
      string str = Application["NickName"].ToString();
}

Code Example 2:
 protected void Page_Load(object sender, EventArgs e)
    {
// Code that runs on page load
        Application["LoginID"] = "Nipun";
        Application["DomainName"] = "www.nipun.com";
    }


Session State:
ASP.NET Session state provides a place to store values that will persist across page requests. Values stored in Session are stored on the server and will remain in memory until they are explicitly removed or until the Session expires. It is defined as the period of time that a unique user interacts with a Web application. Session state is a collection of objects, tied to a session stored on a server.

statemgmt8.gif
Sample:
//Storing informaton in session stateSession["NickName"] = "ABC";
//Retrieving information from session statestring str = Session["NickName"];

 
Code Example:
 object sessionObject = Session["someObject"];if (sessionObject != null)
{
 myLabel.Text = sessionObject.ToString();
}


Profile Properties:
ASP.NET provides a feature called profile properties, which allows you to store user-specific data. It is similar to session state, except that unlike session state, the profile data is not lost when a user's session expires. The profile properties feature uses an ASP.NET profile, which is stored in a persistent format and associated with an individual user. In this each user has its own profile object.

statemgmt9.gif
 
Sample:
<profile>
  <properties>
    <add item="item name" />
  </properties>
</profile>
 
Code Example:
 <authentication mode="Windows" /> 
      <profile> 
      <properties> 
     <add name="FirstName"/> 
     <add name="LastName"/> 
     <add name="Age"/> 
     <add name="City"/> 
      </properties> 
   </profile> 

Saturday, 12 July 2014

Common Table Expressions(CTE) in SQL SERVER And Usess of CTE

It’s a headache for developers to write or read a complex SQL query using a number of Joins. Complex SQL statements can be made easier to understand and maintainable in the form of CTE or Common Table expressions. In this post, I will try to cover some of the benefits that we get when working with CTE.
When dealing with sub-queries, it is often required that you need to select a part of the data from a sub query or even join data from a query with some other tables. In that case, either you have an option to name your sub-queries with an alias or to use it directly. Gradually your requirement is getting more and more complex and your query would look unmaintainable at any time. CTE allows you to define the subquery at once, name it using an alias and later call the same data using the alias just like what you do with a normal table. CTE is standard ANSI SQL standard.

SELECT * FROM  (
        SELECT A.Address, E.Name, E.Age From Address A
        Inner join Employee E on E.EID = A.EID) T
WHERE T.Age > 50
ORDER BY T.NAME


The query looks really a mess. Even if I need to write something that wraps around the entire query, it would gradually become unreadable. CTE allows you to generate Tables beforehand and use it later when we actually bind the data into the output. 

With T(Address, Name, Age)  --Column names for Temporary table
AS
(
SELECT A.Address, E.Name, E.Age from Address A
INNER JOIN EMP E ON E.EID = A.EID
)
SELECT * FROM T  --SELECT or USE CTE temporary Table
WHERE T.Age > 50
ORDER BY T.NAME
 
 
 Yes as you can see, the second query is much more readable using CTE. 
You can specify as many query expressions as you want and the final 
query which will output the data to the external environment will 
eventually get reference to all of them. 
 
 
With T1(Address, Name, Age)  --Column names for Temporary table
AS
(
SELECT A.Address, E.Name, E.Age from Address A
INNER JOIN EMP E ON E.EID = A.EID
),
T2(Name, Desig)
AS
(
SELECT NAME, DESIG FROM Designation)
SELECT T1.*, T2.Desig FROM T1  --SELECT or USE CTE temporary Table
WHERE T1.Age > 50 AND T1.Name = T2.Name
ORDER BY T1.NAME 
 
 
So the queries are separated using commas. So basically you can pass as many queries as you want and these queries will act as a subqueries, getting you the data and name it as a temporary table in the query.
According to the syntax, the CTE starts with a With clause. You can specify the column names in braces, but it is not mandatory.


SQL SERVER – Simple Example of Recursive CTE

Recursive is the process in which the query executes itself. It is used to get results based on the output of base query. We can use CTE as Recursive CTE (Common Table Expression)
Here, the result of CTE is repeatedly used to get the final resultset. The following example will explain in detail where I am using AdventureWorks database and try to find hierarchy of Managers and Employees.

USE AdventureWorks
GO
WITH Emp_CTE AS (
SELECT EmployeeID, ContactID, LoginID, ManagerID, Title, BirthDate
FROM HumanResources.Employee
WHERE ManagerID IS NULL
UNION ALL
SELECT e.EmployeeID, e.ContactID, e.LoginID, e.ManagerID, e.Title, e.BirthDate
FROM HumanResources.Employee e
INNER JOIN Emp_CTE ecte ON ecte.EmployeeID = e.ManagerID
)
SELECT *
FROM Emp_CTE
GO
 
In the above example Emp_CTE is a Common Expression Table, the base record for the CTE is derived by the first sql query before UNION ALL. The result of the query gives you the EmployeeID which don’t have ManagerID.
Second query after UNION ALL is executed repeatedly to get results and it will continue until it returns no rows. For above e.g. Result will have EmployeeIDs which have ManagerID (ie, EmployeeID of the first result).  This is obtained by joining CTE result with Employee table on columns EmployeeID of CTE with ManagerID of table Employee.
This process is recursive and will continue till there is no ManagerID who doesn’t have EmployeeID.