Pages

Saturday, June 27, 2009

Future of Searching and RSS

I'll admit I was excited when the Google API was made available for public use. Nice idea and opens up some cool new ways to integrate searching into your applications or websites. That is, as long as you don't exceed the allowable 1000 queries per day as per the developer license. It was easy enough to use but it was still not enough to get me that fired up about using it. I have that same excitement now about the MSN Search (beta) site. But this time things are different. There is no daily query limitation, there is not even an API. MSN Search allows you to take any query/search and get the results back as RSS/XML. Now we're talking!

Append the QueryString “format” parameter to specify that you want the results back in the form of RSS. For example, if I do an MSN search for “Ryan Farley”, I'll end up with the following:

Now, if I want that same search back as RSS/XML I simply add the format parameter to the query string as follows:

Not too shabby. But, where this starts to get really cool is how easy it is to seamlessly integrate searching into your own websites, and your users won't even know that MSN is being used for the searches. No redirects to some MSN Search page or anything. You just take the value that they are searching for, append your site URL to the search and then display the resulting RSS from the MSN Search however you want, on your own page, with your sites style. For example, if I wanted to search my blog for something like IDisposable - and get back the results as RSS/XML I would use the following:

If you wanted to make things really easy on yourself, you could use something like Scott Mitchell's RssFeed ASP.NET server control to easily display the returned RSS with no coding on your part. All you have to do is form the search query string and set it as the DataSource to the control and you've got instant searching for your site, all courtesy of the MSN Search.

Setting the Value of a TextBox with TextMode=Password

When the TextMode property of an ASP.NET TextBox is set to Password the value set in the Text property will not display at runtime. This can be a pain, however it is actually by design to prevent the unmasked password from being displayed in the HTML source of the page.

While the security reasons are good to not display the masked password value, leaving it unmasked in the source, it is also necessary at times to display the masked value in the TextBox. For example, a user profile page where the user has the ability to change their password. It makes sense to display it there. After all, the user has already authenticated to get to the page (although the value is sent with the data to the browser and could easily be sniffed).

Security reasons aside, you can work around this by adding the password value to the control as as Attribute. Since the TextBox renders as an HTML input control, you can set the value attribute easily, just as you would set the Text property.

PasswordText.Attributes.Add("value", "ThePassword");

Use this to set the value, instead of setting the Text property. You can still read the value from the control via the Text property.

Thursday, June 25, 2009

A Simple Image Slide Show

This is a simple C# application that can open and view images, and show the images one by one in a slide show. The purpose of this article is for a beginner to know how to create an image slide show using timers, in C#.

Click here for details .......

Tuesday, June 23, 2009

A Complete URL Rewriting Solution for ASP.NET 2.0

This article describes a complete solution for URL rewriting in ASP.NET 2.0. The solution uses regular expressions to specify rewriting rules and resolves possible difficulties with postback from pages accessed via virtual URLs.

Why use URL rewriting?

The two main reasons to incorporate URL rewriting capabilities into your ASP.NET applications are usability and maintainability.

Click here for more details ......

Monday, June 22, 2009

Howto: Create a Custom Control in ASP.NET (C#)

Creating custom controls can save you a lot of time and effort when building an application. The built-in sever controls provided can do just about anything you need them to, but sometimes it takes a great deal of coding (hacking) to make it do exactly what you want it to do. Consider the possibility that you need a textbox control that you would like to be able to assign a readony property to it so it either renders as a regular textbox if false or plain text if true.

You may also want a textbox that will cause it's on "OnTextChanged" to bubble up in the "GridViewCommandEvent" of a Gridview control. By default the textbox does not support that.

Click here for details .....

Saturday, June 20, 2009

Accessing the Html Header in ASP.NET 2.0

Taking a look at the Page class there is a Header property that looks tempting to be able to do something like dynamically add a stylesheet. The problem is that when you type in Page.Header it doesn't appear that you have full control over the header, even though there is the ever so tempting System.Web.UI.HtmlControls.HtmlHead class. What I had been doing is throwing an id and a runat="server" onto the head tag in my HTML, which I really didn't like because an id tag on the head tag isn't valid XHTML 1.1.

Today, a break through. This has always bothered me, so I took a deeper look and it turns out that Page.Header is defined as IPageHeader. Perhaps, just maybe I could cast Page.Header into System.Web.UI.HtmlControls.HtmlHead. And sure enough, it worked great. Anyways, I feel a little silly about not figuring that out sooner but now that I've gotten this working I feel much better. Anyways, here's some example code to add a stylesheet to a page:

Dim header As Web.UI.HtmlControls.HtmlHead
header = TryCast(Me.Page.Header, Web.UI.HtmlControls.HtmlHead)
If header IsNot Nothing Then
Dim link As New HtmlLink
link.Attributes.Add("href", "~/whatever.css")
link.Attributes.Add("media", "screen")
link.Attributes.Add("rel", "stylesheet")
link.Attributes.Add("type", "text/css")
header.Controls.Add(link)
End If

Tuesday, June 16, 2009

Make your web application run faster

It is easy to develop your own ASP.NET web application. But making it do some useful things for your users while keeping the design simple and elegant is not so easy. If you are lucky, your web application will be used by more than a handful of users, in that case, performance can become important. For some of the web applications I worked on, performance is vital: the company will lose money if users get frustrated with the slow response.

There are many factors that can result in bad performance, the number of users is just one of them. As a developer in a big corporation, you usually don't have a chance to mess with real production servers. However, I think it is very helpful for developers to take a look at the servers that are hosting their applications.

For more details, Click here ......

Programmatically Manage IIS

This article is about managing IIS programmatically. It provides a class library that represents the tree hierarchy used by IIS for its every aspect. The project is accompanied by a Windows Forms applications that is used to pinpoint and extract any data required.

Click here for details .......

Sunday, June 14, 2009

Dynamically Adding Meta Tags in ASP.NET 2.0

The HtmlMeta class is provided to created meta tags dynamically in your page header.

You can easily create a HtmlMeta object and add it to the Controls collection in the HtmlHead class exposed via Page.Header.

Here is the sample:

Custom Adding Title Tag :

Me.Header.Title = "Title Of Page Here"

Custom Adding Meta Tag :
Dim metaDescription As New HtmlMeta()
metaDescription.Name = "description"
metaDescription.Content = "A description of page here."
Me.Header.Controls.Add(metaDescription)

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.

How To Generate PDF Files Dynamically Using ASP.NET

There are currently many ways to generate PDF files dynamically. The most widely known way is to use ASP together with Acrobat Full Version (4.0 or 5.0) and Acrobat FDF Toolkit.

With Microsoft .NET many developers are wondering about how to use ASP.NET instead of ASP to tackle this same situation. To my surprise I could not find any related documentation from Adobe.

I asked this question in many forums and no one had an answer for me. I had to roll up my sleeves and to my surprise--it's not so difficult. Now, I will make it even easier for all of you.

Click here for details ......

Friday, June 5, 2009

LINQ Code generator

Introduction

LINQ code generator is simple application which generates SQl based LINQ codes by taking some inputs. As LINQ is new to many developers This basic generator is used to generate and test basic Sql based LINQ codes in less than Minutes.

Background

as i started working on LINQ,I came to a very strong conclusion that LINQ has great future.But found it needs more changes still to be done by microsoft.

Click here for download .....

Running ASP.NET websites outside of IIS

Ever come across the need to demo your ASP.NET website on a PC that didn't have IIS installed or access to the internet? OK here is a simple application that can do exactly that. Using the internal web server that Visual Studio uses to run and debug websites could also be used outside Visual Studio to run your web sites on it.

However there are many more uses for the internal web server that is included in Visual Studio if you can think of it.

Click here for details .....

Session Vizualizer for Visual Studio 2005

The purpose of this tool is to let developers easily analyze Session content during debugging and also browse stored objects. For this, a simple interface was built, and a PropertyGrid control is used. In large web applications, there are situations when developers leave old objects stored in the Session, and these are disposed only when the session in ended. Using this tool, it is easy to see the Session content and improve the code that manages Session content.

Click here for details .....

Wednesday, June 3, 2009

RequiredIfValidator - Extending from the BaseValidator class



When writing ASP.NET pages that need to be validated before submission, I find myself coming across controls that only need to be validated if another control contains a particular value. A classic example of this is an "If other, please specify" field. Typically, you'll have a combobox that contains a list of choices, and at the end of the list is an "Other" item. If the user chooses "Other", you'd like them to specify exactly what "Other" means.

Click here for details .......

Generate an Image with a Random Number

We need to check if it is a real person who is registering on our Web site. So we decided to generate an image with a random code, hidden for robots, and feed it to the browser instead of a page response. We show it in our registration form, and let the user enter the code to check it.

Click here for details .....

Tuesday, June 2, 2009

Generic Search Web User Control with event



This control provides a functionality to search a table based on the name column. The user interface uses DataGrid to display the records and the control fires an event trapped by the container to process the request.

Click here for details .....

Web Page Source Transmitter: Get The Page As The Customer Sees It

Web applications without bugs - it is a myth.

Every developer has many problems when he should reproduce a customer's bug. Usually, the customer cannot provide enough information about conditions before an exception (field values he entered; page which was opened before an exception, etc.).

It will be very useful if the application can produce (restore) the source of the opened web page with the data entered, as it was before an exception and store it (e.g. into a database). In this case, the developer can get the source of the page (e.g. from the database), put it to an HTML file and open it in a browser. The developer will get a copy of the page as it was before the exception.

Click here for details ......

Displaying Collapisble Data in GridView

The code is intended to make a high performance GridView that has minimum postback operations, as well as has a collapsible client-side feature to show additional details for a row.

Click here for details .....

Monday, June 1, 2009

PleaseWaitButton ASP.NET Server Control



It is often useful upon a form submission in a web application to display a "please wait" message, or animated .gif image, particularly if the submission process lasts a few seconds or more. The application inserts the uploaded data from the spreadsheets into a database. The upload/insert process may only take a few seconds, but even a few seconds on the web is a noticeable wait.

When testing, some users clicked the upload button repeatedly; it was useful to provide a visual clue that the upload was underway. For that matter, it was useful to hide the upload button altogether, preventing multiple clicks. The control presented here, a subclass of the Button control, demonstrates how client-side JavaScript code encapsulated in an ASP.NET server control can provide such functionality conveniently.

Click here for details ......