Web Technologies

BLOG for Web Technologies

Freewares, Free E-Books Download, SEO, Tips, Tricks, Tweaks, Latest News, .Net, PHP, ASP, ASP.Net, CSP, MS SQL Server, MySQL, Database
earnptr.com
Wednesday, February 20, 2008
How to integrate AJAX Control Toolkit controls in ASP.NET

Before reading this tutorial you should be familiar with ASP.NET and C# or VB.NET (examples will be provided in both C# and VB.NET).

If you don't already have Visual Studio installed on your computer you can download Visual Web Developer 2005 Express Edition freely from the Microsoft website.

To download AJAX Extension go to www.asp.net, click on "AJAX" tab at the top of the page, then click on the "Download" button, and at last click "Download ASP.NET AJAX v1.0" button. Save the file and run the installer.

Now we can create our first AJAX-Enabled website. Open Visual Web Developer 2005 Express Edition and create a new Web Site (File -> New -> Web Site). In the "New Web Site" dialog chose "ASP.NET AJAX-Enabled Web Site" and select your desired programming language from the "Language" Combo Box. This template is installed in Visual Web Developer 2005 Express Edition because we've previously installed the AJAX Extension.

When the new project is created you can see, in the Design mode, that the newly created ASP.NET page already has an ScriptManager. Every page that uses Microsoft AJAX needs to have a ScriptManager instance (and only one).

In the following examples we shall implement a common AJAX development pattern called "Partial page update".

Let's start with a really simple example you get to see nowadays on a lot of websites: a time control that shows the current time. For that we shall drag a Label from the Toolbox into the page and name it lblTime, and a Button called btnUpdate which has the Text property set to "Update". Now, to display the current time in the label we shall add the following code to that auto-generated handler that handles PageLoad event.

[ C# ]

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

[ VB.NET ]

Protected Sub _Default_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
lblTime.Text = DateTime.Now.ToString()
End Sub

The end result should look something like image bellow.

The result is a simple page with a label and a button with the label showing the time when the page was loaded. When we hit the Update button the whole page reloads and the current time is displayed in the label. What really happens is that clicking on the button triggers a postback so the Page Load handler is reached and the lblTime's Text property is updated with the current time.

Ok until now... everything looks good... but the label only displays the time of a specific moment and to update it you have to hit the Update button which reloads the whole page. This is not very appealing.

Let's now modify a bit the application, so it makes use of Microsoft AJAX.

Notice that once the AJAX Extension was installed on the system a new tab was created in the Toolbox with some items. There are basic controls you need to create interactivity with AJAX.

One of the most used controls among them is the "UpdatePanel". UpdatePanel is a very powerful control because all the controls that are nested within this control are automatically updated without page reload.

Drag an UpdatePanel in the page and move the lblTime and the btnUpdate controls in this control so the aspx code behind looks something like this:

<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="lblTime" runat="server" Text="Label">asp:Label>
br>
<asp:Button ID="btnUpdate" runat="server" Text="Update" />
ContentTemplate>
asp:UpdatePanel>
form>

Now, let's enjoy the result. When running the application the Update button updates the time in but without reloading the entire page so that the change happens smoothly. As you see, this is a major improvement.

But the real purpose of a time indicator is to display the current time, and ours only displays the current time when the Update button is hit. So, let's further improve our application.

Delete the btnUpdate control from the page and add a Timer control from the AJAX Extensions Toolbar tab to the UpdatePanel in the page and set its "Interval" property to 1000. The Timer control in the AJAX Extensions triggers an postback at a specified amount of time. This is what we've done here: we're telling the page to reload itself every second. But thanks to the UpdatePanel in which this Timer is located only the UpdatePanel is reload.

Now the aspx code should look like this:

<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="lblTime" runat="server" Text="Label">asp:Label>
<asp:Timer ID="Timer1" runat="server" Interval="1000">
asp:Timer>
ContentTemplate>
asp:UpdatePanel>
form>

And now the page displays a fully functional clock: it updates each second to display the current time. This is possible because the default value of the "UpdateMode" property is set to "Always": this tells the UpdatePanel to update itself each time one of its child controls causes a postback. The other option for the UpdateMode property is "Conditional". In order to build rich interactive user interfaces you must fully understand the functionality of the UpdatePanel. So let's modify a little bit our application and observe the changes.

Let's assume that the timer is placed outside the UpdatePanel. In a real world application this a frequent situation as we can't always have a control reside inside an UpdatePanel or we want an external control to update the UpdatePanel. In this situation the timer updates each second but the whole page is reloading (you can make this more obvious by adding a large dummy text outside the UpdatePanel).

To achieve the smooth update applied only to the UpdatePanel we have to add an "AsyncPostBackTrigger" element to the "Triggers" tag of the UpdatePanel and set the controlID to "Timer1" (which is the name of the timer in our page) and the "EventName" to "Tick" as Tick is the event raised by the timer each time it triggers an postback. Now the aspx code should look something like this:

<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
Triggers>
<ContentTemplate>
<asp:Label ID="lblTime" runat="server" Text="Label">asp:Label>
ContentTemplate>
asp:UpdatePanel>
<asp:Timer ID="Timer1" runat="server" Interval="1000">
asp:Timer>
form>

This is a basic yet complete example of how to use UpdatePanel and Timer controls and the Partial page update pattern to transform a classic ASP.NET page into an AJAX-enabled one.




Now, we shall focus on the AJAX Control Toolkit, a free library of AJAX-enabled controls. You can download it from http://www.asp.net, click the Download button then scroll the page to the ASP.NET AJAX Control Toolkit section and hit "Download the toolkit" button. This will redirect you to the Codeplex website from where you can download the toolkit. I suggest downloading the AJAX Toolkit along with the source code as you may want in the future to modify the existing controls to match your expectations. Notice that the file being downloaded is a zip file, no msi, no installer. Extract the content of the zip file and you shall find a VS solution that you must build. You shall find the result in the bin directory. Now open Visual Studio, right-click the Toolbox and select "Add tab".

Name it whatever you want or simply "AJAX Control Toolkit" and then right-click it and select "Choose Items". Navigate to the bin directory and select AjaxControlToolkit.dll. This will populate the newly created tab with AJAX-Enabled controls. Now your Toolbox should look like image above.

Next we shall build another website that uses controls found in the AJAX Control Toolkit.

Create a new project, add an TextBox and Label and a Button to the page and then add the following code to the button's Click handler:

[ C# ]

Label1.Text=TextBox1.Text;

[ VB.NET ]

Label1.Text=TextBox1.Text

Now, drag a ConfirmButtonExtender control and set its ConfirmText property to "Are you sure?" and TargetControlID property to Button1. What this controls does is that when the button is clicked it pops up a confirmation dialog with the specified text and an OK and a Cancel button. Only if the OK button is pressed the execution of the button's handler is executed as you see in image bellow.




As the name says ConfirmButtonExtender extends the functionality of a Button. The library contains a lot of other amazing and complex controls like: Accordion, TabContainer, CalendarExtender etc.

It is easy to create AJAX-enabled pages in Visual Studio. On the ASP.NET official website (http://www.asp.net ) in the AJAX section you can find complete documentation on each control and even watch the controls live prooving their power. Use them to create a better user experience and ensure the kind of interactivity you've always wanted to create on the web.

Labels: , , , ,

posted by WebTeks @ 3:11 AM   0 comments
Thursday, February 14, 2008
Enabling Roles in ASP.NET v2.0

By default the Roles provider is defined in machine.config but it isn't enabled. Attempting to use the Roles feature before it is enabled will throw the following error:

"The Role Manager feature has not been enabled."

It's easy to enable though. The ASP.NET v2.0 quickstart explains how to enable this:
http://beta.asp.net/QUICKSTART/aspnet/doc/security/membership.aspx#roles

Since the provider is already defined in machine.config, you can use the same provider or define a new one. The advantage of using the one in machine.config is that the server administrator can keep it up to date and consistent with the other providers. I'll give two examples, one inheriting the default machine-level provider and one specifying a new one. These goes in the section of web.config.

Example 1 - Inherit the machine-level provider

Notice that the defaultProvider name is AspNetSqlRoleProvider which is what is specified in machine.config by default. It's essential to use this provider name if you will inherit the provider settings.

<roleManager
enabled="true"
cacheRolesInCookie="true"
defaultProvider="AspNetSqlRoleProvider"
cookieName=".ASPXROLES"
cookiePath="/"
cookieTimeout="30"
cookieRequireSSL="false"
cookieSlidingExpiration="true"
createPersistentCookie="false"
cookieProtection="All" />

Example 2 - Override and specify all roleManager settings

I took this example directly from http://beta.asp.net. Notice that the defaultProvider name can be anything you want as long as it matches the provider name. If you use AspNetSqlRoleProvider which is the name that machine.config uses by default, then make sure to put before the tag. Also notice connectionStringName which needs to be defined in machine.config or web.config and point to a database that is prepared with the asp.net v2.0 schema.

<roleManager
enabled="true"
cacheRolesInCookie="true"
defaultProvider="QuickStartRoleManagerSqlProvider"
cookieName=".ASPXROLES"
cookiePath="/"
cookieTimeout="30"
cookieRequireSSL="false"
cookieSlidingExpiration="true"
createPersistentCookie="false"
cookieProtection="All">
<providers>
<add name="QuickStartRoleManagerSqlProvider"
type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="ASPNETDB"
applicationName="SecurityQuickStart"/>
providers>
roleManager>

In case you are curious and for perspective, I'll include the default machine.config definition for the roleManager section.

<roleManager>
<providers>
<add name="AspNetSqlRoleProvider" connectionStringName="LocalSqlServer" applicationName="/"
type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add name="AspNetWindowsTokenRoleProvider" applicationName="/"
type="System.Web.Security.WindowsTokenRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
providers>
roleManager>

posted by WebTeks @ 8:32 PM   0 comments
Saturday, February 2, 2008
Cookies in ASP.Net
Cookies:
A Cookie is a small text file that the browser creates and stores on the hard drive of your machine. Cookie is just one or more pieces of information stored as text strings. A Web server sends you a cookie and the browser stores it. The browser then returns the cookie to the server the next time the page is referenced. The most common use of a cookie is to store information about the user and preferences the user makes. For example, assume you like DVD's and register with Ebay to participate in online auctions. You are required to fill out a form with your name, credit card details and address. Ebay assigns you an ID, stores your information with that ID in its database on the server, and sends the ID to your browser as a cookie. Your browser stores the ID on your hard disk. The next time you go to Ebay, the ID is sent back to the server. The server looks you up by your ID and customizes the Web page it sends back to you. The page might say, "Cheap rates on your favorite DVD's".

Creating cookies with ASP.NET is simple and straight forward. The System.Web namespace offers a class called HttpCookie to create cookies. The following code demonstrates the creation of cookies. The code assumes that you have a TextBox, two Buttons and a RadioButtonList control with some items in it on a Web Forms page. Check the live code demo at the bottom of this page for more.

Private Sub Select_Click(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles Select.Click
Dim newCookie As HttpCookie = New HttpCookie("Books")
newCookie.Values.Add("Name", TextBox1.Text)
newCookie.Values.Add("FavBook", RadioButtonList1.SelectedItem.Text)
newCookie.Expires = #12/31/2008#
Response.Cookies.Add(newCookie)
Label3.Text = "Cookie Created"
Select.Visible = False
TextBox1.Visible = False
Label1.Visible = False
Label2.Visible = False
RadioButtonList1.Visible = False
End Sub


Understanding the Code:


First, we created a variable called newCookie and an HttpCookie object is instantiated. This object enables us to pass a string when we create it to identify the name that the browser will use to store the cookie. We called it Books.
After we created the object, we added information to it using the Values property and the Add method.
To ensure that the cookie stays on the user's hard drive for a while we set it's date using the HttpCookie object's Expires property.
To get this cookie sent back to the browser and stored on the hard drive we used the Response object.

The code listing above creates and stores the cookie on the user's hard drive which is fine. To retrieve them at a later date, what should be done?


Retriving the cookie:

The code below demonstrates how to retrieve a cookie and display information to the user based on his preferences.

Private Sub Retrieve_Click(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles Retrieve.Click
Label3.visible=False
Label4.Text = "Hello" &" "& Request.Cookies("Books")("Name") & "."&_
"We have a new book for you:"
If Request.Cookies("Books")("FavBook") = "VB" Then
Label5.text="XYZ VB Book"
ElseIf Request.Cookies("Books")("FavBook") = "C#" Then
Label5.text="ABC C# Book"
Else
Label5.text="Startvbdotnet.com's ASP Book"
End If
End Sub


Understanding the Code:

First, we used the Request object to retrieve the cookie and display a message to the user.
Based on the user's selection first time he accessed the page, we display a new book to him using If..Then..Else conditional.

The path to the location on the hard drive where cookies are stored is
C:\Documents and Settings\Administrator\Cookies.

Labels: ,

posted by WebTeks @ 12:08 AM   0 comments
Previous Post
Archives
Links
Template by

Free Blogger Templates

BLOGGER

Subscribe in NewsGator Online Subscribe in Rojo Add to Google Add to netvibes Subscribe in Bloglines Web Developement Blogs - BlogCatalog Blog Directory Blogarama - The Blog Directory Blog Directory & Search engine Computers Blogs - Blog Top Sites Top Computers blogs