Posts Tagged ‘ASP .Net’

How to show error page in ASP.Net

Handle custom errors in ASP.Net

Once the ASP.Net application is ready to launh to customers, there is no need to show the error details in to the web page when any errors occurred. In this scenario we can show our customised page with details like “Server is busy now please after some time” to the customer. At the same time we can store error details to database or txt file for future reference for developers. For customise errors in the ASP.Net we need to do some settings in the web.config file.

 Settings on web.config to show error page 

<customErrors mode="On" defaultRedirect="error.aspx">
<error statusCode="404" redirect="404Error.aspx"/>

The above code should be placed in the web.config file for handling custom errors (mode=”On”). Also we can handling particular erros with error code with appropriate error page. In above mentioned code, if a user request a page that is not in the server, 404 error is occurred then page is automatically direct to 404Error.aspx. If any other errors occurred, it will show web page error.aspx. In the same way we can handle any type of error with the status code, with the appropriate web page.

How to use cache in ASP.Net ?

Why need to cache data in ASP.Net? 

Most of the developers don’t know where can use cache mechanisam in ASP.Net.   For good performance of ASP.Net dynamic application we can use cache mechanism. This is nothing but we store some dynamic data into the cache for reusablility of web pages when user request the same again. That means suppose we have a link in our websites, that displays all the items in the database. When user clicks first time, it will fetch all data from the database and displayed to the web page. If a user trying to get same data for the second time, normally we are not able track whether the user tried same data before, so we are doing same procedure again (Fetching data from database and render to the html). As a optimisation part of the we bsite, we need to fetch same data only in single time for a user (Because new items inserted in to the database is rare case). 

Simple codes to cache data in ASP.Net 

To achieve tracking of user’s request, we can use cache mechanism. In the above example when a user trying to get all items from the database, we need to fetch this data and will store to cache object. When the same user trying to get same data for the second time, we need to check is there any data in the cache object, if it is there just displayed to the web page else taken from the db and store to the cache for future. 

How to store a string variable to cache? 

 if (Cache["name"] != null)
    Label1.Text= Cache["name"].ToString();

 To insert objects into the cache, the Add method or different versions of the Insert method of the Cache class can be used. These methods allow us to use the more powerful features provided by the Cache class. One of the overloads of the Insert method is used as follows: (How to store data object into cache in ASP.Net ?)

Cache.Insert("Name", strName,
    new CacheDependency(Server.MapPath("name.txt"),
    DateTime.Now.AddMinutes(2), TimeSpan.Zero);

The first two parameters are the key and the object to be inserted. The third parameter is of type CacheDependency and helps us set a dependency of this value to the file named name.txt. So whenever this file changes, the value in the cache is removed. We can specify null to indicate no dependency. The fourth parameter specifies the time at which the value should be removed from cache. [See example 5 for an illustration.] The last parameter is the sliding expiration parameter which shows the time interval after which the item is to be removed from the cache after its last accessed time.

The cache automatically removes the least used items from memory, when system memory becomes low. This process is called scavenging. We can specify priority values for items we add to the cache so that some items are given more priority than others:

Cache.Insert("Name", strName,
    new CacheDependency(Server.MapPath("name.txt"),
    DateTime.Now.AddMinutes(2), TimeSpan.Zero,
    CacheItemPriority.High, null);
Categories: DotNet Tags:

How to send mail using Gmail in ASP.Net with Godaddy Server?

May 31, 2011 12 comments

Cannot send email in ASP.Net through GoDaddy Servers?

In ASP.Net we can sennd mail to anyone using gmail smtp server. We have created codes for sending mail using gmail credentials and it is working fine in local. But when we uploaded to the server we are unable to send mail using the options. The thing is that we are using GoDaddy Server as hosting server and it is not supported the gmail smtp server to send mail.

How to Send mail in ASP.Net with GoDaddy Server

Inorder to send mail using ASP.Net we got a support from godaddy department and now it is working fine. Following are the codes for sending mail in ASP.Net with GoDaddy Server:

using System.Web.Mail;

public static void sendEmail(EmailDetails objEmail)
                string SERVER = ConfigurationSettings.AppSettings["MailServer"].ToString();

                MailMessage oMail = new System.Web.Mail.MailMessage();
                oMail.From = objEmail.From;
                oMail.To = objEmail.To;
                oMail.Cc = ConfigurationSettings.AppSettings["AdminEmailID"].ToString();
                oMail.Subject = objEmail.Subject;
                oMail.BodyFormat = MailFormat.Html;   // enumeration
                oMail.Priority = MailPriority.High;   // enumeration
                oMail.Body = objEmail.Message;
                SmtpMail.SmtpServer = SERVER;
                oMail = null; // free up resources
            catch (Exception ex)

Here we have a object ‘objEmail’ which holds the mail details such as from address, to address, subject etc. We have to use System.Web.Mail class for send mail. Here we are taking server details from web.config as given below.

  <add key="MailServer" value="" />


When we are running in local system the above code is working fine, but when we uploaded to goDaddy server send mail is not working. Then we have to change mail server details in web.config to following one.

<add key="MailServer" value="" />
Categories: DotNet, GoDaddy Tags: ,

How to identify a process is running using

Function for checking any process is running

//Namespaces we need to use
using System.Diagnostics;
public bool IsProcessOpen(string name)
       //here we're going to get a list of all running processes on
       //the computer
       foreach (Process clsProcess in Process.GetProcesses()) {
              //now we're going to see if any of the running processes
              //match the currently running processes. Be sure to not
              //add the .exe to the name you provide, i.e: NOTEPAD,
              //not NOTEPAD.EXE or false is always returned even if
              //notepad is running.
              //Remember, if you have the process running more than once,
              //say IE open 4 times the loop thr way it is now will close all 4,
              //if you want it to just close the first one it finds
              //then add a return; after the Kill
              if (clsProcess.ProcessName.Contains(name))
                     //if the process is found to be running then we
                     //return a true
                     return true;
       //otherwise we return a false
       return false;

How to run application from

Process psToLaunch = new Process();
        public void LaunchProcess()
                Process psToLaunch = new Process();
                psToLaunch.StartInfo.FileName = "notepad.exe";
            catch (Exception ex)
                throw new Exception("error on LaunchProcess() : " + ex.Message);
Categories: DotNet Tags:

How to sync large size database with sync framework

May 11, 2011 3 comments

By using sync framework 2.1 we can easily sync databases frequently by scheduling sync with some interval. In one of our project we have to give chance for client to schedule sync frequently. We have implemented the functionalities using sync framework 2.1 with ASP.Net mvc application. You can go through the main codes for sync here.

It was working fine until we are testing with large size db (greater than 10 GB). When we are testing with large size db, we got error in the middle of sync process.

The error is  “There is no enough space for the disk”. Then we are increased the size of the target db to 20 GB (source db 10GB) but got same error. We are search on the google and cannot found enough support for the issue. We are going behind the issue and after some days we have found the root cause of the issue. It was not related to sync framework. When sync process is running, a log file will be writing as backend process to the location “C:\Resources\temp\7aad4070ce51495c82cde6b1d410aa65.WorkerRole1\RoleTemp” of Virtual Machine in the worker role (WaHostBootstrapper). The size of this log file will be increasing continuously and there is some limitation for the size of the file (normally 60 mb). Obviously it will take long time to sync large db and log file size increased and crashed once the max size exceeded. At last we have found the solution and now our application can sync large db without any error. The solution is given below.

1.    We need to extend the max size of the log file. We can achieve it by following code in the “ServiceDefinition.csdef”


      <LocalStorage name=”localStoreOne” sizeInMB=”20480″ cleanOnRoleRecycle=”true” />


   Name ( localStoreOne) : indicates your local storage name

    sizeInMB : indicates the maximum size of the log file you want to give.

    cleanOnRoleRecycle : It will delete and recreated log file for each workerrole when it is        set to true

2.    In the “OnStart()” method in the workerrole we need to map the temp folder by using following code.

string customTempLocalResourcePath =


       Environment.SetEnvironmentVariable(“TMP”, customTempLocalResourcePath);

       Environment.SetEnvironmentVariable(“TEMP”, customTempLocalResourcePath);

Then we can see that log file is archived in the middle of sync with some size, and can hold up to the size that we mentioned in the ServiceDefenition file. It is better to  cleanOnRoleRecycle is set to true, then it will automatically deleted the log files once the worker role restart and recreated again.

How can Read and Write Text Files with ASP.NET?

In most of the cases, developer needs to work with read and write text files from the local folder. By using this function, developer can write and save any errors occurred in the application to a txt files and can refer later. Also having so many chances for this function in various domain.

This is a simple explanation of reading and writing text files in ASP.NET 2.0 using the StreamReader and StreamWriter classes.

To read a text file using the System.IO.StreamReader class into a TextBox control use the following code:

System.IO.StreamReader StreamReader1 =

new System.IO.StreamReader(Server.MapPath(“test.txt”));

TextBox2.Text = StreamReader1.ReadToEnd();


If the file does not exist you will get an error. You can check to see if the file exists using this code:

if (System.IO.File.Exists(Server.MapPath(“test.txt”)))

To write the contents of a TextBox control to a text file using the System.IO.StreamWriter class use the following code:

System.IO.StreamWriter StreamWriter1 =

new System.IO.StreamWriter(Server.MapPath(“test.txt”));



In the above example the StreamWriter class will create the text file if it does not exist and over write the file if it does exist. Line breaks in a TextBox control that uses multiline mode will show up in the text file.

Inserting “\r\n” will create a line break in the text file. Adding line breaks from code can be done using this code:

StreamWriter1.WriteLine(“Some text on line1.\r\nSome text on line2.”);

The dowload contains a web page containing two TextBox controls. Edit the TextBox on top and click the save button. A text file will be created using the text in the top TextBox and saved in the same virtual directory as the web page. The new text file is then loaded into the bottom TextBox to show that changes were saved.

This simple example has demonstrated a couple of the more frequent uses for the StreamReader and StreamWriter classes. They can be used with all kinds of text files including XML, web pages, classes (.cs or .vb), and many more.

Categories: DotNet Tags:

Compress and extract file using Gzipstream

May 4, 2011 6 comments

I have faced situation for downloading large blob files from azure server to local folder. It was easy to download the file from azure server. But if file has more than 2 GB (means larger size) it will got error in the middle of the downloading. When I was facing the issue, I was search on google and not found feasible solution soon that’s why I posted this compress and decompress codes here..

using System.IO.Compression;


Compress files ….

public static void Compress(FileInfo fi)


            // Get the stream of the source file.

            using (FileStream inFile = fi.OpenRead())


                // Prevent compressing hidden and

                // already compressed files.

                if ((File.GetAttributes(fi.FullName)

                    & FileAttributes.Hidden)

                    != FileAttributes.Hidden & fi.Extension != “.gz”)



                    //string[] filesplits = fi.FullName.Split(‘.’);

                    // Create the compressed file.

                    using (FileStream outFile =

                                File.Create(fi.FullName + “.gz”))


                        using (GZipStream Compress =

                            new GZipStream(outFile,



                            // Copy the source file into

                            // the compression stream.


                            Console.WriteLine(“Compressed {0} from {1} to {2} bytes.”,

                                fi.Name, fi.Length.ToString(), outFile.Length.ToString());








Decompress compressed file..

public void Decompress(FileInfo fi)


            // Get the stream of the source file.

            using (FileStream inFile = fi.OpenRead())


                // Get original file extension, for example

                // “doc” from report.doc.gz.

                string origName = curFile.Remove(curFile.Length –


                //Create the decompressed file.

                using (FileStream outFile = File.Create(origName))


                    using (GZipStream Decompress = new GZipStream(inFile,



                        // Copy the decompression stream

                        // into the output file.


                        Console.WriteLine(“Decompressed: {0}”, fi.Name);





Categories: Windows Azure Tags: ,
%d bloggers like this: