Showing posts with label Code. Show all posts
Showing posts with label Code. Show all posts

How to restart your web application

Generally we all use cache to improve our website's performance. Caching is really useful when we are frequently displaying data which rarely requires changes. But, sometime client request an immediate change in cache entries and we have no option to manually run IISReset or change the contents of web.config file to clear all the cache.

In below code, I am sharing different approaches which can help you:-

namespace Utilities.General

{

    public static class Utility

    {

        public static bool RestartAppPool()

        {

            //First try killing your worker process

            try

            {

                //Get the current process

                Process process = Process.GetCurrentProcess();

                // Kill the current process

                process.Kill();

                // if your application have no rights issue then it will restart your app pool

                return true;

            }

            catch (Exception ex)

            {

                //if exception occoured then log exception

                Logger.Log("Restart Request Failed. Exception details :-" + ex);

            }

 

            //Try unloading appdomain

            try

            {

                //note that UnloadAppDomain requires full trust

                HttpRuntime.UnloadAppDomain();

                return true;

            }

            catch (Exception ex)

            {

                //if exception occoured then log exception

                Logger.Log("Restart Request Failed. Exception details :-" + ex);

            }

 

            //Finally automating the dirtiest way to restart your application pool

 

            //get the path of web.config

            string webConfigPath= HttpContext.Current.Request.PhysicalApplicationPath + "\\web.config";

            try

            {

                //Change the last modified time and it will restart pool

                File.SetLastWriteTimeUtc(webConfigPath, DateTime.UtcNow);

                return true;

            }

            catch (Exception ex)

            {

                //if exception occoured then log exception

                Logger.Log("Restart Request Failed. Exception details :-" + ex);

            }

 

            //Still no hope, you have to do something else.

            return false;

        }

    }

}


To implement above case you can create a dummy page i.e. RestartApplication.aspx or add a querystring parameter to your existing page like Home.aspx?RestartPool=true. Feel free to share your thoughts with me. Happy Codding !!!

Real World Scenario: Object Writer

Recently in a project I was facing a bug which was very difficult to reproduce. So, I decided to log object with complete properties in a text file. This code can be really useful for those who want to solve bugs which only occurs very rarely.

Here is the code of my class which converts object into a string:-

public class ObjectWriter
{
    public static string GetObjectString(object obj)
    {
        StringBuilder sb = new StringBuilder(1024);
        sb.Append("Type: ");
        sb.AppendLine(obj.GetType().ToString());
 
        if (obj == null)
        {
            sb.AppendLine("Value: Null");
        }
        else
        {
            sb.AppendLine("-------------------------");
            var type = obj.GetType();
 
            foreach (var prop in type.GetProperties())
            {
                var val = prop.GetValue(obj, new object[] { });
                var valStr = val == null ? "" : val.ToString();
                sb.AppendLine(prop.Name + ":" + valStr);
            }
        }
        return sb.ToString();
    }
}


Here is sample output and usage of my code:-


In above image I have called ObjectWriter.GetObjectString(ie) and in result varibale you can see that I can see its type and other fields information. You can write this information in log file for further investigation.

Send Mails Via .Net


Here is the code to send mails via .Net:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Mail;
using System.Threading;

/// <summary>
/// Summary description for Emailing
/// </summary>
public class Emailing
{
private const int SmtpPort = 25;
private const string SmtpServer = "__SMTP SERVER NAME___";
private const string UserName = "__ USER NAME ___";
private const string Password = "__ PASSWORD __";
private const bool EnableSsl = false; //For Gmail Server set it to true

/// <summary>    
/// Sends the mail    
/// </summary>    
/// <param name="toEmailAddresses">';' seperated To email addresses.</param>    
/// <param name="fromEmailAddress">From email address.</param>    
/// <param name="subject">The subject.</param>    
/// <param name="body">The body.</param>    
/// <param name="mailAttachments">';' seperated mail attachments.</param>    
/// <param name="isBodyHTML">is body HTML.</param>   
public static void SendMail(string toEmailAddresses, string fromEmailAddress, string subject,
string body, string mailAttachments, bool isBodyHTML)
{
char[] splitter = { ';' };
MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress(fromEmailAddress);
mailMessage.Subject = subject;
mailMessage.Body = body;
mailMessage.IsBodyHtml = isBodyHTML;

//Adding Multiple To Addresses
string[] mailAddresses = toEmailAddresses.Split(splitter);
foreach (string mailAddress in mailAddresses)
{
if (mailAddress.Length != 0)
{
mailMessage.To.Add(new MailAddress(mailAddress));
}
}

//Adding Multiple Attachments
string[] attachments = mailAttachments.Split(splitter);
foreach (string attachment in attachments)
{
if (attachment.Length != 0)
{
Attachment attachFile = new Attachment(attachment);
mailMessage.Attachments.Add(attachFile);
}
}

SmtpClient smtpClient = new SmtpClient();
try
{
smtpClient.Host = SmtpServer;
smtpClient.EnableSsl = EnableSsl;
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = UserName;
NetworkCred.Password = Password;
smtpClient.UseDefaultCredentials = true;
smtpClient.Credentials = NetworkCred;
smtpClient.Port = SmtpPort;
smtpClient.Send(mailMessage);
}
catch
{
mailMessage = null;
smtpClient = null;
}
}
/// <summary>    
/// Sends the mail on thread.    
/// </summary>    
/// <param name="toEmailAddresses">';' seperated To email addresses.</param>    
/// <param name="fromEmailAddress">From email address.</param>    
/// <param name="subject">The subject.</param>    
/// <param name="body">The body.</param>    
/// <param name="mailAttachments">';' seperated mail attachments.</param>    
/// <param name="isBodyHTML">is body HTML.</param>    
public static void SendMailOnThread(string toEmailAddresses, string fromEmailAddress, string subject,
string body, string mailAttachments, bool isBodyHTML)
{
Thread mailThread; mailThread = new System.Threading.Thread(delegate()
{
SendMail(toEmailAddresses, fromEmailAddress, subject, body, mailAttachments, isBodyHTML);
});
mailThread.IsBackground = true; mailThread.Start();

}

}


You can use this class like :-

//Send Simple Mail
Emailing.SendMail("sample@sample.com", "sample@sample.com", "Subject is test", "body is Test", "", true);

//Send mail on thread with two attachments
Emailing.SendMailOnThread("sample@sample.com", "sample@sample.com", "Subject is test", "body is Test", 
"c:\\setup.log;c:\\setup1.log;", true);

In case you want to send emails through Gmail server, then use these settings:-
private const int SmtpPort = 465;//if 465 do not work then try 587
private const string SmtpServer = "smtp.gmail.com";
private const string UserName = "__ USER NAME ___";
private const string Password = "__ PASSWORD __";
private const bool EnableSsl = true;