Pages

Sunday, June 14, 2009

Working with Web User Controls at Run-time

Introduction

In addition to HTML and Web server controls, ASP.Net provides with the capability to easily create custom reusable controls by using the same techniques that are used to develop an ASP.Net page. These controls are called user controls.

User controls offer great flexibility than server-side includes (SSIs) by accessing the object model support provided by ASP.NET. Using User Controls you can program against any properties declared in the control just like any other ASP.Net server control, rather than simply including the functionality provided by another file.

Furthermore, in a single application, multiple user controls can exist that are authored using different languages. For example, an application can have a user control created with Visual Basic while another in C#, and have both these controls on the same ASP.Net page.

In this article I will create a simple login user control, and load that to a web-page dynamically.

Prerequisites

This tutorial assumes that you own a copy of Visual Studio 2005 or Visual Web Developer Express. It also assumes that you are familiar with ASP.Net 2.0 basics and have worked with user controls before.

Creating the Website

If you have an existing web site, you can skip this section. Otherwise, you can create a new web site and page by following these steps.

To create a file system Web site:

* Open Visual Studio 2005.
* On the File menu, open New and click on Web Site.

The New Web Site dialog box appears.

* Under Visual Studio installed templates, click ASP.NET Web Site.
* In the Location box, enter the name of the folder where you want to keep the pages of your Web site.

For example, type the folder name C:\WebSites\mySite.

* In the Language list, click Visual Basic (or the language you prefer to work with).
* Click OK.

Visual Web Developer creates the folder and a new page named Default.aspx

Adding a User Control to the Website

Right-click in the solution explorer and select Add New Item. Select Web User Control and type in the name of the control. Click on Add to add the user control to the web application.

This will add a .ASCX file to the project. This is our user control.

Preparing Our Control

Double click loginCtrl.ascx to open the new user control and switch to design view. Add a table to the page by clicking Inset Table under the Layout Menu. Design a page similar to the following:

As you can see, this user control defines a typical Login Control. I also added two Required Field Validation controls and a Validation Summary control. Make sure that the ControlToValidate properties of the validation controls are set, otherwise the application will result in an error at run-time.

Now, switch to the code-behind of the user control. I am going to add property methods to retrieve the values entered in the text-boxes.

Partial Class loginCtrl

Inherits System.Web.UI.UserControl

Property pUser() As String

Get

Return txtUser.Text.Trim

End Get

Set(ByVal value As String)

txtUser.Text = value

End Set

End Property

Property pPass() As String

Get

Return txtPassword.Text

End Get

Set(ByVal value As String)

txtPassword.Text = value

End Set

End Property

End Class

This completes our user-control. You can create a much advanced user-control by adding login button to the user-control and handling the login functionality in the control itself. This way you can completely separate the login functionality from the presentation layer.

Adding the control to the Web-Page at design time

First we will try out our control by adding it to the Default.aspx page at desing-time. Open Default.aspx and switch to Design-view. Now click on loginCtrl.ascx in the solution explorer and drag it onto Default.aspx. This will add the user control onto the page, just like it does a server control.

After adding the control, I created a login button on the page. Switch to code-behind class and create a button event handler for the login button.

Protected Sub btnLogin_Click(_, _) Handles btnLogin.Click

Dim tempString As String = ""

tempString = "UserName: " + Me.LoginCtrl1.pUser

tempString = tempString + "... "

tempString = tempString + "Password: "

tempString = tempString + Me.LoginCtrl1.pPass + "."

Response.Write(tempString)

End Sub

This will fetch the user-name and password from the user control and write it onto the web-page.

Compile and run the web-application. Using planned layout, you can create professional and eye-catching applications with ASP.Net easily. With the use of User Controls, you can keep your presentation layer from your data and business layer.

Adding the control to the Web-Page at run-time

The main focus of this article was in explaining how to setup a user control to be loaded on a page at run-time. This is a very important and useful technique in creating ASP.Net applications. For instance, you have created two menus, one is an administrator menu, and the other is the basic user menu_ Based on the login credentials you can easily identify the user of your site as a simple client or an administrator. Thus, you can load whichever user control as required at run-time.

In the Default.aspx page, switch to design-view and delete the loginCtrl.ascx that we earlier dragged onto the page. Go to ToolBox and drag-n-drop a PlaceHolder where the User Control had been. This place holder will hold our user control, i.e. at run-time, I will add the user control to this placeholder.

Switch to the code-behind class and make changes to the code in order to have the following:

Protected Sub Page_Load(_, _) Handles Me.Load

Dim tempControl As Control = LoadControl("loginCtrl.ascx")

Me.myPlaceHolder.Controls.Add(tempControl)

End Sub

Protected Sub btnLogin_Click(_, _) Handles btnLogin.Click

Try

For Each tempControl As loginCtrl In myPlaceHolder.Controls

Dim tempString As String = ""

tempString = "UserName: " + tempControl.pUser

tempString = tempString + "... "

tempString = tempString + "Password: "

tempString = tempString + tempControl.pPass + "."

Response.Write(tempString)

Next

Catch ex As Exception

End Try

End Sub

The loadControl function is used to create an instance of the user control at run-time. You can define a static path to the .ascx file or a dynamic path. Using the dynamic approach can create the application more portable.

Next follows the changes to the Button handler. What we do in this event handler is locate the loginCtrl instance inside the place holder. If it was successfully loaded, then it would exist. The rest is the same as before.

Taking into consideration our two-menu example, in the button event-handler, we will loop for both controls. On page load, one of the menu is added, and thus the code for that will be executed, while since the other won't exist.

Friday, June 12, 2009

Creating a GridView with Resizable Column Headers

Before I get into the implementation details, here is a quick screen shot of the grid. Unfortunately the mouse cursor didn't come across in the screen shot, but when it is placed over the cell borders in the header row, it displays the east/west pointing arrow. Before I get into the implementation details, here is a quick screen shot of the grid.

Unfortunately the mouse cursor didn't come across in the screen shot, but when it is placed over the cell borders in the header row, it displays the east/west pointing arrow.

Adding this behavior to the existing GridView required implementing a handful of JavaScript functions. My approach for implementing this features was to do the following:

  1. Handle each of the header cells's mousemove events to determine when the user has the cursor placed roughly over the cell's right hand border. If a resize is already in processes then I use this event to determine what the new width of the column should be
  2. Handle each of the header cell's mousedown events to determine when the resizing begins
  3. Handle the document's mouseup event. When this occurs I make sure that the resize has stopped
  4. Handle the document's selectstart event. I cancel this event if a resize is currently in executing. Doing this make's sure that the header cell's text isn't highlighted when I am resizing the cell. I learned this trick from the AjaxControlToolkit's ResizeableControlExtender.

Download the Code

Wednesday, June 10, 2009

How to use HttpWebRequest and HttpWebResponse in .NET

Internet applications can be classified broadly into two kinds: client applications that request information, and server applications that respond to information requests from clients. The classic Internet client-server application is the World Wide Web, where people use browsers to access documents and other data stored on Web servers worldwide.

Applications are not limited to just one of these roles; for instance, the familiar middle-tier application server responds to requests from clients by requesting data from another server, in which case it is acting as both a server and a client.

The client application makes a request by identifying the requested Internet resource and the communication protocol to use for the request and response. If necessary, the client also provides any additional data required to complete the request, such as proxy location or authentication information (user name, password, and so on). Once the request is formed, the request can be sent to the server.

Click here for details .......

Paging, Selecting, Deleting, and Editing in the ASP.NET 2.0 GridView Control with Keyboard Shortcuts

The ASP.NET 2.0 framework comes with the GridView, a feature-rich ASP.NET server control to display, page through, and edit data on a webpage. Paging, selecting, and editing of the GridView is achieved by declaratively adding properties to the markup of the GridView. This adds link buttons to the data rows of the GridView. You have to click on one of the link buttons to delete or edit a row. One feature I missed is the ability to use these features via keyboard shortcuts.

To achieve that, I developed an ASP.NET 2.0 AJAX Extensions Extender Control for use with ASP.NET 2.0 GridView on ASP.NET 2.0 AJAX enabled web pages.

GridViewKeyboardExtender_src

Click here for details ......

GridView Paging using ASP.NET AJAX Slider Extender

As given in the ASP.NET AJAX Toolkit documentation “The Slider extender allows to upgrade an asp:TextBox to a graphical slider that allows the user to choose a numeric value from a finite range.” In this article, we will explore how to implement paging in an ASP.NET GridView using an ASP.NET AJAX SliderExtender.
Note: Visual Studio 2008 is using and thereby utilizing the ASP.NET AJAX plumbing that comes along with it.

Click here for details .......

Monday, June 8, 2009

Freeze ASP.NET GridView Headers by Creating Client-Side Extenders

Lately We've been working on a pet project where I needed to freeze a GridView header so that it didn't move while the grid records were scrolled by an end user. After searching the Web we came across a lot of "pure" CSS ways to freeze a header. After researching them more they tend to rely on a lot of CSS hacks to do the job and require HTML to be structured in a custom way. We also found a lot of custom GridView classes (another one here), and more.

Some of the solutions were really good while others seemed a bit over the top and required a lot of custom C# or VB.NET code just to do something as simple as freezing a header. Freezing a header requires CSS and potentially JavaScript depending upon what needs done. Regardless if CSS or JavaScript are used, these are client-side technologies of course. We started to write our own derivative of the GridView class but quickly realized that it made more sense to use the standard GridView control and simply extend it from the client-side. An example of what we were after is shown next:



Click here for details .......

Ajax ModalPopup Extender in Asp.Net GridView Control

This article helps you more to explore the ModalPopup Extender integrated with Asp.Net GridView control. By reading this article, you will understand the way to show dynamic data in the ModalPopup, edit the data in the ModalPopup extender and save it into database by making a postback.

Very interesting article, click here for details .......

Sunday, June 7, 2009

Oracle to SQL Server VB.NET Utility application

This is a small utility application that I wrote to help retrieve data from an Oracle source database, then to create the structure dynamically in SQL Server and perform a Bulk Copy. I put a GUI on top of it so that you can use this to test multiple connections and queries.

This utility performs the following steps:

  1. Retrieves the data from Oracle through a OracleDataReader
  2. Converts the OracleDataReader to a DataTable
  3. Creates the SQL Server Tables based on the DataTable Structure
  4. Performs a SQLBulkCopy of the DataTable into the new SQL Server tables.

Screenshot - screen.jpg

Click here for details ......

C#/VB - Automated WebSpider / WebRobot

















What is a WebSpider

A WebSpider or crawler is an automated program that follows links on websites and calls a WebRobot to handle the contents of each link.

What is a WebRobot

A WebRobot is a program that processes the content found through a link, a WebRobot can be used for indexing a page or extracting useful information based on a predefined query, common examples are - Link checkers, e-mail address extractors, multimedia extractors and update watchers.

Click here for details ......

Saturday, June 6, 2009

Checking Link Validity with ASP.NET

If you have an index of links, it can be important to check that a link really exists before showing it off on your site. Here's a way to do it.

This is really not a difficult proposition. Think about it - all you have to do is try to reach the page, and if you can't reach it, chances are it's not there. ASP.NET provides plenty of network functionality as part of the framework - this is one of the things the framework was designed for, after all - network computing - so why not?

In this case, the class we need to look at is the WebRequest class, a rather aptly named class which allows you to request documents over HTTP or HTTPS. The ASP.NET documentation (which you shoudl have handy, if you don't want to recieve everyone's wrath online) explains it quite well, but here's my example.

First, we set up a little form into which one can enter a URL. Let's pretend this is part of my 'links' section on this site. Into this textbox goes the URL, and the form gets submitted. Then, on submission, we simply request the page. Now, if it's successful, there's all manner of things you can do. You could use Regular expression to strip out the title tag and meta tags (this is explained in the ASP section), you could cache the page for later. You could pull all the text and perform analysis on it, like a mini-google to rank the page based on its content. Of course, if the requestisn't successful, then you can reject the link outright, and save yourself from the old dead-link syndrome.

Here's the simple checkURL function which is called on submission.

void checkURL(Object o, EventArgs e)
{

pnlDone.Visible = true;
pnlStart.Visible = false;
WebRequest objRequest = WebRequest.Create(strURL.Value);
lblExists.Text = "Link unchecked";
try
{
WebResponse objResponse = objRequest.GetResponse();
lblExists.Text = "Link exists";
objResponse.Close();
}
catch(WebException ex)
{
lblExists.Text = "Link doesn't exist ";
}
}

Things to note. The first thing to note is that my form is in one asp:panel, and the results are displayed in another, hence I do the show/hide shuffle at the start. Then I request the URL in a try/catch block. If the page is not found, the code will throw a WebException, which will usually in this context be a ProtocolError exception, though we're not concerned with that in this simple code. IF the exception is thrown, we tell the user. If it's not, well, we can go on to add the link to our database, carrying out whichever operations we want to on the way. Very simple, eh?

This article was inspired by a recent thread on ASP.NET, as a number of coming articles will be. These articles won't be long on content, but you can be sure the answers will be relevant to real-world problems, so keep checking back for some solutions inspired by real people.