Chapter 07


 

ASP.NET AJAX  DHE  CLIENT-SIDE SCRIPTING (Vazhdim) 


Shembull 1

Qellimi i shembullit te pare eshte krijimi i nje komponenti klient ne AJAX. Ky component nuk ka nje User Interface, ai do te perdoret per t’i shtuar funksionalitetet  faqeve qe e perdorin.  Konkretisht krijohet nje web site ne ASP.NET dhe shtohet nje komponent klient ne nje file JavaScript. Ky komponent percakton nje metode per vleresimin e fortesise se passwordit.

 

1. Hap Visual Studio  dhe krijo nje  ASP.NET Web site te quajtur  AjaxEnabled  .

2. Shto nje JavaScript file ne kete site. Kliko me te djathten tek Web site dhe zgjidh Add New Item. Ne ate Add New Item dialog boxin qe do te shfaqet, zgjidh JScript File. Emertojeni file-in PasswordStrengthComponent.js.

3. Hapni JavaScript file-in qe krijuat. Ne krye te faqes shtoni kodin: Type.registerNamespace("AjaxEnabled");

4. Me pas percaktoni nje konstruktor per klasen ne JavaScript si funksion. Si me poshte:

//create constructor

AjaxEnabled.PasswordStrengthComponent = function()

{

AjaxEnabled.PasswordStrengthComponent.initializeBase(this);

}

5. Hapi tjeter duhet  per te percaktuar pjeset e tjera te klases. Krijojme nje prototip dhe ne kete prototip deklarojme nje funksion te quajtur  returnPasswordStrength qe merr si parameter kete password, kontrollon vleren e tij dhe kthen vleren e fortesise se passwordit.  Me poshte kodi:

 

//define class

AjaxEnabled.PasswordStrengthComponent.prototype = {

initialize: function() {

//add custom initialization here

AjaxEnabled.PasswordStrengthComponent.callBaseMethod(this, 'initialize');

},

returnPasswordStrength: function(password)

{

var strPass = new String(password.toString());

if (strPass.length < 5) {

return "Weak";

}

else {

if (strPass.length < 8) {

return "Medium";

}

else {

return "Strong";

}

}

},

dispose: function() {

//add custom dispose actions here

AjaxEnabled.PasswordStrengthComponent.callBaseMethod(this, 'dispose');

}

}

6. Ne klase shtojme nje kod per ta regjistruar ate me ane te Microsoft AJAX Library  duke thirrur registerClass method te atij komponenti. Kjo klase duhet te trashegoje Sys.Component class nga librarite. Kodi i meposhtem tregon nje shembull se si lajmerohet me notification aplikacioni se skripti eshte loaduar plotesisht:

//register class as a Sys.Component

AjaxEnabled.PasswordStrengthComponent.registerClass('AjaxEnabled.PasswordStrengthComponent',  Sys.Component);

//notify script loaded

if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();

 

7. Hapim Default.aspx ne source view

8. Shtoni nje ScriptManager control nga Toolbox ne faqe. Ne kete ScriptManager control, shtoni nje reference drejt PasswordStrengthComponent.js file te krijuar me siper. Gjithashtu atributin EnableCdn="true", per te mundesuar ekzekutimin e kodit. Me poshte kodi:

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

<Scripts>

<asp:ScriptReference Path="~/PasswordStrengthComponent.js" />

</Scripts>

</asp:ScriptManager>

 

9. Me pas shtoni controls ne faqe per te krijuar nje pamje ten je user login form.

<div style="font-size: large; font-weight: bold">User Login</div>

<hr />

<br />

User Name:

<br />

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

<br />

Password:

<br />

<asp:TextBox ID="TextBoxPassword" runat="server"

TextMode="Password" Width="200"></asp:TextBox>

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

<br />

<input id="Button1" type="button" value="Submit" />

 

10. Hapi pasardhes sherben per te percaktuar  JavaScriptin ne faqe meqe do punoje me komponentin e ndodhur ne anen e klientit. Do te krijojme nje event qe ekzekutohet kur perdoruesi te beje nje veprim key press ne textboxin e Password-it. Sa here qe behet nje key press nga ana e perdoruesit duhet te perdoret metoda per te kontrolluar inputin e vendosur. Rezultatin e shfaqim ne nje label te deklaruar me siper , pikerisht  LabelStrength.Kodi i meposhtem vendoset pas ScriptManager:

<script language="javascript" type="text/javascript">

function _OnKeypress() {

var checker = new AjaxEnabled.PasswordStrengthComponent();

var pass = document.getElementById("TextBoxPassword").value;

var strength = checker.returnPasswordStrength(pass);

document.getElementById("LabelStrength").innerText = strength;

}

</script>

KUJDES!!! Nese jeni duke perdorur masterpage dhe te dhenat i keni ne nje content atehere Id ajne ndryshe, perfshijne dhe id e content-it, konkretisht: MainContent_TextBoxPassword dhe MainContent_LabelStrength .

 

11.Hapi i fundit  eshte per t’u siguruar se ky event qe krijuam duhet te ekzistoje I lidhur me textboxin e Password-it. Kete e realizojme duke shtuar tek  TextBoxPassword atributin  onkeyup=”_OnKeypress()”.

12. Figura me poshte shfaq rezultatin.

 


Shembull 2 ( Krijimi i AJAX Control )

Qellimi i shembullit te dyte eshte krijimi i nje controli  klient ne AJAX dhe shtimi i tij ne faqe. 

1. Hap Visual Studio  dhe krijo nje  ASP.NET Web site te quajtur  AjaxEnabled.

2. Shto nje JavaScript file ne kete site. Kliko me te djathten tek Web site dhe zgjidh Add New Item. Ne ate Add New Item dialog boxin qe do te shfaqet, zgjidh JScript File. Emertojeni file-in PassTextBox.js. 

3. Hapni JavaScript file-in qe krijuat me siper dhen e krye te faqes se file-it shtoni kodin: Type.registerNamespace("AjaxEnabled");

4.  Me pas percaktojme konstruktorin e kesaj klase JavaScript si nje funksion. Ne kete rast konstruktori merr nje parameter  element. Kjo per arsye se duhet te perfaqesohet elementi i DOM te cilin do beje extend control-i qe ne po krijojme. Perdoret ky element per te startuar klasen baze te System.UI.Control.

Ky control do te percaktoje stilin e nje text box duke u bazuar ne fortesine e password-it.

Per kete arsye ka tre properties, nje per cdo opsion te mundshem te fortesise. Shembulli si vijon: 

//create constructor

AjaxEnabled.PassTextBox = function(element) {

AjaxEnabled.PassTextBox.initializeBase(this, [element]);

this._weakCssClass = null;

this._mediumCssClass = null;

this._strongCssClass = null;

}

 

5. Hapi tjeter duhet  per te percaktuar pjeset e tjera te klases. Krijojme nje prototip dhe ky protoptip do te permbaje dy metoda initialize  dhe  dispose. Gjithashtu edhe nje event te quajtur onKeyup qe lidhet me eventin  keyup  te objektit te TextBox-it. Se fundmi kodi perfshin nje sere properties per menaxhimin e marrjes dhe vendosjes se klasave stilistike te password. 

//define class

AjaxEnabled.PassTextBox.prototype =

{

//initialize the UI control

initialize: function() {

AjaxEnabled.PassTextBox.callBaseMethod(this, ‘initialize’);

this._onKeyupHandler = Function.createDelegate(this, this._onKeyup);

$addHandlers(this.get_element(), {‘keyup’ : this._onKeyup}, this);

},

dispose: function() {

(this.get_element());

AjaxEnabled.PassTextBox.callBaseMethod(this, ‘dispose’);

},

//define key press event

_onKeyup : function(e) {

//get password text

var pass = this.get_element().value;

var strength = this.returnPasswordStrength(pass);

switch (strength) {

case “Weak”:

this.get_element().className = this._weakCssClass;

break;

case “Medium”:

this.get_element().className = this._mediumCssClass;

break;

case “Strong”:

this.get_element().className = this._strongCssClass;

break;

}

},

//define properties

get_weakCssClass: function() {

return this._weakCssClass;

},

set_weakCssClass: function(value) {

this._weakCssClass = value;

},

get_mediumCssClass: function() {

return this._mediumCssClass;

},

set_mediumCssClass: function(value) {

this._mediumCssClass = value;

},

get_strongCssClass: function() {

return this._strongCssClass;

},

set_strongCssClass: function(value) {

this._strongCssClass = value;

},

returnPasswordStrength: function(password) {

var strPass = new String(password.toString());

if (strPass.length < 5) {

return “Weak”;

}

else {

if (strPass.length < 8) {

return “Medium”;

}

else {

return “Strong”;

}

}

}

}

 

6. Se fundmi shtoni kodin ne klase duke shtuar nje library me ane te thirrjes se metodes registerClass te componentit. Klasa duhet te trashegoje Sys.UI.Control class nga librarite. Kodi I meposhtem tregon dhe shenim kur kemi nje loadim te plote:

 

//register class as a Sys.Control

AjaxEnabled.PassTextBox.registerClass('AjaxEnabled.PassTextBox',Sys.UI.Control);

//notify loaded

if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();

 

7. Save kete file. Hapim Default.aspx ne source view

8. Shtoni nje ScriptManager control nga Toolbox ne faqe. Ne kete ScriptManager control, shtoni nje reference drejt PassTextBox.js file te krijuar me siper. Gjithashtu atributin EnableCdn="true", per te mundesuar ekzekutimin e kodit. Me poshte kodi:

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

<Scripts>

<asp:ScriptReference Path="~/ PassTextBox.js" />

</Scripts>

</asp:ScriptManager>

 

10. Me pas shtoni controls ne faqe per te krijuar nje pamje te nje user login form.

<div style="font-size: large; font-weight: bold">User Login</div>

<hr />

<br />

User Name:

<br />

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

<br />

Password:

<br />

<asp:TextBox ID="TextBoxPassword" runat="server"

TextMode="Password" Width="200"></asp:TextBox>

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

<br />

<input id="Button1" type="button" value="Submit" />

 

11. Ne tagun  <head /> shtoni  page source:

<style type="text/css">

.weak

{

border: thin solid #FF0000;

}

.medium

{

border: thin solid #FFFF00;

}

.strong

{

border: medium solid #008000;

}

</style>

 

12. Me pas percaktojme kodin e javascript:

<script language="javascript" type="text/javascript">

var app = Sys.Application;

app.add_init(appInit);

function appInit(sender, args)

{

$create(AjaxEnabled.PassTextBox,{

weakCssClass : 'weak',

mediumCssClass : 'medium',

strongCssClass : 'strong'

},

null, null, $get('TextBoxPassword')

);

}

</script>

 

7. Ekzekutojme faqen dhe duket si me poshte:


Krijimi i WebService 

Step (1): Select File--> New --> Web Site in Visual Studio, and then select ASP.Net Web Service. 

Step (2): A web service file called Service.asmx and its code behind file, komunikimdb.cs  is created in the App_Code directory of the project. 

Step (3): Change the names of the files to komunikimdb.asmx  and  komunikimdb.cs. 

Step (4): The .asmx file has simply a WebService directive on it: 

<%@ WebService Language="C#"

                  CodeBehind="~/App_Code/ komunikimdb.cs"

                  Class=" komunikimdb " %> 

Step (5): Open the komunikimdb.cs file, the code generated in it is the basic service. 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Services;

using System.Data.SqlClient;

using System.Data;

 

namespace WEBSERVICES

{

    [WebService(Namespace = "http://tempuri.org/")]

    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

    [System.ComponentModel.ToolboxItem(false)]

    public class komunikimdb : System.Web.Services.WebService

    {

 

        private SqlConnection con = new SqlConnection("Data Source=GENA\\GENAINSTANCE;Initial Catalog=aed;User ID=sa;Password=12");

       

        [WebMethod]

        public DataSet GetLista()

        {

            SqlCommand cmd = new SqlCommand("Select * from aed..Te_dhenat", con);

            SqlDataAdapter da = new SqlDataAdapter(cmd);

            DataSet ds = new DataSet();

            da.Fill(ds);

            return ds;

        }

 

        [WebMethod]

        public DataSet GetPerdorues(String uname,String pass)

        {

            SqlCommand cmd = new SqlCommand("Select top(1) * from aed..Perdoruesit where username='"+

                uname + "' and password='" + pass+"' ", con);

            SqlDataAdapter da = new SqlDataAdapter(cmd);

            DataSet ds = new DataSet();

            da.Fill(ds);

            return ds;

        }

 

        [WebMethod]

        public void DeleteTeDhena(String id)

        {

            con.Open();

            SqlCommand cmd2 = new SqlCommand("Delete from aed..Te_dhenat where  id=" + id + " ", con);

            int rows = cmd2.ExecuteNonQuery();

            con.Close();

        }

 

        [WebMethod]

        public void InsertTeDhena(String Emri, String Mbiemri, String Email)

        {

            con.Open();

            SqlCommand cmd2 = new SqlCommand("Insert into aed..Te_dhenat(Emri,Mbiemri,Email) values "+

            " ('"+Emri+"','"+Mbiemri+"','"+Email +"') ", con);

            int rows = cmd2.ExecuteNonQuery();

            con.Close();

        }

    }

} 

Step (6) : Running the web service application gives a web service test page, which allows testing the service methods.

Step (7) : Click on a method name, and check whether it runs properly.

For the WEB REFERENCE:

Step (1): Right click on the web application entry in the Solution Explorer and click on 'Add Web Reference'.

Step (2): Select 'Web Services in this solution'. It returns the WEBSERVICES reference.

Step (3): Clicking on the service opens the test web page. By default the proxy created is called ‘localhost’,  you can rename it. Click on 'Add Reference' to add the proxy to the client application.


ċ
WEBSERVICE.zip
(200k)
Leogena Zhaka,
Dec 18, 2014, 9:45 AM