TURKISH BLOG   |  ABOUT ME  |  ARCHIVES  | DELETE LANGUAGE COOKIE

Enes TAYLAN

Mind Hegemony - Mood 1.0 - Total Control Edition

BUILDING AND CONSUMING XML BASED WEB SERVICE

clock May 6, 2009 18:50
Building a Web Service means creating a class and expose this class's some methods to web so that a client can consume this web service.To do so create an ASP.NET Web Service in VS2008 by selecting File > New > Web Site and select ASP.NET Web Service. (We will get a data set from a remote machine)

 
Now in solution explorer you have a service.asmx file. Delete it and add a new file to your project.Select Web Service, name it as "Customer.asmx".



Write this code to your Customer.cs in your App_Code directory. 
[WebMethod] //expose our method to the web
public DataSet GetCustomers()   //method to get dataset from a database
{
     SqlConnection conn;
     SqlDataAdapter adapter;
     DataSet result = new DataSet();
     string cmdString = "SELECT * FROM [SELECT * FROM SalesLT.Customer]";  //command string
     conn = new SqlConnection(ConfigurationManager.ConnectionStrings["AdventureWorks"].ConnectionString);
     adapter = new SqlDataAdapter(cmdString, conn);
     adapter.Fill(result);  //our sqladapter fills the data set
     return result;  //return resulting dataset
}    
Now view in the browser our Customer.asmx You will see ASP.NET's specific page for Web Services.

Click GetCustomer() method.There is SOAP messages and also an invoke button to invoke the WebService.You can check whether the webservice is working or not. At this point we can consume this webservice.Create another ASP.NET website and right click on the project name.Select "Add Web Reference"
 
 
In URL part copy your asmx file's URL. In web reference name part, write Customer Service.Click "Add Reference" Now VS2008 has created necessary classes in the second website to work with web reference.In Default.aspx page add a button a GridView.In click event of button write:
protected void Button1_Click(object sender, EventArgs e) 
{
    CustomerReference.Customer ws = new CustomerReference.Customer(); 
    //CustomerReference is the name we defined when adding Web Reference
    GridView1.DataSource = ws.GetCustomers(); 
    GridView1.DataBind();
}

If there is no exception, when we click the button we should see the results.:)



STATE MANAGEMENT IN ASP.NET

clock May 5, 2009 07:29
State managament is a very important concept for server side programming technologies. The reason is simple, the foundation of WEB, which is HTTP, is a stateless protocol.Information exchange between server and client (GET and POST) can’t know who is the user, what are this user’s preferences, what about his authorization? etc. so to address this problem, server side technologies has tools to manage states between several HTTP communications. In ASP.NET to manage to keep track of HTTP communication we have 9 choices. 4 in server side and 5 in client side and corresponding technologies in server side and client side has many common features should be addressed accordingly. But first of all cycle of HTTP request and where we can use state management:

1.A web browser makes HTTP GET request (when you enter www.enestaylan.com) . Assume that this Web browser has never visited this website or deleted all the information of past visits.
:
2.Server (IIS or APACHE or another type) respond this request by returning HTML to the client.Additinally .aspx page return a cookie with a unique ID to track this specific client (Web Browser) on Set-Cookie HTTP Header.Then browser re-returns this cookie in every subsequent HTTP call. (The state is here the cookie.Because every cookie has unique ID and server can differentiate different clients)
:
3.Also the developer could put some hidden text fields 

Server-Side mechanism                                       Features
Application State Fastest.
Cache Object (in Application Scope) Fast.
Session State Choices are:
1.In-Proc
2.Out-Of Proc
3.DB-Backed
Database If several servers, can be
 accessed by any server.                  

 

Client-Side mechanism                        Features
Cookie Simple.Inappropriate for sensitive
and large amounts of data.                               
Hidden Field Fast.Inappropriate for sensitive
and large amounts of data.
View State  Good for page-scoped data.
Control State Simple.Control specific data.
Query String Simple but can be manipulated
easily on client side.

Let's start with session object.

SESSION OBJECT

We have 3 choices to use session object on the server side:  in-process, means in the same process in IIS, out-of-process and database backed.On the client side we have 2 options: with cookie or with query string.Options on the server can be manipulated like below in web.config.

<configuration>
        <system.web>
                <sessionState mode="Off|InProc|StateServer|SQLServer|Custom" />
        </system.web>
</configuration>

In code we refer to session object :

Page.Session["mySession"] = "myValue";

Although Session is an attribute of Page, actually it lives in HttpContext object and Page has just a reference to it.

In-Process Session State :
In this configuration session data is stored in the HttpRuntime's internal cache (in IIS main process). Additinally, because in this type session objects are stored in memory, some situations should be handled to preserve efficiency (like a session data with 40 mb XML file)
Another problem with In-Process mode, when we change anything in our web solution (web.config, global.asax,copying a class in \App_Code directory then our all session states are deleted. InProc type is a simple solution
When we store items in Sesion object we use the notation:

Session["myKey"] = TextBox1.text;

To get the value of the Session object (use explicit casting):

TextBox1.text = (string)Session["mykey"];

Out-of-Process State :
This type of state is generally used in web farms, composed of many servers. state mechanism lives in aspnet_state.exe.Generally an independent server is dedicated to state management

SQL-BACKED Session State :
InProc offers speed, out-of-proc with an independent server resilience/speed and SQL-BACKED session management offers resilience to even IIS starts.

Now state in client side:

Cookieless Session State :
ASP.NET uses cookies to session state on client, default.However, when we write:

<configuration>
        <system.web>
                <sessionState mode="InProc" cookieless="UseUri"/>
        </system.web>
</configuration>

ASP.NET stores session data on url. Like \myapp\(S(kjdfsjdflksj35345h34hk53))\foo\k.aspx

Query Strings :
Query string is an also a tool for state management different from others,however , in a sense that it is not for user specific but navigation specific.Example: assume that you have a news website and a content page, which shows whichever news id comes to it:
\content.aspx?newsID=17

String id = Request.QueryString["newsID"]; 
if (id != null) 
return Convert.ToInt32(id); 
else return 0;

We get the query string field from URL and check whether it is null or not.Query string fields are always strings so convert it to which type you need.

Hidden Fields, ViewState and ControlState :
ViewState and ControlState are generally configured for control specific.ViewState is used like Session Object

ViewState["myView"] = "kj";
Label1.Text = ViewState["myView"];

Hidden fields as an ASP.NET control (not html control):

HiddenField1.Value = "Enes TAYLAN";

There is also another storage place, that is not used so often and lives very short,  HttpContext.Current.Items. It is used for single HttpRequest.



ASP.NET SECURITY: AUTHENTICATION AND AUTHORIZATION

clock April 21, 2009 08:23
ASP.NET gives developers very flexible and powerful capabilities in to secure to make decisions considering user actions.To apply settings we want, we can edit web.config, machine.config, IIS.Besides this settings there are great classes and namespaces in .NET ( we will use generally system.web.security ).Let's start with <authentication> element in web.config. (Authentication is the process that determines the identity of a user, in other words asking user his/her credentials.Authorization,on the other hand, after validating credential, giving the user access to any specific part of the application) 
 

<authentication mode="Forms"> //possible values are "Windows|Forms|Passport|Name   

</authentication> 

 90% we use authentication mode "Forms" so no need to focus on other types.By using <authorization> we define accession rules for specific folders or pages or website as a whole.
 

<authorization>

      <deny users="*"/>

      <allow roles="administrator"/>

</authorization> 

This setting first of all denies all users (*) then gives the access right to the role administrator.If we place this xml in web.config on the root of the application then it uses these settings for whole website.But in specific folders it is applied only to that folder. ie in our example, it seems that this code is for admin directory ( it gives access rights just for administrator(s).) We have deny and allow tags and users and roles attributes.For our need we can use them appropriate combination.And an example of how to use system.web.security and its basic functionalities:

using System.Web.Security;
protected void LoginButton_Click(object sender, EventArgs e)
{
if (Membership.ValidateUser(TextBox1.Text, TextBox2.Text))  //this method takes two arguments username,password
{
FormsAuthentication.RedirectFromLoginPage(TextBox1.Text, true); //go to page which was intended 
//before redirected to loginpage           
}
else
FormsAuthentication.RedirectToLoginPage();  //otherwise go to loginpage again
}
}


BUILDING A SIMPLE ASP.NET PAGE WITH AJAX

clock April 18, 2009 06:16

I will show how to use AJAX capibilities in ASP.NET by using major AJAX controls in our VS2008 toolbox.We have ScriptManager,ScriptManagerProxy,Timer,UpdatePanel and UpdateProgress. In these tutorial we'll use UpdatePanel and UpdateProgress controls.Let's do the classic example that gets the current time from server.To do so first create a website whose name is AJAX (or whatever you want:)) 



 After creating the project lets code our default.aspx page.Add one ScriptManager to the page.(just one because more than one ScriptManager gives error and don’t forget that you should place it above all AJAX controls.To be safe I add it just after <form.....>)

    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>

    <div>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
                <br />
                <asp:Button ID="Button1" runat="server" Text="Button" />
            </ContentTemplate>           
        </asp:UpdatePanel>

    </div>
    </form>

Then add UpdatePanel.In design view you can just drag and drop ASP.NET server controls inside it.But if you are in source view, add contempt template tags in UpdatePanel and now you can add what ASP.NET controls you want since UpdatePanel is a container control. Very simple code behind file:

protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = DateTime.Now.ToString();
} 


When we click the button, it gets the result from the server but doesn't refresh the page.This is the use of UpdatePanel.When an event related with it, Update Panel just request the controls inside it.This is the advantage of AJAX.( In our example because we have just a label and a button, using AJAX doesn't make much sense. However in big pages only updating small partion of the html is very useful!)

And our UpdateProgress Control.This control is very easy to use, too. Now add it above our UpdatePanel.

        <asp:UpdateProgress ID="UpdateProgress1" runat="server">
            <ProgressTemplate>
                updating wait , please
            </ProgressTemplate>
        </asp:UpdateProgress>

        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <br />
                <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
                <br />
                <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
            </ContentTemplate>
        </asp:UpdatePanel> 

And to see the result in localhost (very fast so should sleep it) add to code behind:

protected void Button1_Click(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(4000);
Label1.Text = DateTime.Now.ToString();
}  

Now our program sleeps for 4 seconds and UpdateProgress control shows what it has in <ProgressTemplate>......</ProgressTemplate. After 4 seconds it disappears.We can also add very good wait.gifs. Write this:

<ProgressTemplate>               
                <img style="float:left" src="ajax-loader-darkblue.gif" />
</ProgressTemplate>