Displaying Multi line wrapped text in web form

Hi,


Many a times there is requirements for us to display text in multi-line in web pages. The first try that most of the people do is by giving a fixed width to the label. But this never works.

Height and Width works only for block level element. Label is an inline element and hence setting width does not work.

 

What you can instead do is use a textbox with CSS that will make it looks like a label. To do this we need to set the following properties.

Continued...

Comparing different type with Double Equal operator and Equal method

Hi,

 

There are normally two ways to compare 2 objects. One by using == operator and by using the equals method. But these two are not same in the way they implements the comparison.

 

The difference is there in the type of object (reference type or value type)

 

Value Type

Continued...

How to know when the application is running in Localhost or debugging mode

Hi,

Most of the time (If not all) when working on the project we view the website with the help of localhost in debugging mode. Many a times when working on some modules, for solving small problem, we want to write some code that should execute only when running in the localhost or debugging environment.

Normally developers would write the code and then take it as their responsibility to remove the code before the code goes to the next environment. But some time we might make a mistake of not removing the code and letting it go to the next environment, which can cause a lots of trouble.

In these kinds of circumstances and Asp.Net developer can take help of the IsLocal method of the Request class. The method will return true in case the application is running from localhost.

Continued...

Create PDF, Excel or Word File from Crystal Report from Code

Hi,

Some times when working with crystal report viewer you do not want to show the report to user in raw format but instead you want to pass on the report in PDF or other format without requiring user to do extra click. This can be done easily in Dot Net with the following code.

MyReport report = new MyReport();

DataSet ds = GetData();

report.SetDataSource(ds);

report.ExportToHttpResponse(ExportFormatType.PortableDocFormat, Response, false, "ExportedReport");

 

Continued...

Path.combine to combine two paths and backslash in second parameter

Hi,

system.IO.Path comes with many good function to work with the File system. some of them are ChangeExtension, GetDirectoryName, GetExtension, GetFileNameWithoutExtension, IsPathRooted etc.

The system.IO.Path.Combine is also include as a function in system.IO.Path to combine two paths provided to it. A few days back I was working with it to add paths provided by user. But I started getting erros where by sometimes the path would not be combined and only the second provided path was returned. After doing some research on this I got to the root of the cause.

The problem was only occuring when the second path provided in the method was starting with "\".

To make my understanding more accurate I made a small console applictaion to show what would be the result in differenct scenarios. Below are the situation and the output I got for them.

Continued...

Adding a new control with the help of Page.ParseControl method

Hi,

 

Sometimes we might have a requirement where by we need to parse the tags and create some controls with that in asp.net.  Think of a situation where you do not what type of control will be create. You need to pass the control from an xml file/ or database. There can be many properties to the control, which will be passed. Passing these properties individually can be difficult, because you do not the kind of control itself.

 

In this kind of situation if we can pass the full formatted control tag as a string which will be parsed and updated then it can be great as we can easily apply all the property we want to apply.

 

Continued...

goto keyword in C Sharp and its use to break nested loop
Hi,

 

Two days back, while discussing with a friend came a small interesting (programming) situation where he wanted to stop (break) a loop which was inside another loop.

 

You can think of the situation as he was first looping through all the rows in a grid view and then in the entire column in the grid view. Now he was trying to look into the text of each cell, and if the text matched a given value, he needed to break from both the loop and execute the statement after the loop.

 

His first idea was to use a flag which will be checked in the outer loop every time to see if the value has been found in the inner loop. The code would be something like below.

Continued...

Scheduling a call to URL using windows scheduler

Hi

 

I have used windows scheduler a lot of time while working with Sharepoint. Most of the time this was used to run some console application (which would work in off peak time to do some data management). But few days back, I had a requirement where by I wanted to schedule a windows scheduler to make a call to the page. The page would internally do some work on the load event.

 

But windows scheduler would not take the URL or a shortcut to the URL as a way to be scheduled. It needs an application/ batch file etc to be scheduled. So I had to think of a different way to either schedule it in windows scheduler or some other way to schedule the task of calling the web page.

Continued...

Resource kit for creating web 2.0 Application and services from Microsoft called KOBE

Hi

 

Microsoft has come with some resource kit for planning, Architecting implementing Web 2.0 applications and also services. The resource kit is named Kobe.

 

You can visit the same from the following link.

Continued...

Using HttpWebRequest class to make web request against Http server

Hi,

 

Many a times comes a situation, where we have to make call/request to another page through http protocol. The requirement might come when you want to fetch data from another page through http protocol, or just make a request to start some process which gets started on the page request itself.

 

Continued...

Programmatically Embedding another file to the word document

Hi

Many a times we want to embed some document in the word file, with the help of Insert-> File-> Select File menu item. This will copy the content of the file to the word document. This can also be done programmatically. 

String LocationOfFileToMerge = "C:\\Myfile.doc";

range.InsertFile(LocationOfFileToMerge,ref oMissing, ref oFalse, ref oFalse, ref oFalse);

We can also embed the document in the word file instead of copying the text of the document. In this case you can embed any kind of document.


Object NameForLabel = "File Name";

Continued...

Word Automation and Basic text formatting option

Hi,

when you start working with word programmatically, many a times you will have to add some text in the word document with formatting. Word automation gives you easy way top format the text that you are writing in the Word document programmatically.

To make the same impact as would an enter button in the word document we can use the following code.

oWord.Selection.TypeParagraph();

Basically this will enter a new paragraph in the word document. But you are in a bullet mode than this will take you to next line and also add the next bullet in the sequence.

Some of the common word formatting functionality can easily be performed with the help of word automation.

Continued...

Word automation and find and replace in Word document

Hi,

In My last two posts I talked about

·         How to open and close a word document programmatically.

Continued...

Saving word document in different format using Word Automation

Hi,

In my last post I talked about how to open and close a word document programmatically. In this post I will talk about how we can save the word document.

While using a word document there can be three kind of save functionality that can be required.

1.       When we open an existing word document and make some changes to the word document and save the word document.

Continued...

Microsoft word 2007 automation with C Sharp

Hi,

Some time in our project we need to work with word (winword) document programmatically. Word provides a good way to automate nearly all the functionality that can be used through interface.  The process of programmatically working with word document is commonly termed as word Automation.

I will be using a series of blogs to discuss some of the functionality that can be achieved through word automation. In this Blog I will discuss how we can start programmatically open a new or and existing word document and close it.

To work with word 2007 automation we need to have the word 2007 installed in the machine where the application will run. When we install the word 2007, it also installs with it the com component required to automate word 2007.

Continued...

Large Blob Data problem in Oracle stored procedure

Hi,

Few days back I was working with Oracle database and one of my stored procedures which was inserting a blob data to the database.  But I started getting a strange when the data in the blob data type got large. For large blob data I was getting the following error.

ORA-01460: unimplemented or unreasonable conversion requested.

The system would work consistently for small files but for large files I was getting this error.  After Doing a bit of Google I found that this is a drawback of using stored procedure in Oracle database.  If you try to pass over 32 Kb (or greater than 32512 char of string) then oracle will give this error in case of Blob data type.

Continued...

Asp.Net List Box control and flickering issue

Hi,

Last few days I was working on a page which had lots of list box in it which had multi select option. My master page also had a Menu control for the navigation purpose.  One major problem I was facing was with the flickering of the List box as soon as take my mouse over the menu.

Continued...

Handling Dropdown list inside Gridview with Autopostback

Hi,

Many a times there are circumstances where by we need to use dropdown list inside a Gridview and also handle the index changed event of the dropdown list. The easy example of this kind of requirement would be when we nee to fill another dropdown list in the same row from the value selected in the first dropdown list.

We all know that the dropdown list does not support command name property so you cannot handle the event in the row command event.

Continued...

Sorting and Paging Gridview without datasource control

Hi

Many a times while working with Gridview we want to work with the paging and sorting functionality without using any datasource control. Gridview is flexible enough to perform these tasks without the use of any datasource control and only a few lines of code.  

For paging a Gridview manually we have to handle the Gridview’s PageIndexChanged Event.  In the event we need to change the PageIndex of Gridview to the page that user has clicked and again bind the Gridview.

Continued...

Creating a list of the data cached at a point in the asp.net Application cache

Hi,

 

We all know about the use of caching in our application. With good use of cache we can increase the performance of the application considerably since application does not have to process the stuff again and again. But if we use too much of caching in the application, it can be problem. After all the data in the cache has to be stored in the memory and most of the application have limited memory. And more so in case of shared hosting.

 

Continued...

Going mouse less using keyboard shortcut in Asp.Net

Hi,

 

Many a times when working with the Web Application you would like to give the user the comfort of getting the job done without using the mouse. It can be of great use to the user if they can perform many tasks using the keyboard in a web application. If you have used Gmail you would know how easy it can be to select mails using some key.  This feature can be implemented in Asp.net also very easily.

 

Continued...

Content Page referencing content in Master Page

Hi,

 

Many a times while using a master page we want to refer content, Controls and properties in Master Page while working in Content page. We come across requirement where by we can change or access the values of controls residing in Master page when we are coding in the content page itself.

 

We can write code in the content pages to access properties, methods and controls in the master page, but there are some limits to it. We can only work with those properties and methods which are declared public. For controls we can refer any control on the master page independent of referencing public member.

Continued...

Redirect and refresh a page using the Meta tag

Hi

 

Many a times we have a requirement where by we want to make a pager refresh by itself at a certain interval. We may also want to redirect the page to another page after a certain amount of time. I know we can do this with the help of Asp.Net Ajax Extension’s Timer control. But that can only be used when you are using Ajax in your page and more importantly should be used when you have requirement to update some small section of the page. For this requirement we can simply use a Meta tag in the Page header.

 

Continued...

Obsolete API list for Dot Net framework 2.0

Hi,

Microsoft has come out with a list of APIs which have become obsolete in the .Net Framework 2.0. The same can be accessed from: .NET Framework V2.0 Obsolete API List. The list also contains alternate APIs that can be used for most of the obsolete APIs. In case there is no alternative suggested then this means that there is no replacement for the API.

You can also check the list grouped upon Asembly Here and Grouped by Namespace here.

Vikram


Using ObjectDataSource and passing Object as a parameter

Hi,

 

ObjectDataSource was a great addition to Asp.Net 2.0. But when working with asp.net 2.0’s ObjectDataSource had one limitation when working in Visual Studio designer. When working with ObjectDataSource we cannot pass object as a parameter. We always need to pass string, integer etc as the parameter.

 

But many a times we want to pass some object as parameter instead of passing all the values as string. Passing all the values can also be difficult when working with large number of columns.

 

Continued...

Concurrent request and how session behave

Hi

 

We all have worked with Asp.Net session objects in some point of time. An interesting question came in between the discussion with my colleagues on concurrent request and session state.  Here is what I have to share with all on session and concurrent users.

Continued...

Use Retail attribute to define that all the application run in release mode only

Hi,

 

Lets say you are running multiple application in a single machine, and want to make sure that all the application run in the release mode (debug is false, page output of trace is false etc..). These settings can easily be changed in the web.config. and you do not want any application to run with these setting even by mistake.

Well Asp.Net has a way for that also. You can set the attribute retail to true in the deployment tag inside the System.Web tag in Machine.config.

 

<System.Web>

   <deployment retail=true />

Continued...

Template column and HTML Encoding

Hi,

 

I have seen this question a few times in the forum so decided to blog on that. Many a times we store HTML characters in the database. When we want to show these values in the Gridview, detailsview or similar control.

But when we are displaying the value we want to encode (or sometime even decode) the value displayed. With bound column we get a property to HTMLEncode the value, but what do we do when we are using template column.

 

When we are using template Column we have two ways to HTML Encode (or decode the data). Firstly we can do the encoding in code in the rowdatabaound event

Continued...

Using 301 redirect in the Search Engine friendly web world

Hi,

When working in a Search engine friendly world, every small detail in your page and programming matter on how you can move your site in top position in the search engine. One of those important matter is how we redirect a page to another page.

 

By default we use response redirect which causes a 302 Redirect. For a search engine 302 redirect means that the document has only been temporarily moved and not permanently, hence the search engine will continue to index that page and show it in search result.

Continued...

Multiple column sorting in dataview

Hi,

 

Yesterday I was wondering through the msdn and found an interesting stuff that I did not knew before. I have worked with Dataview many a times and know how to work with it sort property. The sort property takes a string. The string is the columnname on which the dataview will be sorted.

 

What I did not knew was that the dataview can be sorted on multiple columns using the sort property. For sorting the columns on multiple columns we need to separate the columns with a comma. To define the sort direction we can use ASC or DESC after the column name.

Here is an example on how to sort a dataview in multiple columns

Continued...

Showing row number in Gridview

Hi,

 

A few days ago some one asked me this in a mail. After thinking on this a bit I decided to make a post as I thought this might be useful to many. Many a times while using a Gridview or a Datagrid we want to show a row number along with the Row, so that its easy for the user. The row number should always start from 1 no matter what the sorting is.

 

Continued...

Less known important functionality of Request Object

Hi,

Today I was discussing with my friends about some of the cool stuff available in the request class but rarely used or talked. After the talk I discussed on posting them in the blog.

The first in the list is the Request.AcceptTypes. The property returns an array of all the mime types supported by the browser. The results were interesting for me. The number of mime type supported by IE7 are far more than Firefox. The extra mime types included in IE are image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-ms-application, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword. This means that IE can easily recognize these file types and open them in correct application.

Continued...

C Sharp how to find if a given string is a number or not

Hi,

When using JavaScript many a times we have a requirement to find if a value is number or not. With JavaScript its pretty easy, as it gives us a function isNaN which tells us if the string is a number or not. But how can you tell in C# if a string is number or not?

When I confronted with the problem, one of the solution was to use the int.Parse() method inside a try catch block. Below is an example of what I meant

try

{ int.Parse("5000"); }

catch

{ }

Continued...

Creating a generic function to work on all the similar controls in a page using the delegate

Hi,

Of late I have found this one question related to finding controls inside the page dynamically and apply some similar function to them. Like put a css class to all the textbox (or for that matter any control) in a page. Remember a page can have textbox as a control directly under it, or the textbox can be inside another composite control (like login control, gridview, detailview) inside the page.

Many a times we do not want to do this work for individual control but rather have a function, which will do this for all the control in the page. This way it becomes more maintainable and easy to implement.

Continued...

Finding more about Asp.Net Environment using the GetEnvironmentVariables method of Environment class

Hi,

What do you do when you need to find the values of various environment variables in the system like USERDOMAIN, PROCESSOR_ARCHITECTURE, COMPUTERNAME, USERNAME, PROCESSOR_IDENTIFIER, etc. well with asp.net this can be a very simple Job. You can get all these value along with a set of other values with the help of

Environment.GetEnvironmentVariables().

The static function returs the IDictionary collection of the Envirement varibales. To view the value you need to know the key for each value. But its not always known to us.

So what you can do is bind the dictionary to a grid view and see all the keys and values avilable.

Continued...

Preventing one click attack on you site by using ViewStateUserKey

Hi,

One of the very rich security feature and also one of the least known is the ViewStateUserKey. The key is used to add an identifier to the individual user in the viewstate variable for the page.

The value of the variable needs to be set in the page’s init phase. If you try and set the value in page load then it will give an error. Normally the value will be set to a value which is unique to individual users. Setting a constant value for all the users is equivalent to keeping it null. Normally we can fill the value with the userId or sessionID. For many technical reasons it is best to use the sessionID for the same (SessionID are unique, varies from time to time and are different from individual users.).

Continued...

Subkeys scope limitation of a cookie in Asp.Net

Hi,

In My last 2 posts I have talked about the overview of cookie and how to read and write with the help of a cookie. In this post I will talk about some of the more advanced work that can be done with cookie in Asp.Net.

Many a time we just don’t want to store some values in cookie but a collection of name value pair in a cookie. Remember that there are many limitations in number of cookies you should use. If we use more number of cookies in our application then the possibility of browser deleting the cookie will increase. Hence we should try and use less number of cookies and utilize a cookie to store maximum amount of data.

Continued...

Asp.net Reading and writing value in cookies

Hi,

In my last post I wrote about and overview of cookie, there basic use and some of their limitation. In this post I will talk on how do we read and write cookies with the help of Asp.Net.

When a browser makes a request to the server it also send existing (at the browser end) cookies information for that website. In Asp.Net the HttpRequest (also referred as Request property in the page class) objects contains a collection of all the cookies sent by the browser.

We can read the cookies from the request object like this.

if (Request.Cookies["lastVisit"] != null)

Continued...

Asp.net cookies an overview

Hi,

When working with a web application many a times we want to store the client specific data on the client side only. This helps in showing personalized data for the client. The session maintained by default is also done with the help of the session cookie only.

In a layman developer word a cookie is a small amount of data that is passed between the client and the server in the request and response. The data in the cookie can be read in interpreted by the server and is sent to the server whenever the user visits the same site.

But remember maintenance of cookie also depends on the user. Many user can turn there cookie off or the users can delete the cookies in there cookies. Moreover client can read the information kept in the cookie. That is why cookie cannot be used to store sensitive data.

Continued...

How to read XML data sent in a post request

Hi,

A few days ago I posted about how we can send XML data as a post request to any URL. You can read the stuff here. After that many people have asked me on how we can read the data when data is sent as a Post Request.

Reading data when it is sent as a post request value is very simple. We use the Request.InputStream to read the incoming stream request. Here is a glimpse of code to work with the same.

byte[] b = new byte[Request.ContentLength];

Request.InputStream.Read(b, 0, Request.ContentLength);

Here we first get the length of the request and then read the same in an array of byte.

We can convert the bytes into a string by using correct encoding. (Note: I am using the UTF8 encoding for example).

Continued...

How to prevent client cache and getting a server request even when back button is clicked

Hi,

Many a times we do not want browser to show data from cache. For example when user hits the back button of the browser, the browser shows the last page from the cache and does not make a post back to the server. (This is why when some one clicks on the back button of the browser the system looks so fast).

But many a times we do not want the browser to show data from the cache. There are requirements where the data is very dynamic and if browser shows the data from the cache then it can give wrong indication to the user.

Controlling the back button of the browser is not such a good idea because we are trying to stop the user at the client end.  But what we can do is ask the browser to not to cache the page in the client end and always make a call to the server before showing the page.

This can be easily done by expiring the response. Here is the code for the same.

Continued...

How to create a POST request and send XML data

Hi,

Many a times when we are working with the third party services we have to pass the data to the third party over the web. Most of the times we pass the data in the querystring. The data is passed in a get request along with the querystring. The third party takes the value from the querystring and process the data.

But many a times the data need to be passed in the Post method. Many a third party component takes the data in XML format in the POST request. In these cases we have to pass the data as XML string in the post request. Here is an example on how to pass XML in the post request.

string xml = “SomeXML Data”;

string url = @”http://www.vikramlakhotia.com/HomePage.aspx”;

WebRequest request = WebRequest.Create(url);

Continued...

Using tag mapping to change the mapping of user control through out the application

Hi,

Lets say you are working in a fairly large asp.net application. You have about 200 web pages. Now because of situation (or clients request) you want to change all the textbox or button control to some server control or user control.

This can be very very tedious JOB if you are using Asp.net 1.X. But if you are using Asp.net 2.0 or Asp.net 3.0, wait, there is a very easy way to get this done.

Tag mapping seems to be made for these kinds of situations. In asp.net 2.0 we can map tags in web.config. With the help of tag mapping we can remap the tag types to other tag types at compile time.

The remapping will make all the original tag to use the new mapping for all the pages and user control in the asp.net application coming in scope of the configuration file.

Continued...

Reducing the size of HTML by removing the ID of control when not required

Hi,

Many a time we have many server controls with long Id which are never required once there value has been set. We normally disable their viewstate to reduce the size of both viewstate and the page. Especially if these controls are inside nested repeaters (or grid view or likes) the view state size can be huge.

Making the viewstate false reduces the size of the viewstate but when these controls are rendered they render with a long ID. If we are using a master page than the ID of such a label (or other controls) would be something like Ctl100_ + Contentplaceholderid + Repeater Name + ct102 + the label of control. If the repeater is nested than the name of ID can be very very large.

Continued...

What are the limitation of different trust level in a application

Hi,

Most of us have worked with web application and one thing which is very commonly heard is of trust level at which the application is running. I have read many articles which talks (in some way or the other about trust level of the application). But I also feel that most of the developers do not know the limitations or capabilities of different levels.

Here is a list of major restriction and capabilities for an application at different trust levels.

Full trust –

No restriction is imposed on the application by the code aces security.

High trust  -

Continued...

Difference between ASP.NET Server Controls and HTML Server Controls

Hi

ASP.NET Server Controls

Advantages:

1. ASP .NET Server Controls can detect the target browser's capabilities and render themselves accordingly. No issues for compatibility issues of Browsers i.e page that might be used by both HTML 3.2 and HTML 4.0 browsers code is written in the Server Controls.

2. Newer set of controls that can be used in the same manner as any HTML control like Calender controls. Without any need of Activex Control without bringing up issues of Browser compatibility).

3. Processing would be done at the server side. In built functionality to check for few values(with Validation controls) so no need to choose between scripting language which would be incompatible with few browsers.

Continued...

Multiple session updating the application variable at same time

Hi,

Many a times we want to keep some values in our application, which should be available Application Wide. We normally keep these values in the application variables. This is very handy and fast to use.

One of the examples of use of Application Variable that I normally use is a Boolean value describing if the application is running locally or Live (Production). The value is retrieved in the Application_start event from the web.config file. This is very handy as at many point in the application I keep a check on the work to be done based on this value. And I do not have to refer to the config file all the time to know if the application is running locally or on production.

Writing and reading to an application variable is very simple. We can write to an application variable like this.
Application["Local"] = false;

Continued...

Asp.Net 2.0 referring to another page, user control with the help of Reference tag

Hi,

In Asp.net 2.0  if we want to create the object of another page  (in the same application) then we can not do it. We get a compiler error in this case. The reason is that each page is compiled into an assembly (We can also make the directory to be compiled in the same assembly). Hence the two pages might not be in the same assembly. And hence we are not able to create the object of another page in the same web application in another page (As they will not be in the same assembly).

But many a times we want to create the object of another page in the code behind class. I know we can use a base page (will be kept in App_Code folder) for all class and derive all the pages from that class. Now we can create the object of the page by typecasting the base page. But this will not solve the entire problem. As we will not have all the methods of the individual class.

Continued...

Finding the Virtual path of the web Application

Hi,

Many a times we want to find the Virtual path of the Web Application. Getting the virtual paths local to server is pretty straight forward Page.ResolveURL("~").

If you require the same in the BLL, then you have to use the System.Web.HttpRuntime.AppDomainAppVirtualPath

Remember if the web application is in the server root then the following command will return “/” and if the web application is not in the root folder then the command will return the path of the root folder without the “/” in the end.

Vikram


An overview of use of predicate with generic List

Hi

Predicate are type of filter which can filter data based on certain criteria. Predicate is a generic delegate which represents a method that defines a set of criteria to filter records in a generic list.

Lets take an example of a generic list of string.

List<string> strName = new List<string>();

Now let say we want to fetch those data which starts with V. Without predicate we would write something like the code below.
for (int i = strName.Count - 1; i >= 0; i--)

    {

        if (!strName [i].StartsWith("V"))

        {

           strName.RemoveAt(i);

        }

Continued...

Passing ReadOnlyCollection using the AsReadonly method so that user cannot modify the list

Hi,

This was new to me so as always I decided to share with all. The generic List has a method AsReadonly. The methods can be used if you want to pass the list as readonly. The return value of the method is a ReadOnlyCollection.

The ReadOnlyCollection acts as a wrapper around the list. The only difference of a readonlycollection and a list is that a readonlycollection has a wrapper around it which prevents the modification of the collection.

If there are changes made to the underlying collection, the changes will be refelected in the readonly collection.

Let’s say you have a private collection (list) and want to expose it as read only format. This is when this method will be useful.

Vikram


Asp.Net 2.0 Page Element attributes and there meaning

Hi,

In asp.Net 2.0 there are many attributes in the page tag itself. Each attribute has a special meaning to it. These attributes are defined in the page so that we can specify them for specific pages. Most of them are also defined globally so that we do not have define them in the page.

Here is a list of attributes of the Page Tag.

asyncTimeout – This is an optional attribute to define the timeout for the asynchronous handler during asynchronous processing of the page. The default value is 45 sec.

autoeventWireup – This is also an optional attribute that defines if the events in the page are automatically enabled. The default value is true. This means

if we define a Page_load(with same signature) method in the page class, the event will be automatically be attached with page load method.

Continued...

Logging the exception of the Asp.Net application with the help of HttpModule

Hi,

One of the most critical aspect of and asp.net application is exception handling. When an application is there live on the web there can be an exception happening. These exception needs to be logged so that they can be rectified later.

There are many inbuilt ay in which this can be done. Like we can handle the exception at page level, or at the application level or even better create a simple reusable module that can be used in multiple applications.

In this post I will show how we can log the exception in an application. There are three prominent places where we can log the exception.

1 In a text file (or in XML format)

2 In a Database (I know text file is also a database but I meant a RDBMS)

Continued...

Session_End and mysttries on when does it fires in Asp.Net

Hi,

Following my post on few interesting things about session in Asp.Net many people asked me about the Session_End event. You can read the earlier post here.

Many people have asked me on exactly what are the reason for which the Session_End event fires. So I thought I would write a post on the same.

Continued...

Asp.Net and Session – some Interesting Facts

Hi,

Yesterday I was discussion with my colleagues about session and a few interesting things popped up. So I thought I would share the same with all.

If we have the session state enabled and we do not store anything in the session then the session Id will change every time a new request is made. This also means that a new session is created every time. But the sate is never saved as there is nothing to save. Note the session_Start event will not fire for every request. The session_start event will only fire once.

Another interesting stuff about session Id is that it does not changes after we have called the Session.Abondon() method or when the session times out. Even though Session State expires but the session ID remains same. The session Id will last as long as the browser session does.

Continued...

string.compare and string.Equals the difference in usage of culture

Hi

In the string class we have 2 methods to compare the string. I see most of the developers get confused between the 2. Both string.Compare and string.Equals methods are used for string comparison but they significant difference between them. The use of wrong method can lead to globalization and security issues.

String.Equals perform an ordinal comparison while string.Compare performs a culture sensitive comparison.

Continued...

Working with different path in the Request Object in Asp.Net

Hi,

When we are working on an asp.net Application we have to work with various type of Path. These paths are present in the Request Object. Each path has a different meaning and way for representation. Here is a list of different kind of paths used in Asp.net

Application Path – Will return the root path of the application. This is used to get the application path. This can be found in Request Object. By the default the

CurrentExecutionFilePath – used to get the virtual path of the current request. The difference from the FilePath property is that if there is a redirection of the request in the server code (Server.Transfer) then this will return the correct value. For example it might return the value /Vikramlakhotia.com/MyAdm/LogFeed.aspx

FilePath – will provide the Virtual Path of the current request. (See the difference with CurrentExecutionFilePath above.)

Continued...

Asp.Net Web Application different file types

Hi,

A web site Application can have multiple files of multiple file type. Many of these are managed by Asp.Net and many by IIS itself. File types that are managed by the Asp.Net are mapped to AspNet_isapi.dll in IIS. The file types that are not mapped to AspNet_isapi.dll are not managed by asp.net but by IIS only.

Here is a list of all the file types that are managed by Asp.Net.

.asax – The common most example is the Global.asax file. This normally contains code that is derived from HttpApplication class. The file contains application level event that are raised by application like Application start, application end etc. The file has to be kept in the root folder of the application.

.ascx – This file type is used to create web user control. The file can reside in either root folder on in a sub-directory.

.ashx – The file type is used to create generic handler by implementing the IHttpHandler interface.

Continued...

CompilationMode enumeration for the page tag in asp.net 2.0
Hi,

One of the new attribute of the page tag in Asp.Net 2.0 is the CompilationMode attribute. The attribute is used to specify whether the Asp.Net compiler should compile the page or not at the runtime. The attribute has been added new in the asp.net 2.0.

The attribute can have 3 possible values. Always, Auto and Never. The default value is Always. As the name suggest the always and never value are used to tell the compiler to compile the page always or never respectively. Auto value means that Asp.Net will only compile the page if required.

Setting a page to never compile using the Never attribute will increase performance by disqualifying the specified page in the compilation process. Here is how we set the attribute for a particular page.
<%@ page compilationMode=”never”
Continued...

Option group control now with indentation for group member

Hi,

Here is an update to the option control that I posted a few days ago. The control allows you to show group in dropdown list and list box control, where by the user can only select the group member and not the group header. Read this post for more detail on the usage of the control.

The control had a bug where by the options would not indent properly. The problem was in the rendering of OptGroup tag. The tags needed to end only after all the option of group have been rendered. Special thanks to Tim who pointed and also provided the code for the fix of the issue.

This time around I have also given the full source code as download. Many people asked me to give the source code, as it is difficult to use such controls in live without having the source code.

Continued...

Use HttpWebRequest to get the status on weather a site is responding

Hi,

Yesterday I was working and found that one of my projects was not responding from time to time for some unknown error. The problem was intranet (some network problem with database server). We were loosing connection from time to time. But I wanted to keep a check if the site is running or not. So what I basically wanted was a check if the site was working fine by some other entity, which would tell me when there is problem with the web site.  

Hence I decided to make a small windows application that would check for a given URL at the given difference of time and would report back if the site is responding. I found it very useful so thought of sharing with all.

The main work that had to be done was to make a request to the site and check if the response status code is 202 (That is the status code when the site is running fine). Here is the code on how this was done.

Continued...

Order of Compilation for the asp.net 2.0 application

Hi

We all know the term compilation in Asp.Net. But do you know what is the order of compilation in an asp.net project. Do you know which folder in the application structure gets compiled first and which when get compiled last?

Here is the compilation life cycle of an Asp.Net project in the order they get compiled.

App_GlobalResources – First of all the global resources are compiled and the resource assembly is built. All the assembly’s in the bin folder are linked to this assembly.

App_WebResources – next the web resource folder will be compiled. This will create all the proxy types for the web services. The web reference created is then linked to the resource assembly (if it exists.).

Profile properties (defined in the Web.config file) – If we have defined the profile properties in the web.config file than an assembly will be generated for the profile objects.

Continued...

Application restarts 7 reasons that should be avoided

Hi

There are many reasons why the Web Application restarts in Asp.net 2.0. If you are using IN Proc (which is the fastest and most used) then all the users will loose the session information. So it’s very important to know what can cause an application restart in the web application. If we do not stop this application restart process it can cause great problem, as all the user will start loosing their session in the middle of nothing.

Here is a list of events when the Asp.net application restarts in Asp.Net 2.0

Continued...

Asp.Net Server control showing groups in Drop Down list
Hi
The control has some new argument over the dropdown list. There is a new property called DataGroupField. When we are binding the data then we need to asign the value of the group field. Also the data need to be sorted on the group itself otherwise the same group will be show twice (I have not added sorting of the data based on the group in the control as yet. But waiting to see if this will be required.).
You can also add the items one by one. In this case you need to provide the group of the item also. The add methods take and object of type OptionListItem. The optionListItem takes three argument, ItemName, Value and the group. (I know you will have the question why not the type ListItem. The reason is
                
Continued...

Optgroup tag to show the group name in the dropdown and List box control

Hi,

Many a times we have a requirement where we are showing data in a dropdown list. Many of the times the data belongs to a particular group. But there is no way to show the group in the dropdown list. Hence there is no way for the user to know which group (or category) the data belongs to.

Most of the time we use two dropdown list to show the data. When the user selects the category dropdown we populate the sub category of the product itself. (We can also use Ajax to populate the second dropdown, but that’s not in the scope of this post). But this solution is still not the best as the user still cannot look at one list of products (or sub category) and understand which category it belongs to.

Continued...

Keeping the scroll position of a div after post back

Hi

A few days back I came up with an interesting requirement. I was working on a page, which had a scrollable div. The problem was that after the post back the div would loose its scroll position. Now when there is a lot of data it is very inconvenient for the user to again scroll back to the position where he was before the post back.

One of my colleagues helped me out with the solution. The solution was quite simple. We saved the value of the scroll in a hidden variable. This was done on the onscroll event of the div. On the page load event of the page we again set the scroll of the div to the value saved in the hidden variable. That’s all. Here is a simple code to show the actual working.

Continued...

Blog, Ping and update status. How does it work?

Hi,

As we all know the world of the Blogs work on the ping services. Once we update our blog with new posts we need to update the other sources that our blog has been updated. We should ping to the sources whenever we create or update our post.

Pings can be done both manually and programmatically. Many site provide free ping services for with a ping interface like http://ping.in/, http://pingoat.com etc. You enter your URL and and the feed title and they will ping all the ping server listed.

We can also ping programmatically. Programmatic ping is done through XMP-RPC Procedure, through which we send xml over the http request. The XML contains information of your feed and the URL to which you send the request is called the endpoint

Here is an example that I found that uses the xmlRpc Library from the cook computing.

Continued...

Difference between Convert.ToInt32 and Int.Parse method

Hi

Today one of my colleagues came up with an interesting question in the office. If we want to convert a string value (Lets say we have a string “23”) to integer we have 2 options. One is to use the Int.Parse method and other is to use the Convert.ToInt32.

The real query with every one was what is the difference between the two. The answer is null handling. The difference between the 2 is the manner in which null is handled. If you pass a null value to convert.ToInt32 method it will return back 0. But the same is not true with Int.Parse. If we pass null to Int.Parse method it will throw an ArgumentNullException exception.

Although Convert.ToInt32 method does not throw an exception but it can have a big drawbacks. If you use it on a query string value(where u are also expecting the value 0) then the Convert.ToInt32 might cause programmatic error.

Thanks
Vikram


Asp.Net futures May - A look at the future of Asp.Net

Hi

A few days ago Microsoft Released the Asp.Net Futures. This is a list of futures that might be delivered in the future. I have still looked at only one of the Category and the list already looks promising and exiting to me. The functionality in the Futures release includes early experimental versions of features currently being considered for future versions of ASP.NET and the .NET Framework.

Continued...

Tons of stuff available for beta download - IIS 7, Dot Net framework 3.5, Orcas and Silverlight

Hi

It seems to be the season of the beta download and beta testing again. Dot net developers have got tons of things to play with. Four most important products in their different level of Beta. Wow! Here is the list and the links to download

First we have IIS 7 in Beta 3 for download. Yes it also support the go live license. This means that you can use it in the production environment also. And is its stable? Well Microsoft.com is already deployed on this.

Some of the new features of IIS 7 are

Continued...

How to give keyboard accessibility in web sites

Hi

In the modern day web sites where client side features have taken the front seat (AJAX), one of the very important and less talked about things is to give the user keyboard accessibility.

There are many users who do not want to go the mouse while working with a site. If we can give them some keyboard shortcuts then they would enjoy the site even more.

Adding these access keys are very simple and can be of great use to the users. For example to add the access key to a <a> tag would be as simple as adding the following attribute to the tag  accesskey="5". Now when the user clicks Alt + 5 in IE and Shift + Alt + 5 in Fire fox then the user will be taken to the link. If you press enter then then you will find yourself going to that page.

Continued...

Here is a list of all the short cuts in Visual Studio 2005

Hi,

I always felt a need for having all the short cuts in Visual studio at one place so that they can be referred whenever required. These short cuts are really helpful and make the application development really very fast. The fact that you do not have to use your mouse when you are writing some code.

For an example whenever we want to do search we go to the find window and type the word there and start the find process. But we can do it more easily by selecting word to find (If we have it written somewhere) and pressing ctrl & F. Also I would suggest the Incremental search in Visual studio 2005 which searches the document as and when we are writing. Use ctrl & I to get the incremental search

Continued...

Nullable types and Boxing in C# 2.0

Hi

If we try boxing on a nullable type, the boxing will only take place if the object is not null. Meaning that if the HasValue is true then only object will be boxed otherwise instead of boxing the object reference is simply assigned to null.

bool? B1 = null;

object obj = B1;

// obj is null;

If the object is non-null, then boxing takes place. Only the underlying type that the nullable object is based upon is boxed. The system.Nullable that wraps the value is not boxed. These objects can also be unboxed into the nullable types like this.

bool? B2 = (bool?)obj;

This behavior provides two advantages. Firstly the nullable objects can be tested for null and secondly that the boxed nullable types fully support the functionality of the underlying type.

Hope this helps
Thanks
Vikram


Concept of Type parameter with the help of Generics

Hi

Generics are the new feature in the c# 2.0. They introduce the concept of Type parameter. This makes it possible to classes and methods that differs the specification of one or more types until the class or method is declared and used by the code, which will be using it.

Generic helps us to maximize the reuse of code, Type safety and better performance. Generics are most commonly used to create a collection. There are many new generic collection classes in the System.collection.Generics namespace. These classes are advised to be used for type safety and better performance over araylist.

We can also create our own Generic interface, classes, methods, events and delegates. Information on the types used in a generic data type may be obtained at run-time by means of reflection

We can declare a generic class like this

public class GenericClass<T>
{

Continued...

Using static class to separate data and behavior independent of any object

Hi

A few days back I was having a conversation with my colleague on the use of static class. At that point I decided to write a post on the issue giving an example on when to use a static class and members.

We use static class when we have to separate data and behavior that will be independent of any object identity. The data and functions do not change regardless of what happens to the object.

A static class can only contain static members. We cannot create an instance of a static class. Static class is always sealed and they cannot contain instance constructor. Hence we can also say that creating a static class is nearly same as creating a class with only static members and a private constructor (private constructor prevents the class from being instantiated).

Continued...

Trace output capturing in a text file.

Hi

In asp.net 2.0 it’s very easy to capture the trace file and keep it in a text file, Xml file or database. ASP.NET 2.0 introduces flexibility to output the trace information. We can also pass the trace output to any data storage we want.

The TraceContext class now features a TraceFinished event that provides programmatic access to trace output. In the page load event we create a handler for the TraceFinished event.

Trace.TraceFinished += new TraceContextEventHandler(OnTraceFinished);

Now we can use this tracefinished event to log the trace data.

 
void OnTraceFinished (object sender, TraceContextEventArgs e)

{

    foreach (TraceContextRecord record in e.TraceRecords)

    {

Continued...

Finding the statistics and other data for the site

Hi

In last six month I have tried to optimize my site for the Search engines. When doing so I am constantly looking at some of the sites/tools to know the position of my site in regards. These are publicly available free tools and shows statistics for websites. Here is a list of things that people might be interested, in context of there site.

Technical data of a site

IP Address - by DomainTools Search

Other Sites on an IP Address - by IP Query at Live.com

Name Server - by DomainTools Search

W3C Validation for the site page - by W3C Markup Validator

CSS Validation - by W3C CSS Validator

Continued...

Showing hierarchical data from the database using the tree view control in asp.net 2.0

Hi

One of the cool new controls of the asp.net 2.0 is the tree view control. But there is no direct support in the treeview control to populate hierarchical data on the fly from the datasource. In this post I will talk about populating hierarchical data from the database to be shown in the treeview.

For the Example purpose lets say we have a table with hierarchical data. The table has three fields Cat_id, Name and ParentID. The parentId references the Cat_id to make the data hierarchical. On how to retirieve hierarchical data check my previous post.

First define a treeview control in the page like below

<asp:TreeView 

  ID="TreeView1"

  ExpandDepth="0"

  PopulateNodesFromClient="true"

  ShowLines="true"

  ShowExpandCollapse="true"

Continued...

How can I get a schema the record set that is returned from a stored procedure?

Hi

A few days back one of my collegue was asking me on how does the dataset gets the schema of the Table even when we are using the Stored procedure. He wanted to get the schema himself and work around that.

The data reader includes a getSchemaTable method which gets the schema in a data table on the result set. each row in the returned data table corresponds to a Column in the actual resutset. This schema can be utilized to infer the Column Name, its data type etc. To get additional schema information like base table name, column name etc. with commandBehaviour.keyinfo.

There are a few problems with this. If the stored procedure returns different result set depending on the input parameter, this might not work. Also if the stored procedure is using a Temporary table you might not get the addition schema with the CommandBehavior.KeyInfo.

Continued...

How to fetch both Master and detail data from the database

Hi

A few days back I was having a discussion with my colleges on how to fetch data when you want to show category data and also their sub-categories. What I mean is that you have a master table Category (Cat_ID, Cat_Name) and a subcategory table (Subcat_ID, subCat_Name, Cat_ID). Now you want to show category in a gridview and in show the subcategories in the nested grid views inside it.

For this example purpose lets say we have 5 rows in category table and 20 rows in the subcategory table

Continued...

Using is and as keyword in C# instead of reflection

Hi

Now a days people are so much relayed on the casting reference types and reflection that they forget the use of the other keyword in the system to work out the same. I support the use of the inbuilt keywords like as and is because they are faster and many a times they also make us rely on hard coding the type of the object.

Reflection is a very powerful tool but it also has some performance degradation as against the inbuilt keywords. Also if we use the inbuilt keywords we don’t have to hard code the type in the code. With reflection to check the type of an object we would write the following code.

if(Variable.GetType() == Type.GetType("System.String"))

Continued...

Working with nullable types in C#

Hi

One of the new features in the C# language is the support for nullable data types. If in your application you are dealing a lot with database having null fields and this will be very helpful although the nullable data types are useful in other situation also.

A data type that can contain defined data type or null value is nullable data type. Defing the nullable type is very simple. All we need to use is the ? modifier.

Normal declaration without nullable type

Double d1=12;

Declaration with nullable type.

Double? D2= 12;

Or

Continued...

Using generic methods into non generic types

Hi

Dot net 2.0 has introduced generics, which is very useful in many situations. We can introduce some generic methods into the non generic types. This brings power of generics to class with requiring the class itself to me parameterized.

To expand on that I will take an example of a simple function Minimum() which accepts to integer Values and returns the minimum of the two.

public int Minimum(int val1, int val2)
{
     return (val2 < val1) ? val1 : val2;
}

Continued...

How to take the asp.net 2.0 application offline when required
Hi

Some time when we want to make major changes to our application or we want to gain the access to the resources that cannot be accessed when the web application is running, we want to take the Application offline.

When we are making some major changes to the web application we do not want the user to use the web application. If the user uses the web application when we are changing the database structure and its related code then it might result in problem.

Some times we might want to take the application offline because we want to access the actively used Access or SQL Server Express database. When an application is actively accessing the database the associated files are locked so that no other process can change them.

Continued...

Why not to use cross page post back when validation the page.
Hi

In ASP.Net 2.0 we can use the cross page post back to post to a different page. We can also get the same effect by using the Server.Transfer method. You can look at this post of mine to see how to work around with cross page post back.

But we cannot use cross page post back at every situation. There are some disadvantages of using cross page post back at some situation especially validation.

If we have disabled the client side validation for our controls then the page will post back without any validation. Even if the validation is not turned off, we can’t always use validation on the client (some custom validation controls will only be able to validate servers-side), nor can we always trust the client to perform validation.

Server side validation presents a problem for cross page post backs because our response will come from the destination web form instead of the original web form where the user failed validation. When we inspect the
Continued...

How to take the asp.net 2.0 application offline when required

Hi

Some time when we want to make major changes to our application or we want to gain the access to the resources that cannot be accessed when the web application is running, we want to take the Application offline.

When we are making some major changes to the web application we do not want the user to use the web application. If the user uses the web application when we are changing the database structure and its related code then it might result in problem.

Continued...

How to Register User Controls and Custom Controls in Web.config to manage them easily

Hi

In asp.Net 1.X we had to import and use both customs server controls and user control on a page by adding the @Register directives to the top of the page. Once registered developers could then declare these controls anywhere on the page using the tag prefix and tag names configured in the @Register directive.

This is fine but if we have too many user controls across the sites (and that too ascx files) then it can be painful to manage across the site.

Continued...

A small bit about Impersonation in Asp.Net

Hi

The ability of a thread to execute in a security context different from that of as process owning the thread is called Impersonation.

For web Application this means that if the server is impersonating, it is doing work using the identity of the client that is making the request.

The default setting of the Asp.Net is different from the Asp. By default, Asp.Net does not do pre-request impersonation. The Application can be configured to impersonate on every request with the use of following configuration directive.

<identity impersonate="true" />

Since ASP.NET 2.0 does dynamic compilation, enabling impersonation requires that all accounts have read/write access to the application's Codegen directory (where dynamically compiled objects are stored by the ASP.NET runtime) as well as the global assembly cache (%Windir%\assembly).

Continued...

Working with Cross page post back in asp.net 2.0
Hi 

In Asp.Net, By default the button control posts back to the same page that contain the button. In most of the cases this behavior is ok. But sometime we want to be able to post to another page in the application. In Asp.Net 1.X we used the Server.Transfer method to move between the pages without changing the URL. 

But in Asp.Net 2.0 we can post to a different page, firing a normal post back to a different page inside the application. We can also access the values of the server control of the source page that initiated the post back.

Continued...

How to represent a quote within a string in C#

Hi

A very common problem people come-up with while working with string data type is how to work with special character. A number of characters have been labeled as special characters. How would you represent a quote within a string, since the compiler interprets a quote as the beginning or end of the string? Whenever you want to use one of these special characters you need to use a technique known as escaping the character.

Here is a list of the string that needs to be used for the purpose of this special character.

\n = New Line
\r = Carriage return
\r\n = Carriage return and New line
\” = Quotation mark
\\ = Backlash character
\t = Tab

Continued...

How to control Authorization Permissions in an ASP.NET Application

Hi

When we use the forms based Authentication in Asp.Net 2.0 Application. Only the authenticated users can access pages in the application. Unauthenticated users are redirected to the specified login page provided by the loginURL tag. If the user login from that page then the user is redirected to page they wanted to go.

This is perfect when all the pages in the web site are login protected. But that’s not true with all the application. In most of the application some pages are login protected but many pages are not login protected. This means that the user should be given access to a given number of pages even if the user is not authenticated and in login protected pages the user should not allowed the access.

Continued...

Working with MultiView control in Asp.Net 2.0 to show the same page with different views

Hi

Data collection is a common task in web application. We might have to collect data for survey and display result or use the contact us form and after the form is submitted show the user a response that the information has been submitted.

Most the time people transfer these into multiple pages so that the user does not have to see a real long page, and feel that he has to input too much of data.

Many a times in Asp.Net 1.X developer used to complete this task in one form by using multiple panels. They would hide and unhide panels (having a set of controls). This was easier then to create multiple pages for the job.

In Asp.Net we have the MultiView control to work around this problem. This is a new control in Asp.Net 2.0. MultiView makes life easier for developer when they have to show one view at a time out of many views in the same page.

Continued...

How to easily encode and decode a string in Base64 format

Hi

Yesterday I had a task where I had to encode some string in the Base64 format and then later decode the same back to string. When I first started looking at the System.Convert class, I found the convert to base64 function does not take any string parameter.

You can still convert a string into base64 format in one line of code. The code to convert a string to base64 format is

string str64;
string str64back;
string str="Vikram"; 

Continued...

How to send asynchronous emails in Asp.Net 2.0
Hi

Another of the new feature in asp.net 2.0 is the support to send emails asynchronously. This is a very important feature. With the help of this feature you don’t need to wait for the email to be sent before performing other tasks in the page. But instead these tasks can be performed while the mail is being sent asynchronously.

To send Emails asynchronously we need to wire up a sendComplete event, create a send complete event and then call the sendAsync event.

Continued...

How to send an embedded image in the Email in Asp.Net 2.0
Hi
Another of the new feature of the Asp.Net 2.0 in the Emailing section is embedded images. With System.Net.Mail we can now embed images in the Emails sent from Asp.Net 2.0 web site.
To send an embedded image in the mail we first need to create an object of LinkedResource. This linkResource will actually contain the binary data of the Image. This binary data is then encoded as a part of the image and sent along as a part of the mail message.
We also need to give the LinkedResource a unique name and a content ID. We then create an HTML Alternate view. Inside that Html text we can use the standard img tag. The src attribute value will be the content
                
Continued...

What are the things that can be controlled in the HttpRuntime element in System.web element in the Web.Config file?

Hi

In Asp.Net 2.0 we can set many property related to the working of the application. We can set the Execution time out, upload file size etc for the application. We need to set these properties in the httpRuntime section, which is under <system.web>, which will be under <configuration> section.

<configuration>
<system.web>
<httpRuntime>
</httpRuntime>

</system.web>

Continued...

Sending Email with attachment and creating attachments from memory stream in Asp.Net 2.0
Hi
Many a times we have to send Emails with attachment. In Asp.Net 2.0. We can add as many attachments to the mail as we want. To add a attachment to the site use the following code. 
MailMessage.Attachments.Add(new Attachment("c:\\test\\Vikram.txt"));
To add more attachments simply go on adding attachments to the mail class by using the Add method
Remember to send the attachment Asp.Net process of the impersonated account will need to have the permission to read and attach the file to the MailMessage
                
Continued...

How to create default value for property in Dot Net

Hi

Many a times when we create a property we want to assign it a default value. We
will have to use the namespace System.ComponentModel for this.  We assign the default value with the help of the attribute DefaultValue.

Here is how you do that in C#


using System.ComponentModel;

public class c1

    {

Continued...

How to send mail in Asp.Net 2.0 so that we get a mail notification when the user reads the mail for the first time.

Hi

Many a time we want to add read receipt header to the Email we sent. A read receipt is a notification method where by an Email is sent to the given Email address when the mail is first read. To add a read receipt Notification to the Email in Asp.net we need top add the header Disposition-Notification-To in the Email. This can be done very easily by one line of code.

Continued...

How to set the priority of an Email in Asp.Net using the System.Net.Mail namespace

Hi

Many a times when we send Emails from the site we want to make it a high priority Email. In Asp.Net 2.0 the Email functionality is governed by the System.Net.Mail namespace.

The headers in the above-mentioned class control the priority of a mail. But the name space also exposes a property to set the priority of the mail. We can use the Priority property of the MailMessage class to set the priority. The priority can have one of the three values High, Low, Normal (from the MailPriority Enumeration)

Here is an Example that shows the how to change the priority of the mail to high.

Continued...

Working with function of Path class in System.IO Namespace

Hi

The path class of the System.IO namespace is very useful to work with file paths. This class contains many static properties to work with file path. Some of the functions of the class are listed below

Path.Combine(string, string)

This function combines 2 paths together and returns a singe path. This function is very useful if we have directory path and the file path differently. In that case we can use the function to combine them to a single path. A simple concatenation can give us a problem with whether to put the “/” string or not. But with this function we do not need to test these conditions.

Path.GetExtension(string)

Continued...

Why does most of the Email fired from an ASP.NET Site go to the Spam folder?

Hi

Does the Email Sent from you site built in ASP.NET go in the Spam filters of most of the client? Its been happening with me a lot. Most of the Client complains about not getting the Email to finally realize that the mail has gone to their Spam folder.

Of late I have been working with the new System.Net.Mail class for sending emails from the Site. I found that all the mail sent from the Site had their headers added in lower case. This problem was not there in Asp.Net 1.1 when I used the System.Web.Mail class

Continued...

Events fired during the Life Cycle of the of a page in Asp.Net 2.0

Hi

A few days back I talked about the event in the Asp.Net application Life cycle. It talked about the entire event that takes place when a request is made. You can read the article here. In this Article I am going to talk about the event that takes place in the Page.

PreInit()

In this event all the page level controls are created. The property assigned in the HTML is also assigned to the controls in this event. This event is only there for page and not present in user control (Hence not present in Master Page also). If we want to change the Theme and master page of a page, we need to override this event.

[Note: When you override this event remember to call the base pages preInit command.]

 

Continued...

Added an Image Search to site using the Flickr API

Hi

Today I have added another new functionality to the Site. Now the site also has an Image search feature. The Link in the top to find image takes you to the images search page. I am using the Flickr API to search Image. After searching the Image I load them.

When you hover over an image you will see the enlarged version of the Image. This was done with the use of Ajax Extension. I am using the Popup extender to display the enlarged image when the user hovers over the image.

I am not a user of Flickr.com of you will not find any image of mine when you search with my name but hope you find some interesting ones in the image search page.

Hope this helps
Thanks
Vikram


Performing separate validation scenarios on the same page in Asp.Net

Hi

Earlier in asp.net 1.1 when we wanted top validate only a few fields on the click of a button and a few fields in the click of another button on the same page, there was no way to this using the validation control of Asp.Net.

In Asp.Net 2.0 this problem is solved. Now when we want to perform separate validation scenarios on the same page we can use the validationGroup property. With the help of this property we can group the validation control and then tell the post back control to validate a particular group only.

This is very useful for the editing scenarios of the data controls. We need to set the ValidationGroup property to the same value for all the validators that belong to a particular group. On the button control or the postback control (with causes validation property set to true) set the validationGroup property to the name of the group that the control needs to validate when there is a postback.

Continued...

Use ValidateEmptyText property of the custom validators to validate even if the control to validate is empty

Hi

In Asp.Net 1.X there was a problem in using the custom validators. The custom validators never fired if the control to validate was empty. So it was not very useful in all the places. In Asp.Net 2.0 this problem has been solved.

The custom validators have a new property called ValidateEmptyText. If we set the value of this property to true then the custom validators will validate even if the control to validate was empty.

Hope this helps
Thanks
Vikram


Attributes for configuring Forms authentication in Asp.Net

Hi

Many a time we use the forms authentication in our application. When using the forms authentication we need to configure it in the web.config file. There are many attributes to the configuration, which are many a time not utilized properly. Here is a look at the attributes of the Forms Authentication.

[Note: remember Forms element is the sub element of the authentication element inside System.web element in the web.config]

Continued...

How and where to use the Image Map control in Asp.Net

Hi

When we want to work with hot spot regions in an image, we can use the ImageMap control. We can define the Hotspots regions for the image and when the user clicks the Hot spot region, the control can either generate a post back to the server or go to a specified URL.

If we use the control to display a map of geographical region and the use clicks a specific region on the map, the control can navigate to the URL that will provide the additional data about the region clicked. This control is also very useful if we want to capture the response of the user for the votes (the region user clicks for the vote).

We use the top, left, bottom and right property to define the location of the hot spot. We need to provide the hotspot mode property to define what will this hotspot do (navigate or postback). We use these properties inside the hot spot template (like asp:RectangleHotSpot

Continued...

Using the SqlCommand.close method before using datatreader.close method

Hi

The other day I was reading about the data reader class in Dot Net. It is highly said that data reader is faster than the dataset. So we should use the data reader when working with the read-only data. Although this statement is true but there are a few other things that should be taken into notice when working with data reader.

There is one problem with the data reader. Even if you call the close method of the data reader class the data reader will retrieve data from the stream and then close. This can have some performance issue. If there is a big amount of data in the stream, it can take long time and might cause a timeout error. To solve this always use the Cancel method of the SQL Command you are using. The better thing would be to restrict the result set to be smaller if it is not supposed to be used.

Hope this helps
Thanks
Vikram


New Default button and the focus API in ASP.Net 2.0

Hi

One of the cool new features of ASP.NET 2.0 is the Focus API. With the help of the Focus API we can declaratively or programmatically set the focus on a specific control.

The page.SetFocus method is used to set the focus to a particular control. The method takes the ID of a control as a parameter. The ID passed is set the focus on. We can also use the DefaultFocus property of the Form element to define which element will have the focus. Also we can use the focus method of the individual control directly to set the focus.

Similar to the default focus you can also use the Defaultbutton property of the form to define the Default button for the form. The form will submit that button on the click of the enter key inside any input control inside of the Form.

Continued...

How to save and retrieve images from a folder in the server

Hi

Recently 2-3 people asked about how to upload and retrieve images from a folder in the web. Hence I decided to make a post on this.

The idea is to allow the user to upload the images in a folder and then show that image at a particular position. This is particularly required in an ECommerce Site. Where someone will upload the images of the Category, Product etc. The images are then stored in a folder in the web and displayed at the correct position.

First we store the Virtual path to that folder in the Web.config file. This will be helpful if we need to change the virtual path any time. We can just change it in the web.config file and there is no change in the code for that.

Just add the following line in the appsetting section

Continued...

How to read the trace values in Asp.Net

Hi

When we use trace in our web application to keep the trace of the application we also need to view the trace values. If you are using the trace.axd, you will find a View Detail Link to see the details of each request.

The trace detail has many sections to it.

Request Detail

Session Id - The Session Id for this request

Time of Request - The time the request was made

Status Code - The returned status code for this request

Request Type - GET | POST

Request Encoding - Encoding for the request

Response Encoding - Encoding for the response

Continued...

Logging trace values in the Asp.Net Application

Hi

It’s very important to be able to trace your application very easily. We can enable the trace for the entire Application. Enabling Trace at the application level has the effect of enabling Page-level Trace for every page within that application

[Note: This will work provided there is no page-level directive to explicitly disable trace]

ASP.NET runtime also collects several additional statistics, such as the state of the control hierarchy, the contents of session and application state, the query string input values, and other characteristics of a request's execution, when the Application level tracing is Enabled. We can collect the specifics for a specified number of request and also keeps them for either first (Specified number of request or the last specified number of request).

Continued...

Converting a string to proper case in Dot Net

Hi

To convert a string to proper case we will have to use the System.Globalization namespace.

To do this we will use the following code.

string myString = "VikRAM’s WebSite HaVinG a post oN pRoper cAsE";

TextInfo TI = new CultureInfo("en-US",false).TextInfo;

Response.Write (TI.ToTitleCase( myString ));

[Note: Generally, title casing converts the first character of a word to uppercase and converts the rest of the letters to lowercase.]

Hope this helps
Thanks
Vikram


Microsoft Visual Studio Code Name “Orcas” CTP

Hi

You can get the CTP development tool for Dot Net 3.0 here

Microsoft Visual Studio Code Name “Orcas” Community Technology Preview

Hope this helps
Thanks
Vikram


How and when to use the new Hidden control in asp.net 2.0

Hi

Another new addition to the ASP.NET controls in Asp.Net 2.0 is the hidden Field Control. This control enables a developer to store a non-displayed value.

When we need to persist some value during the posts to server, we can use the hidden fields. It renders a <input type= "hidden"/> element in the HTML. We normally use the view state to store these values. But for some reason, if the view state is not available, then we can use HiddenField Control to store these values. Although this is not visible to the user in the browser, but the HiddenField is rendered in the client browser. Hence it is not suitable storing values, which are security sensitive.

Continued...

Using Bulleted list to display a list of name's or HyperLink

Hi

Another new inclusion in the list of controls in asp.net is the Bulleted List control.

Lets say if we want to show the list of values (For me a good use was to view all the values from the word file for Autosuggest Box), this control will be of great use. You can also format the bullets. To specify individual items that we want to appear in the list we can use the List Item tag also.

BulletedList controls can display list of items with a variety of bullet styles. Use the

BulletedList.BulletSyle property to control the style of the bulleted list.

Here is an example of Bulleted List control

Continued...

How can we show the full code file to the user

Hi

Yesterday I was thinking what do I have to do if I wanted to show some of my code file directly to the user. The answer was rather very simple.

Use a simple function, which will show the text of the file. You will need the pass the path of the file to the function. This path should be the absolute path and hence you should use the Server.MapPath while calling this function.

Here is the code to the work

Protected string GetCode(string filename)

Continued...

What is the way to rename a file on the web server in code

Hi

A few days back I got a question regarding what is the best way to rename a file in the server (say an uploaded File) using Asp.Net 2.0. According to me the best way to rename a file is by using the System.IO namespace and moving the file to the same location with a different Name.

In C#

Using System.IO
File.Move(@"C:\Dir1\SomeFile.txt", @"C:\Dir1\RenamedFileName.txt")

In VB

Imports System.IO
File.Move("C:\Dir1\SomeFile.txt", "C:\Dir1\RenamedFileName.txt")

[Note: You might get permission error if you do not have the permission to make changes in the folder ]

Hope this helps
Thanks
Vikram


How to work with file system in asp.net 2.0

Hi

When I made the search Box into and Auto Suggest box I also had to read and write a text file from the code. Hence I decided to blog about it. To deal with the file system we have to use the System.IO Namespace.

To read a file we require an object of the StreamReader Class. Then we use the OpenText method of the File class (System.IO) to open the file. We have to pass the path of the file as the parameter. We read the file in an object of StringBuilder Class. The code looks like this

Continued...

Post-Cache Substitution for optimizing the cached pages

Hi

The partial page caching approach works very well for scenarios where most of the page content is dynamic and/or it is easy to encapsulate cached content into isolated user controls. The concept does not work well for the reverse scenario, when most of page content should be cached and only a very small portion is dynamically built. For example, consider a page displaying static data but only the username displayed is dynamic. In this case it might not be possible to cache the entire page because of the username, which is dynamic.

Continued...

Adding the words for auto suggest box in the cache objects.

Hi

Now I have updated the process of getting the data from the word file (used in Auto-Suggest Box) read the blog here.

I have cached the string of words in the cache objects for 60 seconds and also put a dependency on the text file.

Here is the how the code looks like

System.Web.HttpContext.Current.Cache.Insert

("Words", sb.ToString(),
New System.Web.Caching.CacheDependency(

Continued...

Caching a part of the page when most of the page is rendered dynamically

Hi

Most of the time it is not practical to cache the entire page, as and important section of the page is dynamically generated from the database. But in those pages there is much content. As in my site the name of the category and the number of post per month are fairly static (Until I add a post or category). Since Output Caching caches the HTML or the entire ASP.Net web page, it cannot be used for these scenarios. If I try and cache all the posts (VaryByParam) then it will be a huge amount of cache in the memory and might slow down the site further.

For these scenarios we can use Partial-Page Output Caching.

Continued...

New features of the New web Project System

Hi

With visual Studio 2005 and Asp.Net 2.0 Microsoft brought out a new project Model (Web Project Modal). Here I am going to discus some of the features of the Web Project Modal.

One of the more important features of the web project is that there is no more requirement of the front-page server. With the new project modal we can open the local IIS Application and the virtual directory without FPSE. We can also open and edit the projects from the file system or even remotely over FTP. The FPSE is still supported but it is not required.

The new Visual Studio also comes with a built in WEB SERVER (CASINI). So this means that we can do the development even if there is no IIS installed in the machine. The studio also supports debugging application running within it while using the normal user account and not necessarily Administrator.

Continued...

Forms Authentication timeout and session time out are different and independent of each other
Hi

Here is something I came across that was very interesting. In asp.net we can set the time out for both Form Authentication and Session. These two times can be different.

Hence you can have Forms Authentication time-out is greater than the Session time-out.

[Note: there is a difference in Version 2.0 from V1.X that the value for cookie Expiree (Time-out) is set for both the persistent and non-persistent setting (previously it was only used for the non-persistent case). Previously, the persistent duration was just hard-coded to a really long time]

Although it’s a little bit hard for me to understand how you can time-out and persistent cookie and still say it’s persistent.

Continued...

A comprehensive look at the Master Page

Hi

One of the great additions of ASP.NET 2.0 is Master Page. Master page helps us build a consistent and maintainable UI through out the site.

So how does a Master Page works?

The master Page and the content page merge there content together to create a single aspx page when a request for page arrives, which is using master page. Lets create a simple master page.

Continued...

How to use Generics in DOT NET 2.0
Hi

In Dot Net 1.X developers had to use System.Collections non-Generic collections for their Objects and hence had no type checking. So the developer would have to do type casting while retrieving the objects. One of the main new features of DOT NET (Generics) has made life easier for the developers. Another important reason for using Generics against Non Generics in performance. Reading objects from and Array List will have better performance since we will not have to type cast the Object. Generics also gives us compile time Type safety.

So how does Generics change our code?

In Dot Net 1.x Array list was one of the most common to store objects since it can save any collection regardless of their type. We used to type cast the objects when we used to retrieve them.

List<T> can be used as a good alternative to Array List. The main difference is that List<T> is type specific.

Continued...

Do not forget to set The Application Name property when working with the providers of the ASP.Net
Hi

Whenever you use the Membership and role API of the ASP.NET 2.0 remember to configure the Application Name. If you do not give an Application name and restart your application all the data related to your previous Application will be useless.

When the application Name attribute is not configured, ASP.NET uses the application virtual root path within the web-server to automatically create application Name. This Application name is used when adding data to an ASP.NET Application Service database. Now when you restart the Application a new Application name is created and makes all the data related to the previous Application name waste for you.

Continued...

Site Map added to the site using a DataList inside another DataList

Hi

Now I have also added a Sitemap to the Site. The sitemap has the entire link in the Site.

It also shows the list of Posts by category and by month. To show all the name of the categories and the posts in that category I used a Data List inside a Data list. This creates a tree view like structure that shows the entire category and inside all the category links to all the posts for that category.

Thanks
Vikram


How to use Master page with more than one content template and update only those content Template which are needed to be changed

Hi

Of late some people have asked me about a particular feature of the master page, which is very helpful in the real life scenario. The property to make the header and footer of the page also dynamic using the Master page. This is very important in the real life scenario.  There are many a time when we do not want to show the header or the footer in one or two of the page. Or in place of the current Header we want to show some different header.  No one wants to have the headache of having another master page for these pages.

So how to achieve this. We can have more than one content template in the master page. Lets say we have three content templates in the master page.

Continued...

Rewriting the URL of the Site using HTTP Modules

Hi

So after spending some time with the site one thing I realized that the next thing that needs to be done to the site was URL Rewriting. Now you can see the site working with URL Rewriting. I did not like having meaningless URL's for visitors (i.e. post.aspx?postid=3), and hence went for URL Rewriting.  I had worked on URL Rewriting on asp.net 1.1 so I decided to work on that library only. I use HTTP Modules for URL Rewriting (I know we have other option like IIS, HTTP Handler etc). The main reason for the decision was that I already had the library with me and it took only a couple of hours to complete the work (including creation of rules).

Continued...

How to use a control to send its HTML as and Email

Hi,

Many a time we want to send Email, which resembles the output of a web control. When trying to send an Order confirmation Email where you are sending the description of all the products bought by the user. [The number of product can be anything]. At these occasions it would be great to be able to send the output of a web control.

For this article I am assuming that the SMPT server is configured. (To send Emails using your Gmail Account check this post) We can capture the output of most of the control using their Render Control method. After that you can send the output of the control through a mail.
Here is the code for

Continued...

How to put focus on a control through server side code in ASP.NET

Hi

Many a time you need to set the focus of the form to a particular control. There is no way to do this with server-Side scripting. This needs to be done through Client-Side Scripting. The following JavaScript snippet can be added to the bottom of the HTML view of your page:

<script language="javascript">
      document.getElementById("TextBox1").focus();
</script>

Continued...

ASP.NET Application object events and how can they be used

Hi

ASP.NET Application Object has large number of event where each event can be used for a specific functional purpose. ASP.NET pipeline is a step-by-step process through which various parts of the request are processed in a structured manner. These events can be categorized in two types.

  • Request Related Events.
  • Response related events

[Note: There are many Request related events that only occur under certain condition. (Like application start event, session start event). These have been discussed later].

The event, which occurs when a new request is received, is listed in their order of occurrence respectively.

Continued...

So another Langauge gets released
Hi
Great news today is the fact that a Iron Python Version 1.0 is shipping today.
You can get the download here
http://www.codeplex.com/Release/ProjectReleases.aspx?ProjectName=IronPython&ReleaseId=423

Also shipped is a ton of code with it so that people can see just how it is done as well as run their favorite Python code at CLR speeds.

Enjoy
Thanks
Vikram

AppendDataBound Items lets you add static data to dynamically populated list
Hi

There are quite a few features in ASP.NET 2.0. One of new healthy features in list controls (CheckBoxList, ListBox, DropdownList etc...) is the new property "AppendDataBoundItems" You can bind the list controls to some data source and also add some static data. If the "AppendDataBoundItems" property is set to true then you will get all the date (static data and data populated by data source) in the list. This is very handy if you want to add a "Select One" item in the Dropdownlist and listbox.

Continued...

AppendDataBound Items lets you add static data to dynamically populated list

Hi

There are quite a few features in ASP.NET 2.0. One of new healthy features in list controls (CheckBoxList, ListBox, DropdownList etc...) is the new property "AppendDataBoundItems" You can bind the list controls to some data source and also add some static data. If the "AppendDataBoundItems" property is set to true then you will get all the date (static data and data populated by data source) in the list. This is very handy if you want to add a "Select One" item in the Dropdownlist and listbox.

Continued...

Difference between the ReadOnly and Enabled property of TextBox.

Hi

One of the things that confused me most in the textbox was the two properties Enabled and ReadOnly. The other standard input Web controls - the Checkbox, Radio Button, Dropdown List, RadioButton List, Checkbox List, ListBox, etc. - lack the ReadOnly property and offer only Enabled.

Continued...

How to make Membership, Profile and other built in API to use SQL Server 2000 instead of SQL Express.
Hi

ASP.NET 2.0 comes with some great API’s like Membership, Roles API, Profile API, health monitoring API. Etc. These API use the default providers to store data. Like the Membership API uses the SQL Express database by default to store the data. But many a time you want to use other database. I wanted to store the Membership and profile data in the SQL Server 2000 database.

With ASP.NET 2.0 Provider model this can be done in a few steps.

First we create a new database and obtain its connection string.

Continued...

How to get the statistics about the Database usage using sqlConnection object

Hi

One of the most important things needed to track and improve Application performance is Statistics. Statistics related to database work is of great importance to the developers. Since they need to track how many times the application is calling the database and how much time each query is taking and which query can be improved to increase the performance of the Application. We can use the sqlConnection object to retrieve the statistics related to database work.

Continued...

In built API for Health Monitoring for ASP.NET 2.0 web application

Hi

One of the new cool features of ASP.Net 2.0 is the Health Monitoring system. This is a very basic requirement for any Application. This provider has a comprehensive set of configuration attributes that you can use to customize the way it works.

ASP.NET version 2.0 health monitoring supports many standard events that you can use to monitor the health of your application. Examples of security related events that are automatically generated include logon failures and successes when using the ASP.NET membership system, attempts to tamper with or reuse forms authentication tickets, and infrastructure events such as disk access failures. You can also tap the event related to application start and Application end.

Continued...

How to get the IP address of the machine of the user

When we are logging the website we also want to log the user IP address.

The below given code gives you the IP address of the User Accessing the site.

HttpContext.Current.Request.UserHostAddress;
or
HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

To get the IP address of the machine and not the proxy use the following code

HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

Continued...

Theme changing on the fly using ASP.Net 2.0

Hi

Now the users can change the look and feel of the site as per their choice in my site. You can change the radio button on the left and accordingly the full theme (images, skin, and css) will change. This can be done very easily in asp.net 2.0.

After my friend (Thanks to Farghana) created a new theme for the site it required less than 10 line of code to change the theme on the fly.

Continued...

Sending mail form you Gmail Acount through your Application
Hi
A few days back I wanted to send my mails using the Gmail Account. The problem was that I wanted to automate the system and send mail from my Gmail Account through my Application. For this purpose I wrote a class that would send mail from Gmail Account. Here is the class that I wrote for sending the mail from Gmail.

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Mail;

Continued...

Uploading large files in ASP.NET 2.0 gives a DNS Error

File upload has some big problem in asp.net 2.0 If you try to upload some file of more than 4 mb you will get and error. This is the default file size limit of dot net. This is defined in Machine.config. You can overwrite this in web.config. Like this

<System.Web>
<httpRuntime maxRequestLength="10000" />
</System.Web>

Continued...

Deleting Directory In asp.net 2.0 will make you loose all your session data

Have you tried to delete a directory programmatically in ASP.Net 2.0? Don’t try it; it can cause great problems to your site especially if you are using in-proc session. You will lose the entire session variable after deleting the directory and there is no way of getting those session variable back. This system is a change from asp.net 1.X.

I came to know about this the hard way. I was working on a project were project submission was a process of 6 pages (All in one page using the MultiView control). In the last stem I was supposed to delete the entire directory which was created during the process. Strangely I was loosing all the session values when the directories were deleted.

Continued...

How To make Visual studio work faster
Hi

In case you have observed any slowness in your source view around typing or arrowing through code, here are a few tips that may help.
  1. Turn off background HTML validation. Go to Tools / Options and select Text Editor / HTML / Validation in the tree view on the left side. Uncheck the Show Errors check box.
  2. Turn off AutoRecover. Go to Tools / Options and select Environment / AutoRecover in the tree view.  Uncheck the Save AutoRecover check box.
  3. Close your property grid (View / Properties Window)
Thanks
Vikram

Spell checker add-on in the Visual Studio
Hi

I found this great blog ablout a new add-on in ASP.NET.
Mikhail Arkhipov has developed a spell checker add-in to Visual Studio 2005 that allows you to spell check the contents of your ASP.NET or HTML page in HTML view.
For this to work all you need to have Office 2003 installed on your machine

See http://blogs.msdn.com/mikhailarkhipov/archive/2006/04/17/577471.aspx for details including install location.Try it out today and let me know what you think.

Thanks
Vikram

Increasing the functionality of the validators to give it more flexibility
Hi

Recently I had to customize the appearance of the attached control of a validator during an error situation on the server or the client side, or even call a custom client function without postback. I first lookod around to find if we get some custom control for this. I came across various controls. And then I found this Article which was excatly what I was looking for.

Thanks to Alexander Kleshchevnikov.

The Article talks about enhancing the .net Validation Control.

This is a very good piece of work by Alexander.

Thanks
Vikram

Problem using the Atlas Drag extender in IE
Hi

I am using Atlas control toolkit and found this big problem with Drag panel.

I was trying to use the Drag Panel in one of my page which also contains some drop down lists. When I Drag the drag panel on the dropdownlist (I am using IE) I see the dropdownlist above the drag panel.

This behaviour is only taking place in IE and not in firefox. I do not know the real reason of this problem but this is making life difficult for me.

Does any one know how to solve this problem?

Thanks
Vikram
 
Copyright © 2006 - 2010 Vikram Lakhotia