Chapter 06




ASP.NET State Management

Nje sfide me vete ne zhvillimin plikacioneve eshte gjurmimi i gjendjes se perdoruesit (user state), ose te dhenat e tij, qe kane te bejne me aplikacionin qe ndertojme. Kjo vlen si per aplikacionet WEB dhe per ato desktop. Shpesh duhet te dime informacion rreth perdoruesve, veprimeve dhe kerkesave me te cilet ata punojne, dhe rreth te dhenave te cilat ata i besojne aplikacionit.   Keto te dhena te gjendjes varjojne nga thjesht informacion mbi rolin e perdoruesit ne aplikacion , deri tek te dhenat e nje transaksioni i cili (si per shembull nje shopping cart) e te dhenat qe ne mbajme (transaction history). Duhet menaxhuar ne menyre efektive gjendja(state) e perdoruesit ne site per ti mundesuar perdoruesit nje experience te mire ne faqe dhe per te fituar respektin e tij ne lidhje me aplikacionin.

ASP.NET mundeson disa teknika per mbajtjen e informacionit te gjendjes ne lidhje me klientin. Ketu perfshihet:

-          view state ASP.NET perdor view state  per te gjetur vlerat e kontrolleve ndermjet page requests. Gjithashtu lejon shtimin e vlerave tona ne view state.

-          control state Control state lejon tem bash informacion mbi nje control qe nuk eshte pjese e view state. Nese e kemi disabled view state per nje control ne pageatehere mund te perdoret control state.

-          hidden fields Si view state, HTML hidden fields mbajne vlera pa i shfaqur ato ne browserin e perdoruesit. Keto te dhena dergohen perseri ne server dhe jane disponibel  kur procesohet nje forme.

-          cookies Cookies mbajne vlera ne browserin e perdoruesit dhe perdoruesi I dergon ne server me cdo page request qe ben ne po ate server. Cookies jane menyra me e mire per te mbajtur shume te dhena ne faqe te ndryshme te te gjithe Web site-it.

-          Query strings Query strings jane vlerat qe mbahen ne fund te URL. Keto jane vizibel ne browser-in e perdoruesit.

 

Menaxhimi i state ne anen e klientit ka disa benefite

-          Pershkallezim te mire (nuk ruhet ne server vlera per cdo perdorues te lidhur ne te njejten kohe)

-          Suporton multiple Web server

 

Menaxhimi i state ne anen e serverit ka disa benefite

-          Siguri me te larte

-          Redukton bandwidthin (dergimi nga klienti ne server e me rradhe te informacionit te madh sjell probleme)

 

Ne anen e klientit per te siguruar te dhenat shenojme ne krye te faqes si me poshte: 

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

Default" ViewStateEncryptionMode="Always"%>

 

Leximi dhe Shkrimi i Custom View State Data 

//writing to view state

this.ViewState.Add("MyData", "some data value");

//read from view state

string myData = (string)ViewState["MyData"];

---------

//check if ViewState object exists, and display it if it does

if (ViewState["lastVisit"] != null)

Label1.Text = ((DateTime)ViewState["lastVisit"]).ToString();

else

Label1.Text = "lastVisit ViewState not defined.";

//define the ViewState object for the next page view

ViewState["lastVisit"] = DateTime.Now;

 

Leximi dhe Shkrimi i Cookies

 //check if cookie exists, and display it if it does

if (Request.Cookies["lastVisit"] != null)

//encode the cookie in case the cookie contains client-side script

   Label1.Text = Server.HtmlEncode(Request.Cookies["lastVisit"].Value);

else

   Label1.Text = "No value defined";           

//define the cookie for the next visit

   Response.Cookies["lastVisit"].Value = DateTime.Now.ToString();

   Response.Cookies["lastVisit"].Expires = DateTime.Now.AddDays(1);

 

Ruajtja e me teper se nje vlere 

Response.Cookies["info"]["visit"] = DateTime.Now.ToString();

Response.Cookies["info"]["firstName"] = "Gena";

Response.Cookies["info"]["border"] = "blue";

Response.Cookies["info"].Expires = DateTime.Now.AddDays(1);

 

Query Strings 

Tek WebForm1.aspx vendosim kodin si me poshte:

<asp:HyperLink ID="HyperLink1" runat="server"  NavigateUrl="~/WebForm2.aspx?user=gena&lang=al&page=webform1">

    Kliko per te shkuar tek shembulli tjeter</asp:HyperLink>

 

Tek  WebForm2.aspx  vendosim:

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

 

Tek  WebForm2.aspx.cs  vendosim:

Label1.Text =

            "User: " + Server.HtmlEncode(Request.QueryString["user"]) +

            ", <br/>Lang: " + Server.HtmlEncode(Request.QueryString["lang"]) +

            ", <br/>Page: " + Server.HtmlEncode(Request.QueryString["page"]);

 

 

ASP.NET Application Life Cycle 

1.      Nje perdorues ben request nje faqe ne Site

2.      Kerkesa vendoset ne nje pipeline.

3.      Krijohet nje instance e ApplicationManager class. Instanca e ApplicationManager perfaqeson domainin.

4.      Krijohet  nje  instance e HostingEnvironment class. Kjo klase mundeson akses ne pjeset e brendshme te mjedisit si per shembull folderat/direktorite.

5.      Krijohen objektet HttpContext, HttpRequest, dhe HttpResponse.

6.      Krijohet  nje  instance e HttpApplication.

7.      Se fundmi requestet procesohen nga HttpApplication pipeline.

 

Application Events

 

-          Application_Start

-          Application_End

-          Application_Error

-          Application_LogRequest

-          Application_PostLogRequest

 

<%@ Application Language="C#" %>

<script runat="server">

void Application_Start(object sender, EventArgs e)

{

    Application["UsersOnline"] = 0;

}

void Session_Start(object sender, EventArgs e)

{

    Application.Lock();

    Application["UsersOnline"] = (int)Application["UsersOnline"] + 1;

    Application.UnLock();

}

void Session_End(object sender, EventArgs e)

{

    Application.Lock();

    Application["UsersOnline"] = (int)Application["UsersOnline"] - 1;

    Application.UnLock();

}

</script>

 

Session Read Write

 

protected void Page_Load(object sender, EventArgs e)

        {

            Session["lastVisit"] = DateTime.Now.ToString();

        }

protected void Button1_Click(object sender, EventArgs e)

        {

            if (Session["lastVisit"] != null)

            {

                Label1.Text = Session["lastVisit"].ToString();

            }

            else

            {

                Label1.Text = "Session does not have last visit information.";

            }

        }

 

MASTERPAGE

 

Per te perfshire kod ne Page ne pozicionet qe duam ne MasterPage realizojme hapat e meposhtme:

1.      Shtojme tek MasterPage nje ContentPlaceHolder dhe i vendosim nje Id:

 

<asp:ContentPlaceHolder ID="MainContent" runat="server"/>

 

2.      Ne Page ne vendosim Contentin qe do mbivendoset templates se MasterPage:

 <asp:Content  ID="Content1" ContentPlaceHolderID="MainContent" runat="server">

</ asp:Content  >

 

 

Lidhja me Master Page Properties nga Content Pages

 

Perfshijme ne Site.Master kodin e meposhtem:

 

public String UserId

        {

            get { return (String)Session["UserId"]; }

            set { Session["UserId"] = value; }

        }

 

Ne WebForm5.aspx shtojme poshte @Page kodin e meposhtem:

<%@ MasterType VirtualPath="~/SiteMaster.master" %>

 

Dhe ne PlaceHolder:

<asp:Login ID="Login1" runat="server">

</asp:Login>

 

Me pas tek  WebForm5.aspx.cs shtojme:

Login1.UserName = Master.UserId;

 

Referencim i Controleve ne Master Page

 

Label MyLabelBrand = (Label)Master.FindControl("LabelBrand");

            MyLabelBrand.Text = "GENA'S PAGE"; 

 

THEMES 

Per te shtuar nje teme sic tregohet edhe ne figure duhet te klikoni me te djathten mbi emrin e projektit ne SolutionExplorer -> Add -> Add  ASP.NET Folder -> Theme.

 

 

Krijojme nje folder me emrin qe deshirojme per theme-en qe krijuam.

Ne kete folder shtojme me pas Skins, Style Sheets dhe image qe do te na duhen.

Per te vendosur themen qe ne duam ne faqen tone mjafton te shtojme tek tagu i Page:

Theme="ThemeGena"

 

Ose ne menyre dinamike me ane te programimit si me poshte:

 

protected void Page_PreInit(object sender, EventArgs e)

        {

            switch (Request.QueryString["theme"])

            {

                case "gena":

                Page.Theme = "ThemeGena";

                break;

                case "gena2":

                Page.Theme = "ThemeGena2";

                break;

            }

        }

 


ASP.NET AJAX  DHE  CLIENT-SIDE SCRIPTING

 

Perdorime dhe benefite te ASP.NET AJAX

 

-          Update i pjesshem i Page

-          Procesimi ne Client-side

-          UI te ngjashme me desktop

-          Gjurmim i progresit

-          Performance e permiresuar

-          Thirrje e webserviseve nga ana e klientit

-          Suport cross-browser dhe cross-platform

 

Shembull

 

1.      Krijojme nje faqe se hapni Default.aspx.

2.      Shtojme proceduren  e meposhtme ne bazen NorthWind:

 

CREATE PROCEDURE InsertEmployee

@EmployeeID      int OUTPUT,

@FirstName       varchar(10),

@LastName        varchar(20),

@TitleOfCourtesy varchar(25)

AS

INSERT INTO Employees

  (TitleOfCourtesy, LastName, FirstName, HireDate)

  VALUES (@TitleOfCourtesy, @LastName, @FirstName, GETDATE());

SET @EmployeeID = @@IDENTITY

GO

 

3.       Hap  Default.aspx ne Source view. Shto ScriptManager control ne body nga AJAX Extensions tab tek Toolbox.

 

<asp:ScriptManager ID="ScriptManager1" runat="server">

</asp:ScriptManager>

 

4.      Shtojme nje text per te paraqitur informacion ne lidhje me faqen dhe nje vije horizontale per te bere ndarjen :

 

<div style="font-size: large;"> Stafi</div>

<hr />

 

5.      Shto nje AJAX UpdatePanel control.

6.      Shko tek  Design view shto nje GridView control ne UpdatePanel.

7.      Bejme Bind te GridView  me tabelen Emplyees dhe stringun ta quajme NorthwindConnectionString .

8.      Selekto Enable Paging check box.

9.      Jepi Run aplikacionit dhe shikoni Default.aspx page ne browser. Kliko faqet e GridView dhe kur kalon nga njera faqe te tjetra nuk behet rifreskim i faqes por vetem i te dhenave, kjo ndodh per shkak te UpdatePanel control.

10.   Me pas shtojme nje forme per te hedhur te dhena te reja ne baze:


<div style="margin: 20px 0px 20px 40px">

Last Name<br />

    <asp:TextBox ID="TextBoxLastName" runat="server" Width="200"></asp:TextBox><br />

    First Name<br />

    <asp:TextBox ID="TextBoxFirstName" runat="server" Width="200"></asp:TextBox><br />

    Title of Courtesy<br />

    <asp:TextBox ID="TextBoxTitle" runat="server" Width="200"></asp:TextBox><br />

    <asp:Button ID="ButtonEnter" runat="server" Text="Enter" style="margin-top: 15px"

            onclick="ButtonEnter_Click" />

</div>

 

Me pas shtojme eventin e klikimit per butonin sic eshte deklaruar ( onclick  = “ButtonEnter_Click” ).  Ky buton do te therrase procedure e deklaruar me siper ne klikim te tij:

 

protected void ButtonEnter_Click(object sender, EventArgs e)

        {

                System.Threading.Thread.Sleep(2000);

                String cnnStr=                     System.Web.Configuration.WebConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;

                SqlConnection cnn = new SqlConnection(cnnStr);

                SqlCommand cmd = new SqlCommand("InsertEmployee", cnn);

                cmd.CommandType = CommandType.StoredProcedure;

                SqlParameter LastName = new SqlParameter("@LastName", SqlDbType.VarChar);

                LastName.Value = TextBoxLastName.Text;

                cmd.Parameters.Add(LastName);

                SqlParameter FirstName = new SqlParameter("@FirstName", SqlDbType.VarChar);

                FirstName.Value = TextBoxFirstName.Text;

                cmd.Parameters.Add(FirstName);

                SqlParameter TitleOfCourtesy = new SqlParameter("@TitleOfCourtesy", SqlDbType.VarChar);

                TitleOfCourtesy.Value = TextBoxTitle.Text;

                cmd.Parameters.Add(TitleOfCourtesy);

                SqlParameter EmpId = new SqlParameter("@EmployeeID", SqlDbType.VarChar);

                EmpId.Value = 1;

                cmd.Parameters.Add(EmpId);

                cnn.Open();

                cmd.ExecuteNonQuery();

                GridView1.DataBind();

        }

 

11.  Per te mos patur refresh ne faqe vendoset :

 

<asp:UpdatePanel ID="UpdatePanelVendors" runat="server">

<Triggers>

<asp:AsyncPostBackTrigger ControlID="ButtonEnter" EventName="Click" />

</Triggers>

<ContentTemplate>

 

12.  Per te pare progresin e faqes vendoset kodi i meposhtem:

 

<asp:UpdateProgress ID="UpdateProgress1" runat="server">

<ProgressTemplate>

<div style="margin-top: 20px; font-size: larger; color: Green">

Processing, please wait ...

</div>

</ProgressTemplate>

</asp:UpdateProgress>

 

13.  Per te pare efektshem veprimin e kodit me siper ne klikim te butonit shtoni: 

System.Threading.Thread.Sleep(2000);

 

 

GridView Row Selection

 

Shembull se si selektohet nje gride me Orders dhe ne klikim te cdo rreshti shfaqet informacioni I detajeve te atij Order-i:

 

       

<asp:gridview ID="GridOrders" runat="server" DataKeyNames="orderID"

        AutoGenerateColumns="False"  DataSourceID="SqlGW" style="margin-top: 0px" >

        <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />

          <RowStyle BackColor="#FFFBD6" ForeColor="#333333"  />

          <AlternatingRowStyle BackColor="White" />

        <Columns>

            <asp:BoundField DataField="orderID" HeaderText="Id"  />

            <asp:CommandField ShowSelectButton="True" ButtonType="Button" SelectText="Select" />

            <asp:BoundField DataField="shipname" HeaderText="Emri" />

            <asp:BoundField DataField="requireddate" HeaderText="Required Date" DataFormatString="{0:MM/dd/yy}" />

        </Columns>

        </asp:gridview>

 

    <asp:SqlDataSource

            ID="SqlGW" runat="server"

            ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"          

            SelectCommand="SELECT top(10) orders.orderID,requireddate ,shipname

            FROM [dbo].[orders] ">

    </asp:SqlDataSource>

    <br /><br /><hr /><br /><br />

    <asp:SqlDataSource ID="ordDetails" runat="server"

         ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"

         SelectCommand="SELECT orderID,unitprice,quantity FROM [order details]

                where [order details].orderID=@orderID ">

                <SelectParameters>

                    <asp:ControlParameter ControlID="gridOrders" Name="orderID"

                     PropertyName="SelectedDataKey.Values[&quot;orderID&quot;]" />

                </SelectParameters>

    </asp:SqlDataSource>

 

 

    <asp:gridview ID="GridView2" runat="server"

        AutoGenerateColumns="False"  DataSourceID="ordDetails" style="margin-top: 0px" >

        <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />

          <RowStyle BackColor="#FFFBD6" ForeColor="#333333"  />

          <AlternatingRowStyle BackColor="White" />

        <Columns>

            <asp:BoundField DataField="orderID" HeaderText="Id"  />

            <asp:BoundField DataField="unitprice" HeaderText="Cmim" />

            <asp:BoundField DataField="quantity" HeaderText="Sasi" />

        </Columns>

        </asp:gridview>