Archive

Posts Tagged ‘.NET’

Learn C# – Handling Exceptions (4) – Custom Exceptions

  1. Handling Exceptions – Part 1 – Basic Try / Catch
  2. Handling Exceptions – Part 2 – Catch block
  3. Handling Exceptions – Part 3 – Throwing Exceptions
  4. Handling Exceptions – Part 4 – Custom Exceptions

We met some common exception classes till now, and we even experienced throwing those exceptions by ourselves. That’s not always the case – we might want from time to time to throw our own exceptions, that will describe our own errors. For that purpose we should take a look first in the Exception class.

The Exception class

The basic Exception class is very simple, and contains some important properties:

  • Message – Contains details about the thrown exception.
  • Stack Trace – Contains details about all the methods involved.
  • InnerException – Sometimes contains details about the encapsulated exception.

There are some others, but those are the most useful. The constructor of the Exception class can accept custom message, so we can use that in order to supply our own exception:

void RegisterStudent(int age)
{
if (age < 18)
throw new Exception("Student can't be younger than 18 years old!");
}

This solution can feet our needs, but we usually don’t want to rely on strings to distinguish between exceptions. We will prefer something more strongly typed.

Custom Exceptions

The second solution for our desire will be to create custom exceptions. Custom exceptions are very simple to create, and it has only one rule: Inherit the base Exception class (or one of its childs). You can add whatever properties you want to your custom exception class, and use whatever constructor you’d like in the base class. Sometimes you won’t add any property at all – by creating specific type to describe the exception it might be enough. Let’s declare one:

public class StudentAgeException:Exception
{
public StudentAgeException(int age)
:base ("Age "+ age+" is not allowed. student age should be at least 18 years old")
{

}
}

And now we’ll use it:

void RegisterStudent(int age)
{
if (age < 18)
throw new StudentAgeException(age);
}

In the above example we declare new custom exception, that accept int parameter in its constructor and pass a message to the base constructor describing the issue. Whoever get’s the exception don’t need to rely on the message to understand the problem, since the problem is also identified by the type of the exception itself. That way is much more strongly typed and safe, since the caller can now create specific catch block to catch only StudentAgeException, and handle this exception in more specific way.

In the Next post we’ll describe the finally block, which will be the last part of our series.

Advertisements

Learn C# – Handling Exceptions – Part 2

  1. Handling Exceptions – Part 1 – Basic Try / Catch
  2. Handling Exceptions – Part 2 – Catch block
  3. Learn C# – Exceptions Handling – Part 3 – Throwing Exceptions

In this part we goanna look in more depth in the try/catch clauses.

The simple case of try/catch, as we seen in the last post, can catch any exception occurred in the try block, and let us handle it in our catch block.

try
{
  int x = 0;
  int y = 10 / x;
  Console.WriteLine("Done");
}
catch
{
  Console.WriteLine("Error!!");
}
//OUTPUT:Error!!
//Notice: "Done" wasn't printed to the console, since the exception was thrown before.

Let’s see some other options available for the try / catch.

Exception details

Not only the catch block can catch our exceptions, but also supply details about the caught exception, like this:

try
{
  //some exception
}
catch (Exception ex)
{
  //ex is an instance of the Exception class, with properties that supply many details about the exception.
}

The Exception class is the base class for any exception used in the .NET framework, and will be described in details later. For now, just note that this class contains some properties with details about the exception, as error message, where the exception originally occurred, etc.

Handle specific exception

The Exception class is not the only class in .NET used to handle exceptions. Lot’s of other classes are used, and all share one important behavior: They all inherit (directly or indirectly) from the base Exception class. NullReferenceException, DivideByZeroException and many others are all classes that have the same goal – handling exceptions. the difference between them is only the exception type, and sometimes, the details supplied.

specifying specific exception class in the brackets after the catch keyword will result catching only exceptions from this specific type. catch block without any type defined – will catch any exception. For example:

try
{
  int x = 0;
  int y = 10 / x;
}
catch (DivideByZeroException ex)
{
  Console.WriteLine("Error!!");
}
//OUTPUT:Error!!

In the above example, any other exception do not get caught (and if the program won’t find any suitable exception handler – it will probably crash). Notice that unlike method parameters, the ex used as a parameter name for the DivideByZeroException instance is not mandatory, and if you not going to use the ex properties, but only want to limit the exception types been caught, you don’t need to declare ex.

Handling some specific exceptions

The above technique of handling one specific exception, can be multiplied to more than one specific exception, like this:

try
{
 int x = int.Parse(Console.ReadLine());
 int y = 10 / x;
}
catch (DivideByZeroException ex)
{
 Console.WriteLine("Divide by zero exception was caught");
}
catch (FormatException ex)
{
 Console.WriteLine("Format exception was caught");
}

Now we handle two different exceptions – one for the DivideByZero and other for the Format. Whichever occurs first will cause his own catch clause to be executed.

One important thing need to be taken in consideration when declaring multiple exception handlers – The order of the catch clauses. Let’s have a look in some example:

try
{
 int x = int.Parse(Console.ReadLine());
 int y = 10 / x;
}
catch (Exception ex)
{
 Console.WriteLine("Divide by zero exception was caught");
}
catch (FormatException ex)
{
 Console.WriteLine("Format exception was caught");
}

This Example will cause compile-time error. The first catch declares the base Exception class as the type, and the second one declare the FormatException. Since all exception inherit from the base Exception class, any exception that will be thrown in the try block will be considered to be general Exception, so it will be caught in the first catch. Hence, the second catch block will never be called.

In the next post we’ll try to throw some exception by ourselves!

Categories: C#, Learn C# Tags: , , , ,

Learn C# – Handling Exceptions – Part 1

  1. Handling Exceptions – Part 1
  2. Handling Exceptions – Part 2

Let’s start with three basic assumptions:

  1. Developers usually don’t think about all possibilities.
  2. Users are not always friendly.
  3. A good program should handle any situation.

And that brings us to our subject: Handling exceptions.

Exception is any problem that the application hasn’t learned to deal with. Wrong input from the user can cause exception, as well as wrong mathematical operation, or sometimes the inability to connect to the internet when network is down. Since every application need to know exactly what to do anytime – when it doesn’t / can’t – exception been thrown.

Here are some examples:

int myNumber = int.Parse(Console.ReadLine());
//This code can optionally throw exception, if the user input can't be parsed to integer.

 

int x = 0;
int y = 10 / x;
//this code will throw exception anyway, because dividing by zero is not allowed!

 

File.Delete("some path to non-exist file");

Exceptions aren’t bad things by themselves, but if we won’t handle them carefully, they may crash our program, and we don’t want this to happen, right?

In order to handle exception we can use the try/catch clauses, like this:

try
{
  //here is block of code that potentially can throw exception
}
catch
{
  //if exception will be thrown above, this code will be excuted
}

Any exception that will be thrown in the “try” block, will cause immediate transition to the “catch” block. The rest of the code in the try block that hasn’t been executed yet – won’t be executed anymore. here is an example:

try
{
  int x = 0;
  int y = 10 / x;
  Console.WriteLine("Done");
}
catch
{
  Console.WriteLine("Error!!");
}
//OUTPUT:Error!!
//Notice: "Done" wasn't printed to the console, since the exception was thrown before.

In the next posts we goanna cover exception handling in more depth.

Categories: C#, Learn C# Tags: , , , ,

Learn C# – If statement – Part 2

In the last post we discussed about simple if statements and boolean expressions.

Now, what if we want to check if some expression is equals to false? the simple way will be this:


bool b = true;

if (b == false)

{

//code will get executed only if b equlas to false.

}

Of course, our boolean expression won’t be like this always,  so we can also use this one:


int i=10;

if (i != 10)

{

//code will get executed only if i not equal to 10

}

As you can see, the operator “!=” means “not equal to”. Another relevant operator for this kind of  statements will be the “!” operator, which means NOT, take a look:


bool b = false;

if (!b)

{

//code here will get executed since b equal to false, and that's what we've looked for in the condition

}

int i = 3;

if (! (i==3))

{

//code here won't get executed since we're looking for "Not (i equal to 3)".

}

 In the next post will see how to take an alternative actions, if the condition does not exist.
Categories: C#, Learn C# Tags: , , ,

Learn C# – If statement – Part 1

Introduction

Frequently when writing code, we need to perform specific code section only if certain condition exist.

For example, we want to call the student’s mother only if he failed the exam, or printing receipt to the client only if the payment was approved by the credit card company. Taking actions according to conditions is a very common thing to do in real life, and in particular while coding.

Boolean expressions

Here is another thing that we do all the time without realizing it – Asking ourselves questions. Every day, every hour, and probably more than once at an hour. In order to take actions under conditions we must first define the question – and more important  – find the answer – Yes or No. Questions with only Yes No answers are called boolean  statements. Lets take a look at several different boolean expressions:


bool b = true;

OK, that’s not really a boolean expression, it’s more like variable declaration and assignment. But, if you take a look more closely, you’ll be able to see that the variable “b”, after the assignment, is a boolean expression by himself. That’s because it fits into the “Answer” rule – Everything that gives us Yes or No answer (even if there is no question around) will be considered as boolean expression. Since the value of  “b” is “true”, we can consider it as a boolean expression. Let’s see some more examples:


a == 5

Assuming “a” is an integer variable, we’re using the “==” operator to ask our question:  Is “a” equal to 5. I don’t really know at the moment what is the value of  “a”, but I do know that this question has only one of two answers: Yes or No. Here are some more examples for boolean expressions, before we leap into the “if” river:


//x is an integer
x > 10
//str is a string variable
str == "my string"

We’ll talk more about operators in a different post.

If Statement

After we understood some basic things regarding boolean expressions, all we need to do is to push it into the “if” statement using the following syntax:

if ( /* condition */ )
{
   //do something
}

or more specifically:

if (a == 5)
{
   Console.WriteLine("a is Equal to 5!")
}

Notice, that the code written inside the braces will only get executed if the boolean expression of the if statement will be equal to true. Otherwise, the program will continue to execute the code right after the braces. Of course, we can execute more than one line of code inside the braces – as long as we didn’t close the braces – we can proceed with writing a code that only get executed if the boolean expression of the if statement will be true. If we only want to execute one line of code – we can avoid the braces and write this code right after the if statement, like this:

if (a == 5)
   Console.WriteLine("a is Equal to 5!")
Console.WriteLine("This line will be executed anyway!!!")

Notice that the second Console.WriteLine() will get executed anyway even if the condition inside the if will be equal to false – since “if” without braces will only affect the first line of code.

One more thing for this post – We took an example from an integer variable. Let’s take a look in a boolean variable:

bool b = true;
if (b == true)
{
   Console.WriteLine("b is Equal to true!")
}

Since the boolean variable was assigned to true, the condition exist and the Console.WriteLine line will get executed. However, as we said before, the variable “b” itself is a boolean expression (since it’s a boolean variable), so we don’t need to actually ask the question in it’s full form. We can just use this code:

bool b = true;
 if (b)
 {
 Console.WriteLine("b is Equal to true!")
}

Pay attention to the slight difference between those 2 versions, They are both true, and you can use them both, But it definitely gives you some idea about using boolean expressions inside if statements.

We’ll continue with the “if” statements in the next posts.

Categories: C#, Learn C# Tags: , , ,

Creating Multi-key Dictionary object

Dictionary object has many different uses, and since .Net 2.0 the generic support makes it more common. The biggest limitation of the classic Dictionary<TKey, TValue> is that it has only one key. If you need more than one key, you need to look how to customize it.

Maybe a List<T>?

My first thought was about generic List<T>. Suppose I want to use only string values, I can create the Dictionary<List<String>,String> so I can manage the keys in a list like this:

var listDictionary = new Dictionary<List<string>, string>();

But this code has one big limitation. Take a look:

listDictionary.Add(new List<string>
{
"Key1","Key2"
}, "val");
listDictionary.Add(new List<string>
{
"Key1","Key2"
}, "val");
Console.WriteLine("Exception should be thrown already...");

When the Add() method is looking for matching elements in the keys collection to prevent duplicate key, he can’t find that two keys are equal. It’s the same when you trying to call Equal() on a list:

var l1 = new List<string> { "A" };
var l2 = new List<string> { "A" };
Console.WriteLine(l1.Equals(l2));
//Output: False

This is why we should use in such cases the method SequenceEqual:

var l1 = new List<string> { "A" };
var l2 = new List<string> { "A" };
Console.WriteLine(l1.SequenceEqual(l2));
//Output: True

I can always create an extension method and “override” the Add() and ContainsKey() methods, but of course this is not my first choice.

Custom Class

Another option is creating custom class with property for each key. Same as List<T>, it won’t work because it’s a reference type, and by adding new instance of this class we’re taking a risk to add existing key to the collection (and hence,  not getting the correct value when we want it back).

Tuple

In .Net 4.0 Microsoft introduced the Tuple class, which simply  allow creating object with variety of typed fields. The main goal of that object (at least, for our needs) that it’s act like an immutable type – you cannot changed it after it’s first created. For that reason the  default Equals() method will return true for two different instances of the Tuple class with the same values, not like the List<T> type. Creating the “Tupled” Dictionary for the sample above will look like this:

var tupleDictionary = new Dictionary<Tuple<string, string>, string>();

tupleDictionary.Add(new Tuple<string, string>("key1", "key2"), "val");
//When adding this item exception will be thrown as expected
tupleDictionary.Add(new Tuple<string, string>("key1", "key2"), "val");

Now, you can safely call the Add() and ContainsKey() method.

Categories: C# Tags: , , ,

Outlook Suggestions

A great feature was recently added to Gmail, and I think it’s been called “Gmail Suggestions”. This feature remind you to add contacts to your recipients list when sending mails, based on mails from the past.

quick search on Google.com may result the same feature for Outlook, but since I wanted to write some add-in for Outlook 2010 long time ago, it’s sounds like a nice practice.

in this example, I’m not going to spend much time in the Contact search algorithm, performance and some other staff – I only want to show the concept. so, this is how it’s goanna work:

  1. Creating an Object for all recipients by sent mails.
  2. When adding recipients to a new mail, we’ll search for relevant contacts and add them to a window located on the bottom of the new mail screen.

Creating Outlook 2010 Add-in Project

First, I’ll create new Outlook add-in project, by selecting the right project template:

image

As you can see, VS created the ThisAddIn.cs file for you, and except the Auto generated code – we have two event handlers here: one for the startup, and the second for shutdown.

As I said before, in order to complete this feature and make it ready for publish, some points need to be considered. For now, I only want to concentrate in the basic concept: suggest the outlook user some recipients he may forgot.

So first, whenever the outlook client is launched, I’ll look for any sent mail and found the recipients. This operation might be heavy for large mailboxes, so we should consider change this mechanism before production. For now, it should be fine:

private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
Contacts = new Dictionary<List<string>, int>();

Outlook.NameSpace ns = this.Application.GetNamespace("MAPI");
Outlook.MAPIFolder sentMailsFolder = ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderSentMail);

foreach (Outlook.MailItem item in sentMailsFolder.Items.OfType<Outlook.MailItem>())
{
var contactList = new List<string>();

foreach (Outlook.Recipient rec in item.Recipients)
{
contactList.Add(rec.Name);
}

contactList = contactList.OrderBy(c => c).ToList();

/**
* Contacts.ContainsKey won't work here beacuse the list has different reference.
* So we must user foreach.
**/
bool found = false;
foreach (var contacts in Contacts.Keys)
{
if (contacts.SequenceEqual(contactList))
{
contactList = contacts;
found = true;
continue;
}
}

if (!found)
Contacts.Add(contactList, 1);
else
Contacts[contactList]++;
}

Creating the Form Region

Inside Outlook mail window, we want to suggest the user some relevant contacts, and allow him to add them to the To line as quickly as possible.

Right click on your project –> Create New Item – > Outlook Form region, wizard will appear:

We want to create a new form region, so in the first screen the first option will fit our needs. click next in order to get the Type screen. In the type screen we have some options:

  • Separate – this option creates different page to the form, so you cannot see the mail body and the form region at the same time.
  • Adjoining – Select this option, in order the get the form region as part of the mail body screen. we’ll choose that.
  • Replacement – like Separate, this will create new page, but this option will mark this page as the default page for this item.
  • Replace All – let the form region be the only page for that item.

image

Select the Adjoining option, and click next.

In the next page, give the region name, say Suggestion, and check only the first check-box. we will only want the region to appear when we’re in compose mode, no suggestions needed in reading pane / reading mode. After clicking next. keep the MailMessage item as the only one checked, and click Finish.

Create the Suggestion control

Basically outlook region form uses win forms control, so we’ll use simple Flow Layout control for our suggestion control. Go to the toolbox, and add FlowLayout control to the design surface, set the docking to Fill, and add some other design properties if you like to.

when creating the form region, Visual studio automatically created a code behind file with a partial factory class named (in our case) SugestionsFactory. this partial class already contains event handler for the FormRegionInitializing event, so we can make some manipulations like cancel the form region before it’s get into view. For now, no need to put any code over there.

The only thing we need to care of is, updating the suggestion list based on the contacts already appear in the To list. In order to do that, we’ll create a listener to the PropertyChanged event when the form loaded, like this:

private void Suggestions_FormRegionShowing(object sender, System.EventArgs e)
{
this.item = this.OutlookItem as Outlook.MailItem;
item.PropertyChange += new Outlook.ItemEvents_10_PropertyChangeEventHandler(item_PropertyChange);
}

Now, when this listener is called, just need to select the relevant suggestions from the Contacts static property we’ve created before. We decently have more than one option here. my logic was to take all the suggestions that contains all the current recipients, and give them a rank based on how many mails sent to them. then, I choose the best 7, thus not giving the user list with hundreds of items.

After choosing the relevant contacts, add them to the FlowLayout control with a ClickEventHandler. Whenever the user clicks a contact, it should be added to contact list. Notice we called Resolve to force Outlook to resolve this new string as a contact:

void ShowSuggestion(string contact)
{
LinkLabel lb = new LinkLabel();
lb.Text = contact;
lb.Click += new EventHandler(lb_Click);
this.flowLayoutPanel1.Controls.Add(lb);
}

void lb_Click(object sender, EventArgs e)
{
LinkLabel lb = sender as LinkLabel;
item.Recipients.Add(lb.Text);
item.Recipients.ResolveAll();
}

Many things need to be done before using this simple app in real world scenario, like handling contact name changing, and refresh the contact list when new item sent, etc. For now, this is how it looks like:

image

Enjoyסמיילי

Source Code Here

Categories: C#, Outlook Tags: , , , , ,
%d bloggers like this: