Friday, December 16, 2005

Recently I spotted an interesting question on one of the forums. The person asking this question was conserned if it's possible to have some solution for creating some kind of universal wrapper around third-party API. There was one condition. Sometimes API calls throw an exception, but this doesn't necessarily means that method failed, sometimes the service that was queried in this API method was busy. In this case he wanted to repeat the call number of times before throwind an exception about API failure. This task looked like a perfect example to use generic delegates from C# 2.0. So, I refreshed my memories by reading MSDN articles on generics (I suggest you to read them too, especially if you are not familiar with generics terminology) and started on coding. Here is result of my "titanic work" on generics that actually combines generic type, generic method and generic delegate (isn't it just too much generic in one sentence :-)):

class APICaller<P, R> where R : new()
{
   public const int MAX_API_RETRY_ATTEMPTS = 2;

   public delegate R APICall<T>(T param);

   public R ExecuteAPI(APICall<P> func, P param)
   { return ExecuteAPI(func, param, MAX_API_RETRY_ATTEMPTS); }

   public R ExecuteAPI(APICall<P> func, P param, int ex_count)
   {
      int iAttempts = 0;
      R response = new R();
      while (true)
      {
          try
          {
             iAttempts++;
             Console.Write("Attempt " + iAttempts.ToString());
             response = func(param);
             Console.WriteLine(" successfull!");
             break;
          }
          catch (Exception except)
          {
             Console.WriteLine(" failed!");
             // Allow a max number of failures - then die. 
             if (iAttempts > ex_count)
             {
                Console.WriteLine("Max number of attempts reached!");
                throw except;
             }
          }
      } // while true; 
      return response;
   }
}

Let's see what we have here. First of all, I declare generic type APICaller (APICaller<P, R> where R : new()) with two type parameters: P - type of method's parameter , R - type of method's return value. Modifier (where R : new()) says that instance of this type parameter could be created using new() operator. We will need this to create default return value. Then I define public integer const inside this generic type (const int MAX_API_RETRY_ATTEMPTS = 2). It will serve us as a default value for counter of attеmpts. Then there goes the most fascinating part of this declaration - generic delegate type APICall (public delegate R APICall<T>(T param)). Let's explain this string in details. Modifiers public and delegate say that this is a declaration of a public delegate type with the name APICall that takes type T as an input parameter and return result of a type R. That's it, nothing complicated. :-) Then I declare generic method ExecuteAPI (public R ExecuteAPI(APICall<P> func, P param)). This declaration says that public method ExecuteAPI takes two parameters. First parameter is func of previously defined APICall delegate type (here goes a little trick, I pass type parameter P as a type argument for delegate). Second parameter is param of type P. I used two declarations of method ExecuteAPI so that it will be possible to use default value for parameter ex_count (this is a standard pattern in C# since it does not allow you to setup a default value for method parameters). Then I only mention two rows inside this method: declaration of response variable (R response = new R()), that's the place where we use new() operator mentioned above; actual invocation of delegate (response = func(param)).

To use this construction you have to do two things. First, create a constructed type:
APICaller<String, String> foo_string_caller = new APICaller<String, String>();

Second, call ExecuteAPI method by passing actual API function (e.g API.FooString):
foo_string_caller.ExecuteAPI(API.FooString, "str");

That's it!

To download full source of this example use the link below:

Program.zip (1.12 KB)

P.S. I found three interesting articles on delegates on Julien Couvreur's programming blog:
The dark side of C# Delegates
C# Delegates strike back
C# events vs. delegates
Take a look. It's not about generics but a fun reading anyway :-)

posted on 12/16/2005 1:23:48 AM (Eastern Standard Time, UTC-05:00)  #    Comments [1]
 Tuesday, December 13, 2005

My decision to use DasBlog as an engine for this blog was based solely on a couple of posts from Scott Hanselman's blog. During installation there were few problems I wanted to talk about here so that it might be helpfull to somebody. I use ASP.NET 2.0 on my server and blog's virtual dirrectory mapped as a child dirrectory to my main homepage which is a slightly modified version of Personal Web Site Starter Kit from Microsoft. So, before I opened my blog in browser I've read carefully instruction on installation process, especially the part about ASP.NET 2.0 changes. But it looks like there is more to this. As a result of being subdirrectory to my main home page my blog inherited most of the properties from web.config file in the root dirrectory and some of those settings conflicted with default DasBlog's settings. Here is additional changes I did to DasBlog's web.config:

I added parameter styleSheetTheme="" to the <pages> section. This allowed me to get rid of an error about unknown theme. So that was easy to figure out. Let's move along...

The second glith was more weird. It didn't happen right away and come up a day later, after I posted my first blog entry. All of a sudden the blog engine didn't let me do admin's function like add/edit posts even though the day before everything was running just fine. The weird part about this is that I still could login successfully. The only things were missing are admin's functions. That's probably a good way of getting rid of another boring ASP.NET blog, but at least you've got to give me a chance to prove otherwise  :-). So, I started to make changes into configuration files in hope that there might be something wrong with them. I even replaced all of them with versions from original installation on my home desktop. Nope, It didn't help... It turns out, the problem was with ASP.NET 2.0 membership service. Everything went back to normal after I put <roleManager  enabled="false"/ > into DsBlog's web.config. I wonder why it hasn't happen right away after I started this blog :-/...

I'll post a message on the official DasBlog forum tomorrow.

posted on 12/13/2005 5:57:22 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0]
 Sunday, December 11, 2005

This is my first posting to this blog. Here I'll post all kind of thoughts but mostly related about what I do at my job, which is software development. Most of the stuff will be devoted to web-programming, using ASP.NET 2.0 in particular. Besides, I'll post some links that I consider a good reading. All content of this blog will be in English, so if you are one of my russian readers, I'm sorry for not providing content in Russian. I just don't really have time to write it in two languages. I'm working on my homepage and I hope to launch it by NY2006. So, go check it out, maybe it's already up and running.

Now, a couple of words about myself and what I do at work. My name is Vladimir Bychkov. I'm a software developer at Segue Technologies, Inc. located in Old Town of Alexandria, right on the Potomac waterfront. If there wouldn't be a two-stores high brick wall between my office window and Potomac, I would have a beautifull view on this great river with scenic buildings of the Navy Lab on the other bank :-). Someday I'll post a picture of this view which is fun anyway because right above the wall I can see skies that happen to be a landing corridor for DCA so I can see all kind of aircrafts making their way to Washington DC. So, when I'm not busy watching planes or surfing Internet I write some code (mostly in C#) and watch weird stuff hapenning in debugger :-) . In 2004 after Microsoft published first beta (or may be it was even alpha) of Visual Studio Whidbey and .NET Framework 2.0 (they called it v1.2 at that time) I jumped on web development "wagon" and to be honest I enjoy it every day ever since. MS did really great job putting together this release of dotNET. Before I started to do web-development with C#, I programmed using all kind of programming languages like MS Visual C++, Delphi, Java, VB, Modula-2, FoxPro, Pascal, Borlad C++. I also do some database development and UI design.

Few words about my personal live. I'm originaly from Russia, but now I live in Maryland, US. I'm married. My wife's Tatyana a beautiful woman and a great person to live with. We have three sons. Aleksey (Alex) is 8 yo and have a very independent personality but a very kind kid at the same time. On September of 2005 we were blessed with twin boys Nikolay (Nike) and Michael (Mike). So. I guess you figured it on your own that I have a lot on my plate right now :-), but even though I'll try to post valuable content to this blog. When I have a spare minute I like to read a good book or magazine. I'm somewhat outdoorsy person and like to hike at Summer and ski at Winter. While doing this I enjoy to make photos of the nature.

I'll be glad to see your comments here. I'm open to discussions of any kind. There is only one request. Please be polite and respect other opinions. So, I think it's a good way to start and lets see what's coming! :-)

posted on 12/11/2005 11:48:48 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]