Wednesday, October 11, 2006

Every once in a while I make members of my types "internal" so that I can access them inside my assembly but other code (other assemblies) using my types would not have access to those members. The same holds true for all kinds of helper classes that are either designed specifically to handle some internal tasks or whose api is to complicated to be exposed as public. Internal visibility is also the default visibility the class has if not specified otherwise such as in:

class MyClass
{
   
//...
}

Which makes the class "internal" - that is C# compiler defaults to internal.

Suppose now that the project you are working on consists of multiple assemblies be it because every assembly holds types representing different layers or because of the deployement requirements that specify that assemblies should be more granular.

One of the reasons for restricing visibility of types has been mentioned earlier. But what to do in the simple scenario where one company needs to create multiple assemblies, hide some types from public and still be able to use its own "hidden" types across assemblies?

In the old days when I was learning C++ I have learned about "friend classes". Basically what that meant was that one class allowed  other - well known - class to access its otherwise private members. Until recently I thought that It was impossible to do such a thing in .NET, but then came the InternalsVisibleToAttribute...

Although not the same as "friend class" from C++, the InternalsVisibleToAttribute which is new to .NET 2.0 allows you to specify which assembly has access to internal members of the defining assembly. MSDN: "Specifies that all nonpublic types in an assembly are visible to another assembly."

MSDN documentations explains how to use the InternalsVisibleToAttribute, which basically means that to make your internal types available to some other assembly you will need to specify which assemblies should have been able to access the internal types using  an assembly level attribute as follows:

[assembly: InternalsVisibleTo("AssemblyName, PublicKey=123124.....")]

Where AssemblyName is the name of the friend assembly and the PublicKey is the whole public key (not the token) that assembly will be using.

kick it on DotNetKicks.com

Wednesday, October 11, 2006 8:43:25 AM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [1]  | 
 Tuesday, October 10, 2006

Today I have realized that often when I'm writing code I'm using some skeleton methods that will encapsulate some part of the functionality that I don't really want to write right now. So for example I have a main code with a call to a method that does nothing, because its internals have not been defined yet as in the following example:

public int Calculate()
{
   int x = 1;
   
int y = DoSomething(x);
   
return y + 1;
}
private int DoSomething(int x)
{
   
throw new NotImplementedException();
}

The important thing here is the use of the "throw new NotImplementedException();" since it will ensure that in the future, at runtime I will not forget to implement the "DoSomething" method. This is the way I really recommend you to do instead of returning 0 or null value, because then you WILL forget about it.

Fortunately Visual Studio 2005 comes with some refactoring tools that enable you to generate the "DoSomething" method when you wrtite the line "int y = DoSomething(x);" via smart tag. It will even have a default implementation which throws an exception although of type Exception - which I don't understand. There are however situations when you write the method yourself and for this I have created a simpliest code snippet ever. It outputs the "throw new NotImplementedException();" frament inside your method. To use it just type nimpl from "Not Implemented".

The snippet is available in the package with all my other snippets that I use on daily basis. You can read more on the code snippets in my other article: Visual Studio Code Snippets.

kick it on DotNetKicks.com

Tuesday, October 10, 2006 3:03:26 PM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
 Monday, October 09, 2006

Since the version 1.1 of the .NET framework I have been mesuring the performance of my code using the same simple pattern. This basically was something like this:

DateTime begin = DateTime.Now;
DoSomething();
DateTime end = DateTime.Now;
TimeSpan duration = end - begin;

For long running tasks it was good enough, but if a task was very short, often the difference between the begin and end was 0.

Such as the following code:

private void DoSomething()
{
   
int a = 1;
   
for (long i = 0; i < 100; i++)
   {
      a = a + a - 1;
   }
}

Which's duration allways equals to 0 on my, not so fast, machine.

Of course this is a known "feature" of the DateTime now in that it is far from perfect for messuring short periods of time.

So how do you messure the performance of your code without calling some unmanaged functions? Is it at all possible? In 1.1 I do not think so, but fortunately .NET 2.0 comes with a new class called Stopwatch.

The Stopwatch type is defined in the System.Diagnostics namespace and "Provides a set of methods and properties that you can use to accurately measure elapsed time" (MSDN). The code above used the imperfect DateTime.Now can now be written as follows:

Stopwatch sw = new Stopwatch();
sw.Start();
DoSomething();
sw.Stop();
TimeSpan duration = sw.Elapsed;

Beside the fact that the duration will be much more accurate, the Stopwatch offers you a cleaner API to messure your time.

kick it on DotNetKicks.com

Monday, October 09, 2006 8:53:28 AM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [1]  | 
 Thursday, October 05, 2006

So the Google Code Search has made it debut and everyone is happy. Searching for example code has never been easier. Is it all that the the search provides? Is C#, C++, PHP, Java and other languages code all there is? Someone found a WinZip Serial Number Algoritm, but there is one more thing you can do...

Every time there is a code there are comments. So maybe we should try searching for comments? Indeed this could be funny. Try some of the following searches and see the results :-)

The cite of the day: "/* This is crazy, but we are desparate at this point... */" :-)

I'm sure you can come out with more funny search ideas. I expect a wave of creative blog posts that exploit some of the funniest comments out there.

kick it on DotNetKicks.com

Thursday, October 05, 2006 8:53:07 PM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [1]  | 

Debuted just recently the new tool for programmers the Google Code Search is here.

Google Code Search

Maybe it will end the problem of documentation not having enough examples?

A sample search for a "foreach" construct in C# looks promissing.

kick it on DotNetKicks.com

Thursday, October 05, 2006 8:36:13 AM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
 Wednesday, October 04, 2006

Today I have recieved a request for a sample on how to use MyObjectDataSource control. So without delay I have prepared a very simple web project which allows you to see the ease of use of the my control.

ObjectDataSourceExample.zip (19.05 KB)

Sample is divided into 4 pages explaining how to use some of the features of the control. Descrption is added on each page.

Wednesday, October 04, 2006 6:38:47 PM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 

If you are developing n-tier application sooner or later you will find yourself in a situation where you need to move data between the tiers. Be it from the lowest tier - i.e.: the data tier or data access layer (DAL) to a middle tier such as business logic layer (BLL) or the other way around. So how to accomplish this task?

Actually there are many problems with moving data between tiers, especially if you like a clean OOP with a full domain model. Suppose you have a domain object filled with all the necessary methods such as a Teacher who can Grade Students. Now with this logic you also have the data such as Name for both the Sudent and the Teacher. That is your BLL. Now you also have a DAL in which you would like to have a method such as GetTeacherById or SaveStudent. What should those methods return (or accept as a parameter)? The easy answer is - your BLL objects. This implies the referrence from the DAL to BLL - which is wrong since most people will tell you that every layer should only reference the layer below. I agree with this recommendation completly. If you think about a situation where you would like to have some kind of lazy load mechanism for properties of your BLL objects or a simple method call that gets the data from the database such as Teacher.GetGradedStudents, you would have to have a referrence from BLL to DAL.

So is it possible to at the same time have a referrence from DAL to BLL and from BLL to DAL? In .NET it is not possible as long as both are in separate projects. This situation is called a Circular Refference and Visual Studio will not allow you to do it if you try.

So how to solve this issue? Surely there has to be a solution... There are many solutions to the problem. Microsoft has its way described in their article on Designing Data Tier Components and Passing Data Through Tiers. It is a good overview of the problem, but Microsoft being Micorosft has its way of thinking. After all they are the ones that promote the DataSet/DataTable objects.

In short: what you need is an additional component which I will call a Data Transfer Object (DTO). The DTO will be refferenced by both BLL and DAL but will not reference neither BLL nor DAL. This way we have no circular refference problem. The DTO objects will represent only the data, with no behavior. A DataSet/DataTable is an example of such an object. So is the DataReader or an XmlDocument. You can use any of the mentioned objects to move data from your DAL up to BLL, but it gets a little more difficult to do it the other way. More over, if you are not using Typed DataSets, how would you know how to access the name property of the Teacher object? By using an Indexer and a string argument to represent the column name? How do you know what columns are there in the database? Why do you need this knowledge in the BLL? You do not need it! Even more! It is a violation of the rule that the layer should only know about the layer immediatly below, but the database which dictates the column names is not directly below BLL it is below DAL. So not typed DataSets do not shield you from the database and that is why I think they are wrong. A better solution would be to use a strongly typed objects defined in a separate project. So for example there will be a Teacher class in the DTO with a Name property but without a Grade method.

As an example I have prepared a sample solution with 3 projects: BLL, DAL and DTO. You can download the sample here: DTOExample.zip (7.29 KB).

Keep in mind that the example presents only the simpliest scenario where BLL objects know about DAL and how to save themselves. In a real application it will most likely not be the case.

kick it on DotNetKicks.com

Wednesday, October 04, 2006 4:55:01 PM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [2]  | 
 Thursday, September 28, 2006

Today I happend to me for the n-th time! When I have tried to "Get Latest Version" on my solution I got the following message:

---------------------------
Microsoft Visual Studio
---------------------------
Unexpected error encountered. It is recommended that you restart the application as soon as possible.

Error: Unspecified error

File: vsee\lib\path\cvapipath.cpp

Line number: 2459

Of course we have done nothing unusual today. Adding some projects, changing some files etc. All this stuff made using Visual Studio 2005.

As I've mentioned this is not the first time it has happened to me so I thought I knew what to do. I have tried all the hacks that worked previously from deleting the solution file, through deleting the projects that I have found to be causing the problem to getting the files from the computer where it works. Unfortunatelly this time the "standard" procedure has not worked. Strangely enought I was able to commit changes made to the project that caused the problem.

I have been unable to find anything helpful on the internet other than the fact that I'm not alone with this issue.

As the last effort I thought I delete a ".suo" file for my solution. It was a desperate move but it worked! Wow! So basically now if you have any problems with Visual Studio that appear from nowhere, try the .suo file first :-)

As a side note: I have noticed that the new way ASP.NET projects i.e.: no project file, just directory, is a nightmare for source control tools. I have tried Subversion some time ago and the AnkhSVN plugin which in the newest version is said to support the Web Projects but I was a pain setting it up and it does work after all. What is worse is that even Microsoft's own products have problems with Web Projects! Since I remember I have always had problems with SourceSafe and ASP.NET. Be it ASP.NET 1.1 and Visual Studio 2003 or ASP.NET 2.0 and Visual Studio 2005 - always there are problems!

kick it on DotNetKicks.com

Thursday, September 28, 2006 10:56:40 AM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [1]  | 
 Tuesday, September 26, 2006

Previously I have posted an article: What You Should Dispose When Using ADO.NET. There I describe the common pattern for working with ADO.NET objects. Lets go a step further. I think that it is a very bad practice to return a DataReader object from a data layer to some layer above. The reason for this is that in my opinion you should not return move IDisposable objects between layers. Why? Ask yourself a question: who should dispose of such an object? The client layer where the object is used? Or maybe the data layer where the object originates from?

Given the best practices of object oriented programming (OOP) and encapsulation, you should not have to know the inner workings of the objects that you use. In this case you should not have to know if the DataReader is disposed for you or not etc.

But you have to return some kind of data! So what to return? Some time ago I have created a following pattern for running my queries on the database which in a simple form looks more or less like this:

public IEnumerable<DbDataRecord> ExecuteSelect(string commandText)
{
   
using (DbConnection connection = CreateConnection())
   {
      
using (DbCommand cmd = CreateCommand(commandText, connection))
      {
         connection.Open();
         
using (DbDataReader reader = cmd.ExecuteReader())
         
{
            
foreach (DbDataRecord record in reader)
            {
               
yield return record;
            }
         }
         connection.Close();
      }
   }
}

This way the client for this method ends up with a IEnumerable object that looks and acts like a DataReader but is not IDisposable. In fact when you work with DataReader you actually work with the DbDataRecord objects which the DataReader encapsulates.

Notice also the use of base classes such as DbConnection and DbCommand and not concrete implementations such as SqlCommand. This way you can plug any provider you want to this pattern and in fact this is what I do in the helper methods CreateConnection and CreateCommand:

private DbProviderFactory factory;
private DbProviderFactory Factory
{
   
get
   
{
      
if (factory == null)
      {
         factory =
DbProviderFactories.GetFactory(providerInvariantName);
      }
      
return factory;
   }
}
private DbConnection CreateConnection()
{
   
DbConnection connection = Factory.CreateConnection();
   connection.ConnectionString = connectionString;
   
return connection;
}
private DbCommand CreateCommand(string commandText, DbConnection connection)
{
   
DbCommand command = Factory.CreateCommand();
   command.Connection = connection;
   command.CommandText = commandText;
   
return command;
}

The DbProviderFactories and DbProviderFactory are new feature of ADO.NET 2.0 which are useful for making things more generic not that you couldn't do connection.CreateCommand() before ;-).

kick it on DotNetKicks.com

Tuesday, September 26, 2006 10:26:01 AM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [5]  | 

Everyone that has been using ADO.NET to get the data from the database does more or less the same thing. First you create a Connection object, then a Command, then you execute the command to get the DataReader. With reader, you iterate through the collection of records using a while loop. A sample code looks as follows:

string connectionString = "connectionString";
using (SqlConnection connection = new SqlConnection(connectionString))
{
   string commandText = "commandText";
   using (SqlCommand command = new SqlCommand(commandText, connection))
   {
      using (SqlDataReader reader = command.ExecuteReader())
      {
         while (reader.Read())
         {
            //read the data
         }
      }
   }
}

I have noticed that most people use the using statement only for the connection objects because that is what you will find in most of the books and tutorials. There is however one very important thing to remember and that is a simple rule that you should dispose all disposable object as soon as possible. When you look at the ADO.NET objects you will see the connection object is not the only one that can (and should) be disposed. The command object and also the datareader object are also IDisposable so as far as the rule goes you should dispose them. As for the command object I have seen few examples where it is disposed, but I have seen only one where the datareader is disposed.

So just to remind you: dispose your disposable objects!

kick it on DotNetKicks.com

Tuesday, September 26, 2006 9:51:46 AM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [3]  |