RSS

Category Archives: Code Snippets

Code snippets to do some particluar thing ..might or might not have any comments or descriptions related to it…

Extracting HTML source from a URL website

Was just thinking of trying something short and sweet and thought of trying out a snippet for extracting code from the entered url.
Following is the code have not declared the namespaces on top but used them directly in the code to bring more clarity on which namespace the object comes from.

The code is self explanatory so wont add any explanations over here..

</// <summary>
/// Extracts the source from the url entered.
/// </summary>
/// <param name="url">url to fetch the source from.</param>
/// <returns>string: source for the url entered.</returns>
public static string GetHtmlPageSource(string url)
{

System.IO.Stream st = null;
System.IO.StreamReader sr = null;

try
{
// make a Web request
System.Net.WebRequest req = System.Net.WebRequest.Create(url);

// get the response and read from the result stream
System.Net.WebResponse resp = req.GetResponse();
st = resp.GetResponseStream();
sr = new System.IO.StreamReader(st);
// read all the text in it
return sr.ReadToEnd();
}
catch (Exception ex)
{
return string.Empty;
}
finally
{
// close the stream & reader objects.
sr.Close();
st.Close();
}
}

UPDATE:

If you need to authenticate the request use the following just before you make the request to read the source

// authenticate using the credentials passed for getting access to the page.
if (username != null && password != null)
req.Credentials = new System.Net.NetworkCredential(username, password);
// get the response and read from the result stream
.
.
.

 
1 Comment

Posted by on August 16, 2009 in .NET, Code Snippets, Problem Solving

 

Tags: , , ,

Exception Handling .NET Try Catch Finally Block working

Exception handling and performance

The vanila try- catch statement:

try
{

// Execute the code for SQL
}

Catch(Exception Ex)
{

// Handle the exception.
}

In the above example the try catch encapsulates a piece of code executing some DB operations.
In case there is an exception thrown in the try block code the exception will be smartly catched in the catch block and can be processed and handled.

Catch working.

A Catch block is used as a catcher of exceptions. i.e A catch block will catch the exception or any child exceptions that are derived from the class.

try

{

// Execute the code
}

Catch(ArgumentException Ex)
{

// Handle the exception.
}

In the above case any exceptions from the ArgumentException class will be caught in the catch block this will also include any child exceptions of the ArgumentException such as ArgumentOutOfRangeException, ArgumentNullException etc. As these exception classes are derived from the parent class ArgumentException (Remember .NET classes have loads of base classes 🙂 )

Now that its caught what to do?

A Million dollar question!!! In code reviews have seen developers writing a try catch block and catching the exceptions and doing nothing with it. Wake up!!!!!! guys an exception is a exceptional flow of the code.. ie the moment it comes in the exception block it means this wasn’t the expected flow so obviously we cant let it go silently unnoticed.

Of course we don’t navigate it back to the user , but we do need to log it, process it, pass it back to the calling method with more info etc so that the developer is aware of the exceptions that occurred.

When i say Pass it back to the calling method a qts arises in our mind.. if we have to pass it to the calling function why in the name of God do we need to catch it as if we dont catch it it will automatically get thrown back to the calling method!!!!!!.

Thats true completely true, but as a developer we need to understand the exact location of error, maybe we want to add more custom information to the exception and then pass it back to the calling method.

Lets take an example of a utility class you have written for processing some data, now since this is a class which will be providing service to the classes calling on it.It will have to give out details of the exception if any that it will face in the operations..

try

{
// Open file
// Process data
// Send confirmation mail

}Catch(Exception Ex)
{

Logger.WriteLog(“Exception: Method: ProcessData: Parameters: A = 4, b= “ABC”);
Throw new Exception(“Error occured in processing data MethodXYZ with parameters a = 4, b =”ABC”, ex);
}

The above try catch block will not only handle the exception thrown but also log it into the custom logger and then send a customized exception with the details as well as the stack trace for the exception.

Such detailed exception/debuggin output will not only help the developer pinpoint the exception source but also provide him the details of the object when the exception occured.

P.S Its not a good idea to create new exception class objects and send the existing exception through it as it has some performance issues so choose carefully.

Multiple Catch

In the above scenario it would have been better to even drill down to the exact exception type as we have 3 different piece of code

1) File operation
2) Data Processing
3) Email functionality

* Ideally all these 3 functionality should be in their separate methods for maintainability but for the purpose of this example had to club them together in 1 method.

try

{
// Open file
// Process data
// Send confirmation mail

}
Catch(IOExecption Ex)
{
// Perform catch handling for File input /output exceptions
}
Catch(SQLException Ex)
{
// Perform catch handling for DB exceptions
}
Catch(Exception Ex)
{
// Perform catch handling for general exceptions
}

Order of catch blocks and the importance behind it.

We can very well have multiple catch blocks to handle specific exceptions and process them in specific ways, but in such a case such as the above the order of catch blocks holds lot of importance in the way the catch blocks will be functioning.

Care needs to be taken to see that the most specific catch blocks should be on top of the generic exception catch blocks. inshort the derived exception class catch should be on top of the parent exception class.
Please Note: Exception is the parent of all the other exception classes, hence the catch block for exception should be the last

Before we move on to the last part of exception handling need to mention the last catch block which will take care of any exception

try
{
// code
}
Catch
{
}

Why did .NET give this class? when we already have Exception which is the parent class for all exceptions?? Well the answer is simple Exception class is the parent class for all the exceptions that are thrown through managed code or rather .NET code. what about the code which might throw exception ie not written in .NET maybe a COM component, C++, code ? In such a case we can use the above catch block.This block however due to lack of the exception class/object will not provide us with any information on the exception.Its only useful for making sure no exceptions get through.

Finally Block

The last part of try catch is the finally. It should be like a inseparable trio try-catch-finally block.
As we have seen till now incase there is any error the code execution halts at the error code statement and the execution gets thrown into the catch block.

Now incase we had opened a Database connection / File / etc and inbetween the processing of the connection the exception occurs the execution will be thrown to the exception block and in turn the code for closing of the statements wont be executed and the connections will remain open.

To take care of such situations we have a Finally block and as the name suggets this block is executed finally ie after all the above code in try or catch block gets executed.

The finally block is executed:

  • Incase the code gets through the try block without any errors
  • Incase the code falls through the Catch block because of some exceptions.
  • Incase of any flow followed by the code.So the best bet is to put such code in finally block which has to be executed irrespective of the flow of code.
    try

    {

    1) Open Database Connection
    2) Retrieve Records
    3) Process data <<—— Exception gets thrown at this point.
    4) Update records back to DataBase
    5) Close Database Connection

    }
    Catch(SQLException Ex)
    {

    Logger.WriteLog(“Exception: Method: ProcessData: Parameters: A = 4, b= “ABC”);
    Throw new Exception(“Error occured in processing data MethodXYZ with parameters a = 4, b =”ABC”, ex);
    }
    Finally
    {
    If (Connection is Open)
    {
    Close Connection
    }
    }

    In the above scenario we have opened a connection in Point # 1 and while processing data i.e Point # 3 the exception gets thrown.In such a case the other statement below ie Point # 4 & #5 will never get executed as the control will be thrown to the catch block and then out of the method. This will lead to open connection.To take care of such situations instead of writing the close connection code in the Try block we should write the same in the Finally block as this block will get executed irrespective of whther there is an exception or not.

   UPDATE: plz check this post related to exception being raised due to using Response.Redirect
           in a try catch block

Copyright © Shounak Pandit

 

Tags: , , , , , , ,

Crystal Report toolbar images not Displayed ASP.NET

Reposting from old blog

One of my colleague faced a strange problem while using Crystal Reports

He got his report published on the ASPX page but the images in the toolbar weren’t being displayed.
While trying to find out the problem for it I checked the ASPX page and noticed that the src path for the images on the toolbar was from another virtual directory  “crystalreportwebformviewer2” which to our surprise didnt exists on his machine at all.
Well no idea whether that was due to inapropriate installation or what but the fact was we didnt have a directory to which
t he images were being referenced from.

Well anyways here’s the solution to the above problem
When you plan to use the Crystal reports toolbar in your reports it will automatically
refer to the images stored in your program files directory i.e

C:\Program Files\Microsoft Visual Studio .NET 2003\Crystal Reports\Viewers\Images

this directory has all the images in appropriate sub directories inside but for .NET to refer to it at runtime there
needs to be a virtual directory

in Our case the virtual directory being referenced was This might change according to the version of Crystal reports being used.

So all we had to do to get the Images on the toolbar was to

1# Create a virtual directory   crystalreportwebformviewer2
2# M
ap it to  C:\Program Files\Microsoft Visual Studio .NET 2003\Crystal Reports\Viewers\Images

After which the images on the toolbar were displayed without any other issue 🙂

Shounak Pandit

 
 

Tags: ,

How StringBuilder string concatenation affects performance , string builder vs string concatenation “+”

reposting from older blog

How String Concatenation String Builder Append affects performance

Most of us have used String concatenation in our projects, Have we ever given a thought to what goes on behind while concatenating the strings?

There is a major flaw in using string concatenation as against the String builders append concerning performance only.
Except for performance and memory management both are same and give us the same desired output.

How they work

Lets take a look at how the things work when we concatenate strings

lets take a case where we are concatenating 2 strings and assigning the output to a 1st string

outputString += secondString;

In the above case, each instance of the string is created and assigned hence

in total we will have 3 instances of the strings!! Surprised?? well thats how strings concatenation works

It will create a new string outputString,with both old outputString and secondString

String objects in .net are immutable. Once the string has been created, the value can’t be changed. When you type
outputString = outputString + secondString;
you actually discard the old outputString and create a new string object containing the result of the concatenation. When repeated several times, you end up constructing many temporary string objects.

now just imagine the case where you have n number of strings you have to concatenate how many string objects will be created wont that be a waste of time ??? Creating a string object assigning it some value then again creating a string object and so on …..

Imagine the impact on the performance of the application!!!!

Now lets see how String builder works

Using a string builder you will have

System.Text.StringBuilder outputString = new System.Text.StringBuilder();

outputString.Append(secondString);

StringBuilder, is a mutable string hence in this case we just have 1 instance of outputString and the second string is appended into that existing instance
no other instance is created hence the process is efficient and fast.

Note :- The point to remember here is that using StringBuilder for a concatenation of 2-3 strings doesnt make a significant difference in the performance but when you have numerous strings then the usage of StringBuilder has a big positive Impact on the performance

To see a example check my post

Shounak Pandit

 
3 Comments

Posted by on September 10, 2008 in .NET, Code Snippets, Problem Solving

 

Tags: , , , ,

Sending a Appointment programmatically through Code , ASP.NET ,ICalendar Format

Here is  in which you can send appointments via ICalendar format through code and not using the Outlook Object library (This is a very basic version of the way and does not involve much exception handling,and doesnt take care of nth case , explore a bit on that front :))


I am going to show the method of sending an appointment by creating a ICalendar Appointment file first and then sending it as an attachement over email.  (The way in which ICalendar format files are sent when you click on Tools ->Export -> as ICalendar file in the appointment )


Here is the declaration for the TimeFormat and some variables used to fill  the Appoinment details. viz start time,endtime etc.

const string c_strTimeFormat = “yyyyMMdd\\THHmmss\\Z”;
string
strStartTime=””;
string
strEndTime=””;
string
strTimeStamp=””;
string
strTempStartTime =””;
string
strTempEndTime = “”;
string
vCalendarFile = “”;

Create a Skeleton for the appointment ICalendar file format and using the variables created above we will assign the values accordingly into the Appoinment skeleton. (This string concatation can be optimised by using string builder)

// VCalendar Format.
const string
VCAL_FILE =
“BEGIN:VCALENDAR\n” +
“VERSION:1.0\n” +
“BEGIN:VEVENT\n” +
“DTSTART{0}\n” +
“DTEND{1}\n” +
“LOCATION;ENCODING=QUOTED-PRINTABLE:{2}\n” +
“DESCRIPTION;ENCODING=QUOTED-PRINTABLE:{3}\n” +
“SUMMARY;ENCODING=QUOTED-PRINTABLE:{4}\n” +
“TRIGGER:-PT15M\n” +
“PRIORITY:3\n” +
“END:VEVENT\n” +
“END:VCALENDAR” ;

Assign the Appointment values to the variables declared in the first code section and in the appropriate format.

DateTime dtmStartDate = DateTime.Parse(startDate.ToString());
DateTime dtmStartTime = DateTime.Parse(startDate + ” ” + startTime.ToString());
DateTime dtmEndTime = DateTime.Parse(startDate + ” ” + endTime.ToString());
strTempStartTime = string
.Format(“{0} {1}”,
dtmStartDate.ToShortDateString(),dtmStartTime.ToLongTimeString());
strTempEndTime = string
.Format(“{0} {1}”,
dtmStartDate.ToShortDateString(),dtmEndTime.ToLongTimeString());
strTimeStamp = (DateTime.Parse(strTempStartTime)).ToUniversalTime().ToString(c_strTimeFormat);
strStartTime = string
.Format(“:{0}”, strTimeStamp);
strEndTime = string
.Format(“:{0}”,
(DateTime.Parse(strTempEndTime)).ToUniversalTime().ToString(c_strTimeFormat));

Using String.format fill in the Appoinment skeleton created earlier with the variable values.

vCalendarFile =
String.Format(VCAL_FILE, strStartTime, strEndTime, location, summary, subject , strTimeStamp, attendeeEmail.Trim() , “ShaunakP”, attendeeName.Trim(), attendeeEmail.Trim(), organizerEmail.Trim());

Now that we have the ICalendar file created, we need to write it to the disk so as to attach it to the outgoing email
(Anybody knows a method of just creating the ICalendar file in memory and directly attaching the file without creating a Physical file please leave a feedback on how to do that,didnt get much time to look into it.)

filePath += “\\” + subject+ “.ics”;
TextWriter tw = new StreamWriter(filePath);

// write a line of text to the file
tw.WriteLine(vCalendarFile.ToString());

// close the stream
tw.Close();

Now that we have the ICalendar all we need to do is send a mail to the persons involved in the Appoinment with the ICalendar file as an attachment.

// Create object for sending mails

MailMessage mail = new MailMessage();
mail.To = attendeeEmail.Trim();
mail.From = organizerEmail.Trim();
mail.Subject = “You have got a Appointment.”;

// create the attachment
MailAttachment attachment = new MailAttachment(filePath, MailEncoding.UUEncode);
// Attach
mail.Attachments.Add( attachment );
SmtpMail.SmtpServer = _smtpServer;
SmtpMail.Send( mail );

When the Person who receives the mail opens the attached ICalendar file,it will open up in Outlook as an Outlook Appoinment.

Cheers!!

P.S There are a lot of improvements that can be done in this code like for e.g using stringbuilder etc but I have skipped on them as this is just a code snippet.

To see the code for the above SendAppoinment method click here

*Update : For those of you interested in sending a Meeting Request here is the VCalendar format

“BEGIN:VCALENDAR\n” +
“PRODID:-//Microsoft Corporation//Outlook 9.0 MIMEDIR//EN\n” +
“VERSION:2.0\n” +
“METHOD:REQUEST\n” +
“BEGIN:VEVENT\n” +
“ATTENDEE;CN=\”{8}\”;ROLE=REQ-PARTICIPANT;RSVP=TRUE:MAILTO:{9}\n\n” +
“ORGANIZER:MAILTO:{10}\n” +
“DTSTART{0}\n” +
“DTEND{1}\n” +
“LOCATION:{2}\n” +
“TRANSP:OPAQUE\n” +
“SEQUENCE:0\n” +
“UID:{6}\n” +
“DTSTAMP:{5}\n” +
“DESCRIPTION:{3}\n” +
“SUMMARY:{4}\n” +
“PRIORITY:5\n” +
“X-MICROSOFT-CDO-IMPORTANCE:1 \n” +
“CLASS:PUBLIC\n” +
“BEGIN:VALARM\n” +
“TRIGGER:-PT15M\n” +
“ACTION:DISPLAY\n” +
“DESCRIPTION:Reminder\n” +
“END:VALARM\n” +
“END:VEVENT\n” +
“END:VCALENDAR” ;

* Known Issue: If a person rejects the meeting it wont be conveyed to you

 
31 Comments

Posted by on September 10, 2008 in .NET, Code Snippets, Problem Solving

 

Tags: , , , , , , , ,

Datagrid Sorting ASP.NET or How to Sort Datagrid

Datagrid Sorting ASP.NET or How to Sort Datagrid

Step I )

In the Datagrid definition:
add 2 properties AllowSorting = true and OnSortCommand=”MethodName in code behind”

e.g
<asp:datagrid id=”dgSearchList” runat=”server” Height=”125px” Width=”627px” CssClass=”panelChildSolidBorder”
CellPadding=”2″ AllowCustomPaging=”True” AutoGenerateColumns=”False” OnItemCommand=”detailsClicked”
ShowHeader=”True” AllowSorting=”True” OnSortCommand=”dgSearchList_SortClick” PageSize=”4″>

AllowSorting=”True”
makes the datagrid sortable and OnSortCommand=”dgSearchList_SortClick” tells which method to call when the header is clicked.

Step II )

Now we need to define the method to call when the column headers are clicked
here dgSearchList_SortClick is the method that will be called when the Column headers are clicked for sorting.

Codebehind :

public void dgSearchList_SortClick(object sender,DataGridSortCommandEventArgs e)
{
sortField = e.SortExpression; // ie the Sortexpression assigned to the Column.Check STEP III for how to assign a   // sortexpression on a column.
PopulateDatagrid(); //Call the method that populates the Datagrid with
//the values from the Dataview.
}

PopulateDatagrid()
{
if(sortMode.ToString().Trim().Equals(SORT_ASC))
{
sortMode = SORT_DESC; // Here sortMode is just a Variable storing the
direction of the sort.There are better ways to store this than the current one shown hereJ
}
else
{
sortMode = SORT_ASC;
}
txtSortMode.Text = sortMode;

// SORT_DESC and SORT_ASC are constants with the following string values.
// SORT_DESC = “Desc”
// SORT_ASC = “Asc”

DataView dv = new DataView(dt);
dv.Sort = sortField.Trim() + ” ” + sortMode;
dgSearchList.DataSource = dv;
dgSearchList.DataBind();

}

The code above checks whether we want to sort in Ascending order or in Descending order
and assigns the SortExpression concatenated with the Sorting direction (Asc/Desc)
and binds the datagrid again (don’t forget to bind the data grid its very important)

Step III)
You need to specify the sorting expression for that column in the column definition in the ASPX page

e.g
<asp:BoundColumn DataField=”Location” SortExpression=”Location” HeaderText=”LocationArea”>
<ItemStyle Height=”10px” Width=”10px”><!–ItemStyle>
asp:BoundColumn>

be carefull of what you define as the sortexpression because this is what is passed to the codebehind and sortexpression is what identifies which column was clicked for sorting

in this case the sort expression for the LocationArea column is “Location”, hence when we clicking on the location column will set the e.SortExpression (check Step III for e.SortExpression) to “Location”. Hence identifying the column clicked.

 
Leave a comment

Posted by on September 10, 2008 in .NET, Code Snippets, Problem Solving

 

Tags: , , ,

Sending Appointment through .NET

I had to create a Appointment by parsing through the database and then sending a particular guy a appointment which would remind him about the appointment approx 15 mins before the scheduled time. The same way in which Outlook Appointment functions.

Searching a bit, I found a way to utilise the Outlook Object library and send appointments by creating appointment objects and sending them.

Was damn happy with the outcome till I ran the program and then I saw the dreaded Prompt.
Due to a security protocol of MS ( Security patch ),everytime a code tried to create a instance of the Outlook object library and use it to send a mail, appoinment etc. it prompts the user with a dialog box asking him whether to allow access or to reject access to the program trying to use outlook object.

Now, since I was writing the code as a part of Windows Service there was no question of the prompt and letting the user click on the buttons every time code would send a appointment. Hence searching a bit on the outlooks Way of Forwarding Appoinments in ICalendar format and also the great Google 🙂
Found out a way of creating a ICalendar format Appointment and sending it accorss to the attendee.

Here is a way in which you can send appointments via ICalendar format through code and not using the Outlook Object library (This is a very basic version of the way and does not involve much exception handling,and doesnt take care of nth case , explore a bit on that front :))

posted Thursday, February 24, 2005 12:40 AM by Shaunakp with 2 Comments

SendAppointment Method ASP.NET ,ICalendar format
/// Sends a appointment in a ICalendar format.
/// Date of the meeting.
/// Start time of the meeting.
/// End time of the meeting.
/// Subject of the Meeting.
/// Name of the attendees for the meeting.
/// Email addresses of the attendess,seperated by ;.
/// Email address of the organizer.
/// Path of the current working directory.
/// bool indicating the status of the method call.
/// Need to give the current working directory path as the meeting request is
/// stored in the current directory before attaching it to the mail.
/// Will be adding more customisations in the parameters. and a class to encapsulate the parameter passing.
/// meetingRequest.CreateMeeting(“12/3/2004”,
///“12:30:00 PM”,
///“12:50:00 PM”,
///“Discuss demo issues”,
///“we need to have this meeting to discuss certain issues related to demo.”,
///“Conference room 1st floor”,
///shounak pandit,
///shounakp@XYZ.com,
///shounak.pandit@ABC.com,
///“c:\\prj\\temp”); currently requires the filepath to store the ICalendar file in.
////

public bool SendAppoinment(string startDate,
string startTime,
string endTime,
string subject,
string summary,
string location,
string attendeeName,
string attendeeEmail,
string organizerEmail,
string filePath)
{

const string c_strTimeFormat = “yyyyMMdd\\THHmmss\\Z”;
string strStartTime=””;
string strEndTime=””;
string strTimeStamp=””;
string strTempStartTime =””;
string strTempEndTime = “”;
string vCalendarFile = “”;

// VCalendar Format.
const string VCAL_FILE =
“BEGIN:VCALENDAR\n” +
“VERSION:1.0\n” +
“BEGIN:VEVENT\n” +
“DTSTART{0}\n” +
“DTEND{1}\n” +
“LOCATION;ENCODING=QUOTED-PRINTABLE:{2}\n” +
“DESCRIPTION;ENCODING=QUOTED-PRINTABLE:{3}\n” +
“SUMMARY;ENCODING=QUOTED-PRINTABLE:{4}\n” +
“TRIGGER:-PT15M\n” +
“PRIORITY:3\n” +
“END:VEVENT\n” +
“END:VCALENDAR” ;

try
{

DateTime dtmStartDate = DateTime.Parse(startDate.ToString());
DateTime dtmStartTime = DateTime.Parse(startDate + ” ” + startTime.ToString());
DateTime dtmEndTime = DateTime.Parse(startDate + ” ” + endTime.ToString());
strTempStartTime =
string.Format(“{0} {1}”,
dtmStartDate.ToShortDateString(),dtmStartTime.ToLongTimeString());
strTempEndTime =
string.Format(“{0} {1}”,
dtmStartDate.ToShortDateString(),dtmEndTime.ToLongTimeString());
strTimeStamp = (DateTime.Parse(strTempStartTime)).ToUniversalTime().ToString(c_strTimeFormat);
strStartTime =
string.Format(“:{0}”, strTimeStamp);
strEndTime =
string.Format(“:{0}”,
(DateTime.Parse(strTempEndTime)).ToUniversalTime().ToString(c_strTimeFormat));

vCalendarFile =
String.Format(VCAL_FILE, strStartTime, strEndTime, location, summary, subject , strTimeStamp, attendeeEmail.Trim() , “shaunak”, attendeeName.Trim(), attendeeEmail.Trim(), organizerEmail.Trim());

filePath += “\\” + subject+ “.ics”;
TextWriter tw =
new StreamWriter(filePath);

// write a line of text to the file
tw.WriteLine(vCalendarFile.ToString());

// close the stream
tw.Close();

// Create object for sending mails

MailMessage mail = new MailMessage();
mail.To = attendeeEmail.Trim();
mail.From = organizerEmail.Trim();
mail.Subject = “You have got a Appointment.”;

// create the attachment
MailAttachment attachment = new MailAttachment(filePath, MailEncoding.UUEncode);
// Attach
mail.Attachments.Add( attachment );
SmtpMail.SmtpServer = _smtpServer;
SmtpMail.Send( mail );

}
catch (Exception ex)
{
throw new Exception(ex.Message + “for email address : ” + attendeeEmail.Trim() + “;”
,ex.InnerException);
}
return true;
}

)


 
1 Comment

Posted by on September 10, 2008 in .NET, Code Snippets

 

Tags: , , , ,