Archive

Posts Tagged ‘C#’

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: , , ,

Reading leading Zeros from Text files with OLEDB

OLEDB allows us to read large text files, exactly like reading tables from DataBase. For example, using this connection string, you can simply create connection to CSV file:

@"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=""[Your Directory]"";Extended Properties=""text;HDR=No;FMT=Delimited"";

and then reading it with this command:

"SELECT * FROM [FileName]"

Not only .csv files applicable with this Format, you can also set the delimiter to other values, as Tab.

Suppose you have this simple .csv file:

ColumnA,ColumnB,ColumnC
0001,12,13
00002,15,16

When reading this file to DataTable using OleDbDataAdapter, the leading zeros for the first column will be omitted, since the DataTable recognize this column as an Integer column, and there is no meaning for leading zeros. In order to tell the DataTable to treat this column as a string column, just add file called schema.ini in the same directory of your .csv file, with the following content:

[YourFileName.csv]
ColumnA= Text
ColumnB=Integer
ColumnC=Integer

Now the DataTable will read the first column as string. More options for the schema.ini file you can find here: Much ADO About Text Files

Categories: ADO.NET, C# Tags: , ,

Handling logical delete with Entity Framework 4

Many systems use logical delete in DB, instead of physical delete. For example, when the end user want to delete some records from the DB (not directly, of course), the Data access layer should only set the record’s Deleted column to true, and not use the SQL Delete statement. This behavior is very common used, and very convenient for restoring the data later in case of mistakes. But, of course, it has it drawbacks. In this article, I want to focus on two of them, specifically when using Entity Framework 4:

1. Filtering every query with ‘Deleted = false’ can be very exhausting job. When using Include(), filtering on the second and below levels can force us sometime create more than one query.

2. As I said, sometimes only part of the tables use the logical delete, and others keeps with the physical. We would like to have a generic solution for that, without making changes all the time. For example, if tomorrow we will want to add a logical delete for some table, of course we’re not going to change each query this table appears in.

So, what we got?

I’ve created some simple model, describing Schools DB. As you can see in the diagram, the School & Class entity has logical delete support (by ‘Deleted’ column), and the Student entity needs to be physically deleted when calling delete:

image

First, we will add condition  to the School & Class entities, forcing the model only bring us the undeleted rows (our assumption is, that we really won’t need any deleted rows in our code), like this:

image

We should also delete the ‘Deleted’ column from the model, in order to avoid exceptions. Meaning of this is, that from now on, we will not see the ‘Deleted’ column in our code. Only undeleted rows will be retrieved from DB, and no developer can set (or filter by) this column. So, how we goanna delete exists column?

For this purpose we need to add some code. lets create a partial class for our context, and override the SaveChanges() method. This method is been called each time the model saving changes, so we can catch all deleted items here, and decide whether to actually delete it or not:

var deleted = this.ObjectStateManager.GetObjectStateEntries(EntityState.Deleted);

Next, we will look for each item if he has ‘Deleted’ column in the DB, and execute direct  Update statement. For doing that, we will need to investigate the SSDL (Store model). Remember that Entity framework works with 3 models:

1. CSDL – the conceptual model, describing what you’re going to see in your code.

2. SSDL – the store model, describing your DB.

3. C-S mapping – the mapping model, describing the connections between the two above.

Because we already delete the ‘Deleted’ column from the CSDL, we should ask the SSDL for this column, like this:

var storeItem =  this.MetadataWorkspace.GetItems<EntityType>(DataSpace.SSpace).Where(et => et.Name == deletedItem.EntitySet.Name).FirstOrDefault();

if (storeItem != null)
{
//find the delete property
var deleteProperty = storeItem.Properties.Where(ep => ep.Name == "Deleted").FirstOrDefault();

For simplicity, I supposed that EntitySet.Name and the store name should be equal. Of course, if it’s not, just explore the mapping model to find the correct name. Notice that there is some trick when working with SSDL metadata. Entity framework first load the CSDL, and the SSDL will not be loaded till he needs to create a query for the first time. In order to force the SSDL to load, we will make a fake call to the ToTraceString() method before we will investigate the SSDL. This should be called only one per process:

private void EnforceSsdl()
{
(this.Classes as ObjectQuery).ToTraceString();
}

Next, we will get the entity key name and value, in order to execute direct update on the DB. This code is only for the simple case where you have only 1 key. For complex cases, simply change this:

const string deleteSql = "Update {0} Set Deleted=1 Where {1}={2}";

var keyName = storeItem.KeyMembers.First().Name;
var keyValue = deletedItem.EntityKey.EntityKeyValues.First().Value;
var sql = string.Format(deleteSql, storeItem.Name, keyName, keyValue);
this.ExecuteStoreCommand(sql);

Finally, don’t forget to change this item state back to unchanged, to ensure that EF will not delete it as part of the transaction. Close the method with returning the base.SaveChanges() and it’s done. you can find the Full source code link below.

Source Code Here

Categories: C#, Entity Framework Tags: , ,
%d bloggers like this: