RSS

Response.Redirect Try catch block , ThreadAbortException


What is with the combination of Response.redirect and Try catch block?



well, most of you who have tried out the combination must have been stuck with a weird error of "Thread was being aborted" and must have wondered what has a thread got to do with Response.redirect?



Well, to answer your question here goes:-

A thread is executing your application in terms of ASP.NET worker process , when you call Response.Redirect(URL);

In your code then to redirect to the new URL specified by you ASP.NET framework must be told to stop the current execution of the page and to transfer the execution to the URL page specified in the method call.

This is done in a 2 way step :-

1) Response.End() is called internally by Response.Redirect to stop the current execution and the ThreadAbortException is thrown.

2) .NET framework will call catch “ThreadAbortException” and stop current execution and start executing the new page.

Now during the Step #1 Response.End will throw out a ThreadAbortException” to let .NET framework know that the current execution needs to be stopped and the execution of new should begin.

Asp.net framework catches the Redirect method's exception, aborts the thread and use a new thread for execution of to be redirected page.



Solution :- The way to get over this problem is to specify Response.Redirect(URL,false) , this will tell .NET framework not to stop the execution of the current thread and hence the error will be resolved.

ThreadAbortException” is a special kind of an exception even if you catch it in a catch block even then it will be raised again at the end of the catch block. When this exception is raised, the runtime executes all the finally blocks before killing the thread.

Visual Studio .NET has detected that the specified Web server is not running ASP.NET version 1.1. You will be unable to run ASP.NET Web applications or services


“Visual Studio .NET has detected that the specified Web server is not running ASP.NET version 1.1. You will be unable to run ASP.NET Web applications or services“

Got this error when i tried to create a new web project on my computer in my new company
Here is the solution i followed :-

  • Open Visual Studio Command prompt.

  • Type “aspnet_regiis -i“ and press enter.


Here is the output :-

c:\>aspnet_regiis -i
Start installing ASP.NET (1.1.4322.0).
Finished installing ASP.NET (1.1.4322.0).


Thats it now try creating a new web project it will work.

UPDATE :

Steps to reach the VS Command Prompt

1) Click Start.
2) Programs/All Programs.
3) Microsoft Visual Studio .Net 2003.
4) Visual Studio .Net Tools
5) Visula Studio .Net 2003 command Prompt.



Server versions of OS

For the Server versions of OS the above step might not work Try the following

To resolve this problem, change the status of ASP.NET 1.1 to Allowed in the Web Service Extension list in IIS 6.0. To do this, follow these steps:






















1.Click Start, point to Programs, and then click Control Panel.
2.Double-click Administrative Tools, and then double-click Internet Information Services (IIS).
3.Click Web Service Extensions.
4.In the details pane, click ASP.NET v1.1.4322 in the Web Service Extension list.
5.Click Allowed to change the status from Prohibited to Allowed.

NOTE:- There is an issue in running ASP.NET over sharepoint portal server some settings need to be made for the 2 to run.

Setting margins while printing Crystal reports.


Crystal reports provides its own printing method, which will print the page but there might be some problems in the print out unless you set the margins for the page.








PageMargins margins = new PageMargins();
' Get the PageMargins structure and set the ' margins for the report.
margins = rep.PrintOptions.PageMargins;
margins.bottomMargin = 350;
margins.leftMargin = 350;
margins.rightMargin = 350;
margins.topMargin = 350; ' Apply the page margins.
rep.PrintOptions.ApplyPageMargins(margins);
' Print the report.
Set the startPageN and endPageN
'parameters to 0 to print all pages.
rep.PrintToPrinter(1, False, 0, 0);

PrinttoPrinter method of Crystal reports

Form Validators Non Microsoft Internet Browser Client side validation


Learnt a new thing today:-

Ever tried using Form Validators on a form which would be opened in a Non MS IE browser?
You will be surprised to see that the client side validation doesn't work even though you have set cleintvalidation to True.
Only the server side validation work for Non MS IE Browsers.


The reason for this is because of the way the validators are built up.

To start with,by default ASP.NET is configured to send HTML 4.0-compliant HTML to only Internet Explorer, and sends HTML 3.2-compliant HTML to all non-Microsoft browsers, even though modern, non-Microsoft browsers such as Netscape 6.0+, Mozilla, Opera etc. can handle HTML 4.0.
This can be taken care of by changing the configuration in the Browser Caps section of the config file.


But one thing that still creates a problem for client side validation is the way the client side script is renedered on to the page.
Using the Browser Caps settings the HTML 4.0  compliant HTML will be rendered onto the page but inspite of this the script emitted by the BaseValidator class contains a javascript block that creates an array of all the validators on that particular page.
This array is used to itterate through to check the validity of the controls on the page
its done using the






document.all[validatorID]

script which is only supported by Microsoft's Internet Explorer While other browsers (including MS IE) supports the standard way





document.getElementById(ID)

There are some workarounds like some people who have build validator controls by extending from the Basevalidator class and overiding the method that emits the Javascript code to emit the correct standard script.
Good news is that this problem is taken care of in Whidbey (.NET 2.0)
Bad news is till its released we have to work with the workarounds :)

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;
}


)



StringBuilder append Vs String Concatenation "+"


For all of you looking for proof that Stringbuilder is faster than the normal string concatenation using "+"

In the following code snippet i have used both the methods and used start time and end time in each method to calculate the Elasped time for each respective method Create a new project and add the necessary labels and the button to check it for yourself.

private void Calculatebutton_Click(object sender, System.EventArgs e)

{

DateTime plusStart;

DateTime plusEnd;

DateTime bldrStart;

DateTime bldrEnd;

string test = String.Empty;

string stringToAppend = "ap";

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

int upperlimit = 100000;

plusStart = DateTime.Now;

for (int i=0 ; i < upperlimit ; i ++ )

{

test += stringToAppend;

}

plusEnd = DateTime.Now;

plusElaspedlabel.Text = plusEnd.Subtract(plusStart).ToString();

plusEndlabel.Text = plusEnd.ToString();

plusStartlabel.Text = plusStart.ToString();

bldrStart = DateTime.Now;

for (int j=0; j < upperlimit ; j ++ )

{

sb.Append(stringToAppend);

}

bldrEnd = DateTime.Now;

bldrElaspedlabel.Text = bldrEnd.Subtract(bldrStart).ToString();

bldrEndlabel.Text = bldrEnd.ToString();

bldrStartlabel.Text = bldrStart.ToString();

}

Lock Workstation through Code , Locking Workstation


Reposting from prev blog

Idle mind is Devils Workshop!!

Today didnt have much tasks to work on as had already finished the task expected to go on till today evening ,hence had loads of free time to try out stuff
Found this link Lockworkstation Function and thouht of implementing it in .NET since I hated the idea of

CTRL + ALT + DEL and ENTER / Win + L to lock my workstation.

Anyways here it is the code

You will need to include the Namespace
using System.Runtime.InteropServices;

Copy the following in the Code behind



[DllImport("user32.dll")]

public static extern void LockWorkStation();

And in the form load event give a call to the LockWorkStation Method we declared above.

private void LockStation_Load(object sender, System.EventArgs e)
{
try

{
LockWorkStation();
}
finally
{
this
.Close();
}
}


Thats it you are done !! Copy the Assembly from the bin folder onto your desktop and click on it whenever you want to Lock your workstation!!

Cheers!!
Copyright © Shounak S. Pandit. Powered by Blogger.

Ads