Showing posts with label dotnet. Show all posts
Showing posts with label dotnet. Show all posts

Sunday, April 21, 2013

clr20r3 P9 system.componentmodel.win32 : Handling unhandled exceptions

The problem : An Application that doesn't start


Happened to come across an older (read dot net 2.0) application which , due to some reason started to misbehave. whenever it is started it said "App has encountered a problem and needs to close. We are sorry for the inconvenience". There are no other details and the only point of hope was the windows log which said.

EventType clr20r3, P1 app_name.exe, P2 1.1.2.0, P3 4f1ea58b, P4 system, P5 2.0.0.0, P6 4889de7a, P7 3839, P8 131, P9 system.componentmodel.win32, P10 NIL.

I was also told by the dev guys that the application is having its own error log which does not show any entry of this error and also the infamous excuse of "It worked yesterday."   and "It is working fine on my machine."


The source


Going through the source code , found that all the methods had try catch blocks with exception logging configured to log everything including stack trace. Even all the line of codes inside the static Main() were enclosed in a try catch.


The Solution


Since there was no handler for unhandledexception written, the same was added just inside the Main()

           AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(delegate(object sender, UnhandledExceptionEventArgs e)
                {
                  if (e.IsTerminating)
                  {
                      object o = e.ExceptionObject;
                      MessageBox.Show(o.ToString()); // use EventLog instead
                  }
                }
            );



This snippet makes sure that no exceptions are unhandled from your side. [On a lighter note, the root cause here in this case was revealed to be an error log which grew out of size]
I suggest the usage of this handler for trapping any exception that stays unhandled.


Understanding the error log [Watson buckets]



For Breaking up the windows error log entry
EventType clr20r3, P1 app_name.exe, P2 1.1.2.0, P3 4f1ea58b, P4 system, P5 2.0.0.0, P6 4889de7a, P7 3839, P8 131, P9 system.componentmodel.win32, P10 NIL.
The entries P1 ,P2 ,P3 etc are the details collected by the system regarding the exception that went unhandled. They are known as Watson buckets. They include the following information


  1. Executable
  2. Assembly version number
  3. File Stamp
  4. Full assembly name
  5. Faulting assembly version
  6. Faulting assembly timestamp
  7. Faulting assembly method def
  8. IL Offset within the faulting method
  9. Exception type




Hopes this helps someone, someday, some time...
Happy Programming...



Thursday, December 8, 2011

Map Network Drive using C# / Vb.net code

This post will show you an easier way to map a network drive using dot net code. you are free to use any .net language of your choice. I will be mostly sticking to C# though.

We will be relying on COM Interop for this and we will be referencing the Windows Script Host Object Model for this task. Lets get going....

  • Step 1.
Open your choice of application project. In this case I am opening a new Windows Forms Application in C#. And you are there on the default form :Form1.

  • Step 2.
Add a new reference.
In Solution Explorer, right click on References and Click on Add reference.

Select the COM tab.

Scroll down and select Windows Script Host Object Model
Now the solution explorer will look like this with an IWshRuntimeLibrary added.

Now you are ready to go.

  • Step 3.
Write Code.
Go to the code window. select your required event [button click or form load or just anything].
Create an instance of the class IWshNetwork_Class
Call the MapNetworkDrive method and you are done.

  • Sample Code
IWshNetwork_Class network = new IWshNetwork_Class();
network.MapNetworkDrive("k:",@"\\192.168.20.35\MyShare", Type.Missing, "user1", "password1");

you can use the following code to UnMap or remove the mapping.

network.RemoveNetworkDrive("k:");

Hope this saves some time for you....
Happy Programming...

Sunday, October 17, 2010

Multiline Textbox Character Limit

Giving character limit to a multiline textbox can be done using a regular expression validator. Add a regular expression validator to theaspx page and set the control to validate as the multiline text box. Then in the validation expression give

^[\s\S]{0,2000}$
This solution limits the character length to 2000 characters including blank spaces and tabs.

Cheers

Monday, June 8, 2009

Coolite : ExtJS + ASP.Net

Every one agrees that using Ajax in ASP.Net is cool. And even cooler if you can use third party javascript/Ajax frameworks. A number of people had asked me whether there is an easy solution to use extJs framework in ASP.Net. So I thought of writing something about that here.

ExtJS is an excellent framework by itself , But a cooler way to integrate it with ASP.Net exists. Enter Coolite Toolkit. Coolite toolkit is A suite of professional ASP.NET AJAX Web Controls
built on the ExtJS JavaScript Framework. The project is in development phase and the current release [as of June 2009] is version 0.8. The control kit is dual licensed and is available in GPL and also with a commercial license.

The Library consists of a vast collection of UI components starting from buttons and datepickers to treeviews, Grid panels , Messageboxes and a Desktop control. You can see them live at Coolite Example Explorer. The controls are easy to use [you need to have a look at their examples to know how to use them and better if you can find time to read the documentation] and intuitive and they offer community help through their forum also.

Another interesting thing that i found with the library is the use of [AjaxMethod] Attribute . By using it you can call any server side method from a javascript function without any flicker/postback and the same is done using Ajax and JSON.

Do find some time to explore this toolkit.


Sunday, March 9, 2008

Send and Receive Mail from C# (SMTP and POP)


Today we shall see both sending of mails from a domain and reading mails from a domain.

Some domains wont allow mails to be send from them from an application if no mail is popped from it,ie;read from it. That means , to send a mail we first need to get pop access to the domain.Once we authenticate that we can start sending mails from that domain.

Include the following code bit in any page.

public class Pop3Exception : System.ApplicationException
{
public Pop3Exception(string str)

: base(str)
{

}
};

public class Pop3Message
{

public long number;

public long bytes;

public bool retrieved;

public string message;

};
public class Pop3 : System.Net.Sockets.TcpClient
{
public void Connect(string server, string username, string password)
{
string message;
string response;

Connect(server, 110);
response = Response();
if (response.Substring(0, 3) != "+OK")
{
throw new Pop3Exception(response);
}

message = "USER " + username + "\r\n";
Write(message);
response = Response();
if (response.Substring(0, 3) != "+OK")
{
throw new Pop3Exception(response);
}

message = "PASS " + password + "\r\n";
Write(message);
response = Response();
if (response.Substring(0, 3) != "+OK")
{
throw new Pop3Exception(response);
}
}

private void Write(string message)
{
System.Text.ASCIIEncoding en = new System.Text.ASCIIEncoding();
byte[] WriteBuffer = new byte[1024];
WriteBuffer = en.GetBytes(message);
NetworkStream stream = GetStream();
stream.Write(WriteBuffer, 0, WriteBuffer.Length);
Debug.WriteLine("WRITE:" + message);
}

private string Response()
{
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
byte[] serverbuff = new Byte[1024];
NetworkStream stream = GetStream();
int count = 0;
while (true)
{
byte[] buff = new Byte[2];
int bytes = stream.Read(buff, 0, 1);
if (bytes == 1)
{
serverbuff[count] = buff[0];
count++;
if (buff[0] == '\n')
{
break;
}
}
else
{
break;
};
};
string retval = enc.GetString(serverbuff, 0, count);
Debug.WriteLine("READ:" + retval);
return retval;
}

public void Disconnect()
{
string message;
string response;
message = "QUIT\r\n";
Write(message);
response = Response();
if (response.Substring(0, 3) != "+OK")
{
throw new Pop3Exception(response);
}
}

public ArrayList List()
{
string message;
string response;

ArrayList retval = new ArrayList();
message = "LIST\r\n";
Write(message);
response = Response();
if (response.Substring(0, 3) != "+OK")
{
throw new Pop3Exception(response);
}

while (true)
{
response = Response();
if (response == ".\r\n")
{
return retval;
}
else
{
Pop3Message msg = new Pop3Message();
char[] seps = { ' ' };
string[] values = response.Split(seps);
msg.number = Int32.Parse(values[0]);
msg.bytes = Int32.Parse(values[1]);
msg.retrieved = false;
retval.Add(msg);
continue;
}
}
}
public Pop3Message Retrieve(Pop3Message rhs)
{
string message;
string response;

Pop3Message msg = new Pop3Message();
msg.bytes = rhs.bytes;
msg.number = rhs.number;

message = "RETR " + rhs.number + "\r\n";
Write(message);
response = Response();
if (response.Substring(0, 3) != "+OK")
{
throw new Pop3Exception(response);
}

msg.retrieved = true;
while (true)
{
response = Response();
if (response == ".\r\n")
{
break;
}
else
{
msg.message += response;
}
}

return msg;
}
}

Now calling PopMail(),

private static void PopMail()
{
try
{
Pop3 obj = new Pop3();
obj.Connect("pop.rediffmailpro.com", "full@email.address", "password");
ArrayList list = obj.List();
foreach (Pop3Message msg in list)
{
Pop3Message msg2 = obj.Retrieve(msg);
System.Console.WriteLine("Message {0}: {1}",
msg2.number, msg2.message);
break;
}
obj.Disconnect();
}
catch (Pop3Exception pe)
{
System.Console.WriteLine(pe.ToString());
}
catch (System.Exception ee)
{
System.Console.WriteLine(ee.ToString());
}
}

will do the tricks.

No we'll see the sending of mails.For that we use a button click event on our application.

private void _sendButton_Click(object sender, EventArgs e)
{
System.Data.Odbc.OdbcConnection connect = new System.Data.Odbc.OdbcConnection();
...
{
..
}
foreach (DataGridViewRow row in grid.Rows)
{
count++;
if (row.Cells[0].Value != null)
{
if (row.Cells[0].Value.ToString() == "True")
{
..
if (count % 300 == 0)
PopMail();
sendMail(row);
..
}
}
}
MessageBox.Show("Mails sent Successfully");
}

bool sendMail(DataGridViewRow row)
{
MailMessage message = new MailMessage();

string getToAddress = row.Cells[4].Value.ToString();
try
{
if (getToAddress == "")
message.To.Add("default@email.id");
else
message.To.Add(row.Cells[4].Value.ToString());
}
catch (Exception ex)
{
message.To.Add("default@email.id");
}
try
{
message.From = new MailAddress("emailid", "domain");
message.IsBodyHtml = true;
string messageBody = GetMessageBody(row);
message.Body = messageBody;
message.Subject = "Hi";
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("smtp.rediffmailpro.com");
System.Net.NetworkCredential smtpAuthen =
new System.Net.NetworkCredential("emailid", "password");
smtp.UseDefaultCredentials = false;
smtp.Credentials = smtpAuthen;
smtp.Send(message);
return true;
}
catch (SmtpException se)
{
Console.WriteLine(se.Message);
return true;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return true;
}
}

In the code you might have noticed that,the PopMail() is called in a loop during limited time interval.That is because,the authentication time expires after sending a couple of mails.So the PopMail is called after sending every 300 mails.

Hope this is useful..

Friday, March 7, 2008

Strongly Typed Dataset C#

Have you ever struggled to generate a Strongly Typed Dataset from an xml File.

Most of you guys might be knowing this technique.

This post is for my friends who dont know how to implement that.I shall explain that to you with the help of two batch files.

One for converting and xml file to its corresponding schema file,ie;xsd and next to generate its class file.

Before that..just a slight introduction.

There are generally two types of dataset.

1.Untyped Dataset
2.Typed Dataset

In an untyped dataset we access a table as,

dataSet.Tables[0]

But in a Typed Dataset it can be accessed by giving,

dataSet.TableName

ie; direct access.

There are many other features.This was just to give a slight idea.

Now we shall see the batch file to convert xml file into xsd.

Type the following code in notepad

c:
cd %VS2003DIR%\SDK\v1.1\Bin
xsd C:\xmlConverter\abc.xml /out:K:\dotnet\csharp\dialogs
pause

and
save this file as xmlToSchema.bat

Now run this batch file.

A new file called abc.xsd will be now available in K:\dotnet\csharp\dialogs

Now create the next batch file.

c:
cd %VS2003DIR%\SDK\v1.1\Bin
xsd K:\dotnet\csharp\dialogs\abc.xsd /c /out:K:\dotnet\csharp\dialogs
pause

Save this file as schemaToCS.bat

On running this file the corresponding class file for the xsd will be generated.Now if we read the xml file to a dataset, the dataset will be a typed dataset.

Very simple right? Hope this is of use to somebody or the other.

Cheers...