Tuesday, March 19, 2024

Creating and Using Cookies

 COOKIES

Cookie is a small text file which is created by the client's browser and also stored on the client hard disk by the browser. It does not use server memory. Generally a cookie is used to identify users.

A cookie is a small file that stores user information. Whenever a user makes a request for a page the first time, the server creates a cookie and sends it to the client along with the requested page and the client browser receives that cookie and stores it on the client machine either permanently or temporarily (persistent or non persistence). The next time the user makes a request for the same site, either the same or another page, the browser checks the existence of the cookie for that site in the folder. If the cookie exists it sends a request with the same cookie, else that request is treated as a new request.

Types of Cookies

1. Persistence Cookie: Cookies which you can set an expiry date time are called persistence cookies. Persistence cookies are permanently stored till the time you set.

Example to create persistence cookie

Response.Cookies[“name”].Value = “Vishwa Academy”;
Response.Cookies[“name”].Expires = DateTime.Now.AddMinutes(10);

In above code we use Response.Cookies object for create Cookie.
In above example we have set 10 Minute time for Expire Cookie, we can retrieve cookie values up to 10 minutes, after 10 minutes the cookies automatically expires.

2. Non-Persistence Cookie: Non persistence cookies are not permanently stored on the user client hard disk folder. It maintains user information as long as the user accesses the same browser. When user closes the browser the cookie will be discarded. Non Persistence cookies are useful for public computers.

Example to create non-persistnce cookie

HttpCookiestrname = new HttpCookie(“name”);
strname.Value = “Vishwa Academy”;
Response.Cookies.Add(strname);

Limitation of cookies: The number of cookies allowed is limited and varies according to the browser. Most browsers allow 20 cookies per server in a client's hard disk folder and the size of a cookie is not more than 4096 bytes or 4 KB of data that also includes name and value data. 

Creating Cookies:

 Type 1:

HttpCookie StudentCookies = new HttpCookie("studData");

StudentCookies.Value = TextBox1.Text;

StudentCookies.Expires = DateTime.Now.AddHours(1);

Response.Cookies.Add(StudentCookies);

 Type 2:

Response.Cookies["studData"].Value = TextBox1.Text;
Response.Cookies["studData"].Expires = DateTime.Now.AddDays(1);

 

Type 3:(Writing Multiple values in single cookie)

Response.Cookies["studData"]["RollNumber"] = TextBox1.Text;
Response.Cookies["studData"]["FirstName"] = "Vishwanath";
Response.Cookies["studData"]["MiddleName"] = "D";
Response.Cookies["studData"]["LastName"] = "Panchal";
Response.Cookies["studData"]["TotalMarks"] = "350";

Response.Cookies["studData"].Expires = DateTime.Now.AddMinutes(5);

 

Reading Cookies:

 

For Type 1 and Type 2

 string str1 = Request.Cookies["StudentCookies"].Value;

 

For Type 3

 string str1;

str1= Request.Cookies["StudentCookies"]["RollNumber"];
str1= str1 + " " + Request.Cookies["StudentCookies"]["FirstName"];
str1= str1 + " " + Request.Cookies["StudentCookies"]["MiddleName"];
str1= str1 + " " + Request.Cookies["StudentCookies"]["LastName"];
str1= str1 + " " + Request.Cookies["StudentCookies"]["TotalMarks"];
Label1.Text = str1; 

 

Example:

To Create Cookie ASPX File:

 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="CreateCookie.aspx.cs" Inherits="CreateCookie" %>

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 <html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        Enter Data: <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

        <br />

        <asp:Button ID="btnCreate" runat="server" Text="CreateCookeis"

            onclick="btnCreate_Click" />

    </div>

    </form>

</body>

</html>

 

To Create Cookie ASPX.CS File:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

 public partial class CreateCookie : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

     }

    protected void btnCreate_Click(object sender, EventArgs e)

    {

        //Create Cookies

        Response.Cookies["mydata"].Value = TextBox1.Text;

        Response.Cookies["mydata"].Expires = DateTime.Now.AddMinutes(10);

        Response.Redirect("http://localhost:50618/WebSite18/ReadCookies.aspx");

    }

}

 

To Read Cookie ASPX File:

 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="ReadCookies.aspx.cs" Inherits="ReadCookies" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 <html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <asp:Label ID="Label1" runat="server" ></asp:Label>

    </div>

    </form>

</body>

</html>

 

To Read Cookie ASPX.CS File:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

 public partial class ReadCookies : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

        string str;

        str = Request.Cookies["mydata"].Value;

        Label1.Text = "Your Cookie Data is " + str;

    }

}

 

Thursday, March 24, 2022

Creating and Using Web Services

What is Web Service? 

A Web Service is a reusable piece of code used to communicate among different Applications. Once a web service is created and hosted on the server in the internet it can be used by any application developed.

A file with .asmx extensions is an ASP.NET Web Service file that provides communication between two objects over the internet using the Simple Object Access Protocol (SOAP).

Creating and Using Web Services

Steps to create web service:

Step 1: Open .Net Visual Studio, create an Empty web site.

Step 2: Right click on App location in Solution Explorer and Select “Add New Item”, from add new item dialog box select and add “WebService” file with “.asmx” extension.
This file contains some program line as given below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {

    public WebService () {

        //Uncomment the following line if using designed components
        //InitializeComponent();
    }

    [WebMethod]
    public string HelloWorld() {
        return "Hello World";
    }
   
}

From above line of code the part 

    [WebMethod]
    public string HelloWorld() {
        return "Hello World";
    }
Containing the methods used as web services. You can add your own methods, like

[WebMethod]
    public int MyCalc(int x, int y)
    {
        return x * y;
    }
Accordingly go on adding methods as per the need of our web application.

Step 3: To test these newly added methods just execute the project, it will run in web browser, and the following output will be observed. After Executing it will display the names of web services.





To execute these services just click on the name of the web service. The output screen of “MyCalc” web service can be shown as

As MyCalc service requires two parameters, it will ask for two values.

Making the use of web service in the Web Application:

Step1: To make use of this Web Service add an Web Form (i.e. Default.aspx page) in the project.

Step 2: Right click in solution explorer, select “add web reference”, this will open Add Web Reference dialog box, from the dialog box, Click on “Select Web Services in this solution” as shown in the figure.



Step 3: From the dialog box above click on the Add Reference button. This will add “.disco” and “.wsdl” files in the application.
(Note: WSDL: WSDL stands for Web Service Description Language. It is written in XML and also specifies the location of the service and the methods used.
 
XML grammar describes details such as:-
1. Where we can find the Web Service (its URI)?
2. What are the methods and properties that service supports?
3. Data type support.
4. Supported protocols

The DISCO (is the abbreviated form of Discovery) file typically points to a WSDL(Web Service Description Language) source that in turn points to the actual Web Service.When one searches for the Web Services, it will go to the DISCO which gives actual information for the particular Web services. It has .disco file extension. It is an XML document which contains link to another resources.)

 
Step 4: Now add two textbox controls and a button control, and on the click event of button control add the following line of code in code behind model of the Default.aspx file.

        localhost.WebService wc = new localhost.WebService();
        int a = int.Parse(TextBox1.Text);
        int b = int.Parse(TextBox2.Text);
        int c = wc.MyCalc(a, b);
        Label1.Text = "Answer is " + c.ToString();