Invalid access to memory location. (Exception from HRESULT: 0x800703E6) in Microsoft.SqlServer.Replication

My team use the Sql Server 2005 Replication feature in order to synchronize between databases in different enviornments. One of the strange things though, is that the reference to Microsoft.SqlServer.Replication generated a weird “Invalid access to memory location. (Exception from HRESULT: 0x800703E6)” Error. After a quick google search I found this link which offers a nice workaround (this seems to be VS.NET 2005 bug) which worked for several folks out there but unfortunately it didn’t work for me. The search continues…

 

New Hebrew blog at MS community

I’ve joined Microsoft Israel community so you can now find some of my post in this address:


http://blogs.microsoft.co.il/blogs/orenellenbogen/


I’ll publish a few advanced post in Hebrew in the following month so stay updated.

 

Presenting about advance use of delegates & generics in the next C# group

I’m going to give a deep insight presentation about advanced usage of delegates, generics and anonymous methods at the next C# group meeting.


Please let me know if you’re planning to come(drop me a comment), it will be nice to see some of my co-workers\readers\friends at my first lecture at Microsoft user groups.


The original excrept can be found here. (don’t forget to register, free of charge, by sending an email to: ivcug at comconix dot com)


The Details:


Date:    Wednesday, May 17, 17:00 – 20:00


Place:   Microsoft Israel 


            Hapnina 2  (Amdocs Building)


            Ground Floor


            Raanana


+972 (9) 762-5100         


 


Parking available at the Kurkar parking lot. Proceed straight past the traffic circle and the parking lot will be on your right.


Topic: Advanced Use of Delegates and Generics


Lecturer: Oren Ellenbogen


 This lecture will not be just about Delegates or Generics, but it will combine those topics to show you how you can leverage to usability of those semi-new features. Oren will discuss the receiving of delegates as parameters and the implementation of abstraction in this methodology. He will tie the two topics together by refactoring(live!) existing code using a principle he calls “Code Templating”;  a coding method that allows running unique logic within recurrent code.


 Agenda:



  1. Looking at a “simple” scenarios of recurrent code

    1. Check if a value exists in a collection.
    2. Get the item index in a collection.
    3. Filtering a collection (get only some of the items based on a condition).
    4. Manipulating every item in the collection (string concatenation for example).

  2. Looking at “advanced” scenarios of recurrent code

    1. Querying the database.
    2. Exception handling.

  3. Discuss solutions for further abstraction in those scenarios.
  4. Introduce “Code Templating” – separating the unique code from the recurrent code.
  5. Before we start, getting to know our toolbox: generics & delegates

    1. What are they?
    2. Calling a delegate which was given as parameter – understand the benefits.
    3. Anonymous delegates\methods – how & why
    4. What’s going on under the hood?

  6. Examples of Code Templating in .Net 2.0

    1. Handle those “simple” scenarios via List<T>.Find, List<T>. FindAll, List.<T>.Exists etc…

  7. Refactor (live!) the “advanced” scenarios, step-by-step.
  8. Code Templating – What do we gain? What can we lose?
  9. Q & A

 


Oren Ellenbogen is a Team Leader at SQLink’s R&D Department. Oren’s responsibilities and areas of expertise span from Analyzing and Designing Web Applications to developing innovative coding enhancement tools. Oren’s project leading at SQLink involves all stages and forms from team leadership to high level consulting.


 Oren’s years of developing experience cover a variety of languages including PHP, C++, VB6 and C#.


 Oren published a series of articles at codeproject.com, publishes a programming oriented blog and is an active member of several .Net architects forums.


 As always, although admission is free and you may attend without reserving a place, we kindly request that you notify us if you plan to attend so that we can be sure to have enough chairs and FOOD!

 

Return operation “status” from a method

I sat with Mario today in order to figure out the best way to receive a “status” message from one of our business layer methods.


The task was clear:

We want to activate a rules validation method which will query the data and retrieve the missing operation(s) which are needed before the user can save his data. It is possible that the user have only one operation he has to do but it’s also possible that he has to do N operations. We needed some sort of status combination.
In addition, if the validation passes – we want some sort of “Everything is OK” status.

Our options:



  1. Use ref\out parameter and fill a string variable. Concat error messages to that string and send it back to the caller. The method will return true if everything is good and false otherwise.
  2. Return the error message(s) as string. Again, we’ll have to concat the error messages.
  3. Return a Bitwise Enum which will allow us to “add”\”remove” statuses.

Elimination process:


The main reason we quickly drop options (1) and (2) is the orientation of the error message(s). Sometimes, in act of pure laziness, we will print the error we’ve got from the BL method directly to the user screen. Some time passes by and the user gives you a call and says “Hey, I’m trying to save a user but it throws me an error like [Rule 1] is invalid… What the heck is [Rule 1] ?? I don’t remember seeing it in the user manual!” and you’ll reply “Wait a second, let me see… Hmm… if… else…not… Oh ya!! the bank account number you filled doesn’t match the bank address !”. See the problem here ?


Think about it – your business layer should return a “programmer oriented” message rather than “client oriented” message. If you’ll return some sort of client oriented message from your BL – how would this work in multilingual application ? your BL would talk with some Resource Manager just to return the “correct” message to the user ? No. This is why you have Graphic User Interface layer. So we’ll send a programmer oriented message from the BL back to our caller (for logging purpose), but wait, this will require our GUI to parse the string we’ve got from the BL method and format it for the client. Something like:


if (errorMessage.indexOf(“Rule 1 is invalid”) != -1 && errorMessage.indexOf(“Rule 2 is invalid”) != -1)
{
    // show “1). You must fill the user details. 2). You must fill the user paycheck”
}
else if (errorMessage.indexOf(“Rule 1 is invalid”) != -1)
{
    // show “You must fill the user details”
}
else if (errorMessage.indexOf(“Rule 2 is invalid”) != -1)
{
    // show “You must fill the user paycheck”
}
else
{
    // show “Save complete”
}


Yes, I can make some refactoring (constants, ToLower(), split) but no matter what I’ll do – this code smells (terrible) !


Solution:


This leaves me with option 3. It would be great to ask something *like*:


if (status == ActionStatuses.InvalidRule1 && status == ActionStatuses.InvalidRule2)
{
   // show “You must fill the user details. You must fill the user paycheck”
}
else if (status == ActionStatuses.InvalidRule1)
{
   // show “You must fill the user details”
}
else if (status == ActionStatuses.InvalidRule2)
{
   // show “You must fill the user paycheck”
}
else
{
   // show “Save complete”
}


It’s time to write some code, shall we ?


1). Let’s define a bitwise Enum, so will be able to create a status combination:


[Flags]
public enum SaveUserStatuses
{
   OK = 1,
   BankAccountMissing = 2,
   WrongEmailFormat = 4,
   BankAccountMismatchBankAddress = 8,
   SaveFailed = 16
}


The only rule: if you need to add more values just double the previous value by 2.


2). In our business layer method, we’ll do something like:


public static SaveUserStatuses Save(User user)
{
   SaveUserStatuses status = SaveUserStatuses.OK;


   if (!CheckIfBankAccountExists(user.BankAccount))
      status = (status | SaveUserStatuses.BankAccountMissing) & ~SaveUserStatuses.OK;

   if (!CheckEmailFormat(user.Email))
      status = (status | SaveUserStatuses.WrongEmailFormat) & ~SaveUserStatuses.OK;


   // you get the idea…

   if (status == SaveUserStatuses.OK)
   {
      if (!UsersDal.Save(user))
      {
         status = SaveUserStatuses.SaveFailed;
      }
   }

   return status;
}



The trick here is for every bad validation you add (“|” – bitwise OR)  the required status and remove the “OK” status by using “~” complement operator.


3). Finally, in our GUI:


SaveUserStatuses status = UserBL.Save(someUser);

if ( (status & SaveUserStatuses.BankAccountMissing) == SaveUserStatuses.BankAccountMissing &&
     (status & SaveUserStatuses.WrongEmailFormat) == SaveUserStatuses.WrongEmailFormat )
{
    // show the required message – client\user oriented !
}
// like the above – parse the status and show the required client oriented message(s).



This code smells a lot better:


a). We have no problem extending this code: (1) Add another member to the Enum (2) Add another check to our BL (3) handle the new status at GUI level.


b). We don’t have to parse strings in order to build our errors. Parsing strings is error prone. Using Enum values can set a contract between the BL and the GUI. If someone will break it, we’ll get compile time error (fail fast).


Back to code…

 

Update: A full example of Generics & delegates is now available

I’ve fixed some wrong methods signatures in my article (thanks Ken) and uploded a demo which, I hope, ease the understanding of the entire article.


Go ahead and download.

 

Creating Virtual Directory for ASP.NET 2.0 programmatically

For all of you programmers out there, who develop for asp.net 1.1 and asp.net 2.0 on the same machine – this trick can be quite useful for you !


If you’re still using IIS, you’ll want to create a VD(Virtual Directory) which support asp.net 2.0 for those application developed for that version, and still use VD which support asp.net 1.1 for your older application. Running an asp.net 2.0 application with VD of 1.1 (and vice versa, of course) will not work.
Where’s the catch you may ask ?
Well, if you add a new virtual directory, you may notice that the chosen (default) version is the one you have in the Default Web Site. This can cause some annoying problems as some of your developers(or your server(s) administrator(s)) will define asp.net 2.0 as their default while the others will define asp.net 1.1 as their default. Just mentioning “define a new Virtual Directory for the application X” won’t be enough.


The trick is to create a new Virtual Directory in the old fashion way, and just after it – call


%windir%\Microsoft.Net\Framework\[wanted version]\aspnet_regiis.exe -s w3svc/1/root [your Vitual directory name]


But hack, why do you need to remember all of this ?


Use the new(here is the old, without asp.net 2.0 support), improved, stylish, with asp.net 2.0 support – VDCreator:


VDCreator bin(EXE & Config only) (4.81 KB)


VDCreator Source (39.56 KB)



last but not least 

Ken helped me on this one so thanks mate !

 

Templating with Generics & Delegates

It took me some time to understand the real power behind .Net 2.0 Generics. I think that the lack of usage with delegates hold me back from developing some elegant template-based code. After practicing a little, I managed to pull something off and I thought to share it with you.


My goal:


Create a template for executing an IDbCommand object (as a Reader, NonQuery, Scalar – you name it).


Why?


There is a common pattern for querying the database and that is:


try
{
   using (IDbConnection conn = ProviderFactory.CreateConnection())
   {
      cmd.Connection = conn;

      conn.Open();

      // use the cmd object. 

   } //”using” will close the connection even in case of exception.
}
catch (Exception e)
{
   // 1. Trace ?
   // 2. Rollback transaction ?
   // 3. Throw a wrapper exception with some more information ?
}


I want to make this pattern a template so I could trace the entire traffic(sql queries) between my application to my database in one single place !
I can even change the type of the exception it throws or the information it add to it in just one single place !
You got the idea…


Solution:


Step 1 – delegates as generic handlers:


I declare this two delegates:


public delegate T ReaderHandler<T>(IDataReader reader);
public delegate T CommandHandler<T>(IDbCommand cmd);


I believe that they are pretty simple to grasp, lets see the usage of those delegates in the generic template.


Step 2 – The generic “command executer” template:


/// <summary>
/// Simple command executer “design pattern”.
/// </summary>
/// <typeparam name=”T”>The type to return</typeparam>
/// <param name=”cmd”>The command</param>
/// <param name=”handler”>The handler which will receive the open command and handle it (as required)</param>
/// <returns>A generic defined result, according to the handler choice</returns>
public static T ExecuteCommand<T>(IDbCommand cmd, CommandHandler<T> handler) //*1
{
   try
   {
      using (IDbConnection conn = ProviderFactory.CreateConnection()) //*2
      {
         cmd.Connection = conn;

         // Trace the query & parameters.
         DatabaseTracer.WriteToTrace(TraceLevel.Verbose, cmd, “Data Access Layer – Query profiler”); //*3

         conn.Open();

         return handler(cmd); //*4
      } //”using” will close the connection even in case of exception.
   }
   catch (Exception e)
   {
      // Trace the exception into the same log.
      Tracer.WriteToTrace(TraceLevel.Error, e, “Data Access Layer – Exception”); //*5

      throw WrapException(e); //*6
   }
}


I know, this is hard to watch at first glance, but I’ll walk you through:


*1: Notice the generic type “T” – this will be necessary for returning different types depending on programmer choice (see step 4 for further details).
*2: Create a connection – I’m using some factory I’ve built in order to return a strongly typed connection depending on the selected provider in the application configuration(*.config) file.
*3: Trace the command (CommandText, Parameters etc) – DataBaseTracer class check the “switch” I’ve declared in the .config file and trace the query only if it was requested. This will give me that ability to trace all the queries later on in the production environment (good for prodction debugging).
*4: Send the live command(the connection was opened) to the handler so it can use the command for its needs.
*5: Trace the exception, again, only if requests.
*6: Wrap the exception in DALException – myself, as an architect, believe that the Data Access Layer should throw only DALException exceptions.


Step 3 – A first usage of the template:


/// <summary>
/// Execute the db command as reader and parse it via the given handler.
/// </summary>
/// <typeparam name=”T”>The type to return after parsing the reader.</typeparam>
/// <param name=”cmd”>The command to execute</param>
/// <param name=”handler”>The handler which will parse the reader</param>
/// <returns>A generic defined result, according to the handler choice</returns>
public static T ExecuteReader<T>(IDbCommand cmd, ReaderHandler<T> handler)
{
   return DalServices.ExecuteCommand<T>(cmd,
      delegate(IDbCommand liveCommand) //*1
      {
         IDataReader r = liveCommand.ExecuteReader();
         return handler(r);
      });
}


This one is even harder to follow, but relax, it’s not as bad as you might think.
*1: You can see that I’m using anonymous delegate for the CommandHandler<T>, so the delegate gets the live command object from the ExecuteCommand method and call ExecuteReader() on it. Afterwards, it sends the reader to the ReaderHandler<T> handler (given as parameter).


Step 4 – Real life example, using ExecuteReader<T> to parse a reader into List<Person> and string:


/// <summary>
/// Retrieve the persons according to the specified command.
/// </summary>
/// <param name=”getCmd”>The command to run.</param>
/// <returns>Typed collection of person.</returns>
protected List<Person> ExecuteReader(IDbCommand cmd)
{
   return DalServices.ExecuteReader<List<Person>>(cmd,
      delegate(IDataReader r)
      {
         List<Person> persons = new List<Person>();
         
         while (r.Read())
            // Create a Person object, fill it by the reader and add it to the “persons” list.
      
         return persons;
      });
}


/// <summary>
/// Retrieve the persons xml according to the specified command.
/// </summary>
/// <param name=”getCmd”>The command to run.</param>
/// <returns>Xml representation of the persons.</returns>
protected string ExecuteReader(IDbCommand cmd)
{
   return DalServices.ExecuteReader<string>(cmd,
      delegate(IDataReader r)
      {
         StringBuilder res = new StringBuilder();
         
         while (r.Read())
            // Build the person object xml and add it to “res”.
      
         return res;
      });
}


Step 5 – Leveraging the command executer template:


Now that we understand the template, let’s wrap some more execution “modes”. You can add to it later on, according to your needs.


/// <summary>
/// Execute the db command in “NonQuery mode”.
/// </summary>
/// <param name=”cmd”>The command to parse</param>
/// <returns>Affected rows number</returns>
public static int ExecuteNonQuery(IDbCommand cmd)
{
   return DalServices.ExecuteCommand<int>(cmd,
      delegate(IDbCommand liveCommand)
      {
         return liveCommand.ExecuteNonQuery();
      });
}

/// <summary>
/// Execute the db command in “Scalar mode”.
/// </summary>
/// <typeparam name=”T”>The type to return after parsing the reader.</typeparam>
/// <param name=”cmd”>The command to execute</param>
/// <returns>A generic defined result, according to the handler choice</returns>
public virtual T ExecuteScalar<T>(IDbCommand cmd)
{
   return DalServices.ExecuteCommand<T>(cmd,
      delegate(IDbCommand liveCommand)
      {
         return (T)liveCommand.ExecuteScalar();
      });
}



Conclusions:


Now that every command run via ExecuteCommand<T> method I can capture the entire communication between my Application and my database and make some enhanced production debugging, if I’ll need to. In addition, I can decide what to do in case of an exception or add some generic validation checks later on.


All in just one place.


This is a “real life” usage of the power Generics & delegates give us; Using them may be harder at first, but playing with them for a little bit can give you the ability to “patternize” your repetitive code and thus give you a tremendous power to control and manipulate it.


I hope I was clear enough,
Any feedbacks would be great !

 

Parsing batch of T-SQL statements via IDataReader

I wasn’t aware of it, until now anyway…       


using (SqlConnection conn = new SqlConnection(“your-connection-string”))
{
   string query = “SELECT * FROM T1; SELECT * FROM T2;”;
   SqlCommand cmd = new SqlCommand(query, conn);
   
   conn.Open();
   SqlDataReader reader = cmd.ExecuteReader();
   do
   {
      while(reader.Read())
      {
         // read each row in the statement results.
      }
   }
   while(reader.NextResult()); // jump to the next statement results.
}

 

Lnbogen Challenge: refactor exception handling

Level:


3/10 at Ellenbogen’s scale.


Preface:


You have the following code:


try
{
   // Some code which can throw any kind of exception
}
catch(Exception e)
{
   // If e is from DataGatewayException type – throw the original exception;
   // Otherwise, wrap the exception with DataGatewayException and throw it.
   // In any case – this “block” will throw only DataGatewayException.
   if (!(e is DataGatewayException))
      throw WrapAndPublishException(e); // *
   else
      throw;
}



* WrapAndPublishException method returns a new object from DataGatewayException type (which wraps the original exception).


The Challenge:


Refactor the code above so it will be more readable and extendable(in case we want to re-throw other exception types as well).
Use your imagination.

 

Visual Studio .Net 2005 JIT debugger isn’t available

For some strange reason, I can’t seem to debug my .Net 2.0 application via VS.NET 2005 debugger. I call Debug.Fail(“…”) in my code and run it via Ctrl+F5 – this is the screen I get:


no2005debugger.jpg


Where the hack is my VS.NET 2005 debugger ?!
If anyone found my lost debugger, please send it back to this address (via comment).


Thanks!


btw – debugging with F5 works fine; That makes me wonder how can I control the items in the box (at the picture), maybe registry magic is required. I’ll update if I’ll manage to find my debugger …