Converting Base10 to Base26

There is a post I answered on the asp.net forums I thought was really interesting because it reminded me of my college times. Actually I'm pretty sure that the guy who posted the question was trying to get an answer to his homework, but it doesn't matter, I had fun doing it :-). The problem was to do an ascending sequence using the alphabet (which is a Base26). Something like: A,B,C...Z,AA,AB,AC...AZ,BA,BB,BC...BZ and so on. Well the easiest way to do this is to convert our regular Base10 numbers to Base26 because using Base10 we can do a plain for loop and cout up to the number we want and while doing the loop we can convert the Base10 to Base26. Here is the algorithm: 

        public static string NumberToString(int value)
        {
            StringBuilder sb = new StringBuilder();
            
            do
            {
                value--;
                int remainder = 0;
                value = Math.DivRem(value, 26, out remainder);
                sb.Insert(0, Convert.ToChar('A' + remainder));
                
            } while (value > 0);

            return sb.ToString();
        }

I know this isn't very useful for everyday programming but it was fun to remember the time I was still in college solving this kind of problem. It was a really fun exercise.

Typed Convert using Generics

Last night I answerd a interesting question on the Asp.Net Forums that I thought is worth a post. The objective was to create a method using Generics that could get a value from the Session only instead of returning a Object it would return the value in the type defined in the generic method. Just to make the demonstration easier I'll use a Dictionary instead of the Session but it works just the same:

class TypeTest
{
    private static Dictionary<string, object> PretendSession = new Dictionary<string, object>();

    public static void Test()
    {
        PretendSession.Add("int", 10M);
        Console.Out.WriteLine(Get<int>("int"));
    }

    public static T Get<T>(string theKey)
    {
        object aSessionObject = PretendSession[theKey];

        if (aSessionObject == null)
        {
            return default(T);
        }

        return (T) aSessionObject;
    }
}

This code works well for most cases but you can get in trouble when you work with Value Types. Look at code that follows and to undestand the problems with boxing and unboxing value types:

 //doesn't work, need explicit cast 
int i = 10M; 

//now it's fine 
int i = (int)10M; 

//boxing and unboxing work fine 
object o = 10; 
int i = (int)o; 

//doesn't work 
object o = 10M; 
int i = (int)o;

When you know exactaly what is the type of you are putting inside the Session it all goes fine. When you don't know what type you are working with you need the help of the Convert class to convert the type before casting it. To do this we test if the object is of type ValueType and if it is, before casting it we use the ChangeType method of the Convert class to make sure that the object really contains the type we will try to cast it to.

 

class TypeTest
{
    static Dictionary<string, object> PretendSession = new Dictionary<string, object>();

    public static void Test()
    {
        PretendSession.Add("int", 10M);
        Console.Out.WriteLine(Get<int>("int"));
    }

    public static T Get<T>(string theKey)
    {
        object aSessionObject = PretendSession[theKey];

        if (aSessionObject == null)
        {
            return default(T);
        }

        if (aSessionObject is ValueType)
        {
            return (T)Convert.ChangeType(aSessionObject, typeof(T));
        }

        return (T)aSessionObject;
    }
}

Now you should be safe to use your Get<T> method. Hope this can help other people that face this same issue.

Passed 70-547

Hey, I'm just writing to let my friend know that I have passed the 70-547 exam and now I'm an MCPD Web Developer.

I have to say that the test was way easier than I thought. I think it was the easiest Microsoft test I have ever taken.

If you are asking why I still took a .NET 2.0 exam the reason is simple. I had already bought all the books last year. I was supposed to take the test last October but I had to help out at work doing some long shifts to deliver a product that was sold before we expected. Go news for them and a lot of work for me :-). Not to worry I really like the guys I work for and the system is kind of a son to me so I also had fun. Now that it's over I'm back to my plans.

Now I'm in the process of getting my MCT (Microsoft Certified Trainer).

I'll keep you guys posted on how it goes.

ELMAH: Error logging doesn't get any simpler

ELMAH stands for Error Logging Modules and Handlers. I don't love the name but everything else about it is great!! In it's site it is described as:

"ELMAH (Error Logging Modules and Handlers) is an application-wide error logging facility that is completely pluggable. It can be dynamically added to a running ASP.NET web application, or even all ASP.NET web applications on a machine, without any need for re-compilation or re-deployment."

I'm using this blog as I write it and if I had to classify it I'd say it is a pre pre alpha release not suitable for anyone else but me. The only use I see for other people right now is to look around the code (what should be quick). Given my choice to put the application online in this early stage it seamed pretty obvious that that I needed to start logging the errors my users are getting so that I can work on them as soon as possible. As usual I was deciding between using NLog or Log4Net when I saw a new post by Scott Hanselman talking about ELMAH.

As usual Scott's post saved me a lot of time! Setting up ELMAH was really as simple as he said. In a matter of minutes I was logging all errors in my application. Now I can sleep well knowing that every weekend I'll have a list of errors to work on :-)

I highly recommend you use this in your application even if you are already using another logging framework. The cool thing about ELMAH is that if you missed something forgot to place logging on some part of your app, ELMAH won't. It will log every error you have and store it in XML, SQLServer, Oracle...

Lessons Learned in Url Rewriting

When I decided to write my own blog and leave Mephisto one of the few requirements I felt were really important was to maintain the url pattern I was already using. My articles had url's like this:

www.gbogea.com/year/month/day/permalink

When I first looked up url rewriting in google I found a great article by ScottGu that really suited my needs. I'm using IIS7 on my develpment machine and I thought I was also using it on the hosting service I contracted. ScottGu's post shows a really simple way to do rewriting when using IIS7. All you need is the UrlRewriter.Net module and a few configurations to your web.config.
Checkout SocottGu's post for the whole config, here I'll only show you the pattern I needed to be compatible with the articles url in Mephisto. Here it is:

<rewrite url="~/((19|20)\d\d)/(0?[1-9]|1[012])/(0?[1-9]|[12][0-9]|3[01])/(.+)" to="~/PostDetail.aspx?year=$1&amp;month=$3&amp;day=$4&amp;permalink=$5"/>

Once I did this everything worked fine. I had achieved my objective, or so I thought. The problem is that I found out later on that my hosting service was actually using IIS6 and to my sadness IIS6 doesn't do well with url's that do not have an extension.

When I contacted my hosting they informed me that they had support for ISAPI Rewrite, which is alson discussed in Scott's post but sadly not in engough depth for my case. The configuration is also a lot more anoying then with UrlRewrite.Net. If you have to use ISAPI Rewrite my first recomendation is to get in touch with your hosting and find out if they have version 2 or 3 installed. It makes a great difference. In my case I had version 3 installed. Here are the steps I took to configure it:

1 - Create a ".htaccess" file in the root or your web application.

2 - In the file I've written the following code:

RewriteEngine on
RewriteBase /
RewriteRule ((19|20)\d\d)/(0?[1-9]|1[012])/(0?[1-9]|[12][0-9]|3[01])/(.+)$ /PostDetail.aspx?year=$1&month=$3&day=$4&permalink=$5 [NC,L]


The rewrite rule is basically translating the pattern I'm using (www.gbogea.com/year/month/day/permalink) to the real pattern that the ASP.NET applcation understands (PostDetail.aspx?year=YYYY&month=MM&day=DD&permalink=WHATERVER).

The options and the end are also very important. NC means Case Insensitive. L means that no other subsquent rule should be processed, it stops here. You will find a lot of examples that use an R (which means Redirect) however this was not suited to my case. The redirect would be done to the new URL and then the url shown in the browser would be the ASP.NET url and not mine.

This usage was not easy to figure out. If you need any assistance on using ISAPIRewrite I can recomend this two links:

Documentation: http://www.helicontech.com/isapi_rewrite/doc/
Blog: http://helicontech.blogspot.com/search/label/isapi_rewrite

Helicon's blog was the one that helped me the most. The have a post about common issues people have which is really to the point.

Looking back at all the work I had it would probably be cheaper just to have my hosting plan upgraded to IIS7 but where would be the fun in that right? Joking aside, it's this kind of thing that make you learn, perhaps your client doesn't have the option to migrate to IIS7, then what would you do? Having said that, if you have the choice between using IIS 6 and 7 I would definitely go with 7 and avoid using ISAPI Rewrite altogether.

If you want to have a closer look at my web.config or the .htaccess file you can look at the source code for this blog at speakoutblog.codeplex.com. At this time there is no realease version yet but you can go to the source code and download any commit you want.

Finally, the move is over!

Finally! After a few days my new blog is alive.

I've been using Mephisto for a long time but I felt it was time to change. Mephisto is writen in Ruby On Rails and while I really like Rails I really needed an Blog engine writen in ASP.NET. There were many excelent options like:

Subtext

dasBlog

BlogEngine.Net

All of the above are great blog engines. They are used by most of the community. So which one did I chose? None!

I decided to create my own blog engine. I know, I know...  Why?? Am I crazy? Do I want to take over the blog market? Nope!!! All I really wanted was a pet project that I could really use while allowing me to keep trying new stuff. A blog engine is something simple enough that I don't need to worry about the business rules. It's been done over and over and we use it everyday. It is also small enough that if I ever decide to throw all my code in the trash and start over with a different approach I easily could.

For this adventure I created a project at Codeplex: SpeakOutBlog. From now on SpeakOut is my sandbox, the place I'm going to try ideas and technologies that interest me. The good thing is that at the same time I'll have do something that works, otherwise my blog will go offline. I don't want to let my fans (my wife, dad and mom) down.

On my next post I'll talk about the difficulties I had with URL Rewriting on my shared hosting. I hope that this project keeps giving me material for the blog.

Oh, before I forget... I really want to thanks the guys that develop Subtext, dasBlog and BlogEngine.Net. Their code is really fun to play with and gave me many ideas to use in SpeakOut. I hope someday someone could look at my code and learn something interesting as I have learned from these guys code.

MVC Storefront: Migrating to the Entity Framework

The title of the post is actually misleading. A better title (although too long) would be: Migrating the Repository concept used in the MVC Storefront to the Entity Framework.

Lately I’ve been playing more with the Entity Framework. The other day I was trying to replicate the way Rob Conery used the Repository Pattern in the MVC Storefront sample application and I was surprised to learn that the Entity Framework has some differences from LINQ to SQL that I did not expect.

My first test was very simple. I wanted to get an IQueryable of Posts with it’s respective Comments attached. The StoreFront did this in a really clever and simple manner. The following code was supposed to work:

class BlogRepository
{
    SOEntities ctx = new SOEntities();

    public IQueryable<Comment> GetComments()
    {
        return from comment in ctx.Comments.Include("Post")
               select new Comment()
               {
                   CommentId = comment.CommentId,
                   Author = comment.Author,
                   Body = comment.Body,
                   PostId = comment.Post.PostId
               };
    }

    public IQueryable<Post> GetPosts()
    {
        var posts = from post in ctx.Posts
                    let comments = GetComments()
                    select new Post()
                           {
                               PostId = post.PostId,
                               Title = post.Title,
                               Body = post.Body,
                               Comments = comments.Where(x => x.PostId == post.PostId)
                           };
        return posts;
    }
}

class Post
{
    public Guid PostId { get; set; }

    public string Title { get; set; }

    public string Body { get; set; }

    public IList<Comment> Comments { get; set; }
}

class Comment
{
    public Guid CommentId { get; set; }

    public Guid PostId { get; set; }

    public string Author { get; set; }

    public string Body { get; set; }

}

class Program 
{
static void Main(string[] args)
{
    BlogRepository rep = new BlogRepository();
    var posts = rep.GetPosts();
    posts = posts.Where(x => x.Title.Contains("MVC"));
    List<Post> postList = posts.ToList();
}
}

I get an error saying that Linq to Entities does not recognize the method GetComments().

It’s not a bug, it’s is just the way the EF works. The method GetComments can’t be translated to anything in the provider. But why does it work with Linq to Sql you ask? Because it converts the Linq expression in a different way. Sorry but the post would be too long if I got into this subject.

The way recommended by the EF team is you use the AsEnumerable() extension method, forcing the initial query to be executed and then you would be working with objects. Here is how I needed to change my code for this to work:

public IQueryable<Post> GetPosts()
{
    var posts = from post in ctx.Posts.AsEnumerable()
                let comments = GetComments()
                select new Post()
                       {
                           PostId = post.PostId,
                           Title = post.Title,
                           Body = post.Body,
                           Comments = comments.Where(x => x.PostId == post.PostId)
                       };
    return posts.AsQueryable();
}

This does work, but when ToList() method is called in the posts object, instead of filtering the posts in the sql code, all the posts are brought from the database and then they are filtered as objects. This is a work around but it’s not ideal.

I have another work around, it also isn’t the ideal but it does work in the sense that it will apply the filter in the database.

public IQueryable<Post> GetPosts()
{
    var comments = GetComments();
    var posts = from post in ctx.Posts
                select new Post()
                       {
                           PostId = post.PostId,
                           Title = post.Title,
                           Body = post.Body,
                           CommentsQry = comments.Where(x => x.PostId == post.PostId)
                       };
    return posts;
}

class Post
{
    public Guid PostId { get; set; }

    public string Title { get; set; }

    public string Body { get; set; }

    public IList<Comment> Comments { get; set; }

    public IQueryable<Comment> CommentsQry
    {
        set { Comments = new LazyList<Comment>(value); }
    }
}

The trick is that I introduced a IQueryable property in the Post class. This property receives an IQueryable and under the hood converts it to a LazyList and sets the Comments property. Doing this overcomes the limitation that the EF has in not letting you use constructors that take parameters in the EF code. It only allows parameterless constructors on the select projection.

If you run this code you will see that the records are filtered in the database. The reason I still don’t consider this solution ideal is that I had to make a change to my model class and created a property that is not related to the business but rather to a limitation imposed by the framework. I still don’t see a way around this. If anyone has any suggestions please do leave them as comments.

A very interesting post was written by Muhammad Mosa a while ago. It’s worth visiting his blog to checkout his idea.

Find and Replace using Regular Expressions within Visual Studio

Regular expressions can be a great addition to the Find and Replace functionality within Visual Studio, specially when you want do do some transformation on the text you are looking up. Lately I’m working on a simple conversion class to transform some HTML into RTF. I got a list of special characters in HTML that I had to convert to the RTF equivalent and for that I needed to create a dictionary. The values where listed in a text document like this:

\'b0 \tab &deg;\par
\'b1 \tab &plusmn;\par
\'b2 \tab &sup2;\par
\'b3 \tab &sup3;\par
\'b4 \tab &acute;\par
\'b5 \tab &micro;\par
\'b6 \tab &para;\par
\'b7 \tab &middot;\par
\'b8 \tab &cedil;\par
\'b9 \tab &sup1;\par
\'ba \tab &ordm;\par
\'bb \tab &raquo;\par
\'bc \tab &frac14;\par
\'bd \tab &frac12;\par
\'be \tab &frac34;\par

And I needed to create a dictionary with the key being the HTML code (third column) and the RTF code (first column) the value. Like this:

Dictionary<string, string> charsMapping = 
    new Dictionary<string, string>();
charsMapping.Add("&euro;", @"\'80");

Here is the expression to find the matches within Visual Studio: __ {\\’:a:a}{.}{&:a;}{\\par}

Each pair of { } is a group to be matched. The difference is that the usual \w (letters or numbers) is :a. In my expression I have four groups the fist is the match for the RTF character and the third is the match for the HTML code. Knowing that the Replace expression is as follows: __charsMapping.Add(”\3”, @”\1”);

Here is how it would look like in VS:

Doing this is much easier then creating the dictionary by hand of even writing a console app to do the replace. Sure I could have used some other text tool to do the same but it wouldn’t be as much fun as figuring out how to do it in VS.

Here is the final output:

Dictionary<string, string> charsMapping = 
    new Dictionary<string, string>();
charsMapping.Add("&deg;", @"\'b0");
charsMapping.Add("&plusmn;", @"\'b1");
charsMapping.Add("&sup2;", @"\'b2");
charsMapping.Add("&sup3;", @"\'b3");
charsMapping.Add("&acute;", @"\'b4");
charsMapping.Add("&micro;", @"\'b5");
charsMapping.Add("&para;", @"\'b6");
charsMapping.Add("&middot;", @"\'b7");
charsMapping.Add("&cedil;", @"\'b8");
charsMapping.Add("&sup1;", @"\'b9");
charsMapping.Add("&ordm;", @"\'ba");
charsMapping.Add("&raquo;", @"\'bb");
charsMapping.Add("&frac14;", @"\'bc");
charsMapping.Add("&frac12;", @"\'bd");
charsMapping.Add("&frac34;", @"\'be");
charsMapping.Add("&iquest;", @"\'bf");

Of course the number of characters was much bigger but it doesn’t matter here. If you need more info on regular expressions you might want to check out the Regular-Expressions.info site, they have a lot of good info on the subject. There are some specifics to using regular expressions on VS so you need to make sure to visit MSDN Reference.

Linq: Using Group By with Multiple Columns

I have a group of classes that I build to get metadata from the database to use with my code generators. The class has the following structure:

public class ConstraintMetadata
{
    public string ConstraintName { get; set; }

    public string ColumnName { get; set; }

    public string ConstraintType { get; set; }

    public string TableName { get; set; }
}

I wanted to write a group by clause using Linq to group the objects I retrieved from the db by TableName, ConstraintName and ConstraintType. This would allow me to have one object for each constraint with a list of all the columns. Since Linq only allows one object in the group by clause the way out is to create an anonymous object with all the properties I want.

var constraints = from c in constraintsMetadata
                  group c by new
                             {
                                 c.TableName, 
                                 c.ConstraintType, 
                                 c.ConstraintName
                             } into g
                      select new
                      {
                          g.Key.ConstraintName,
                          g.Key.ConstraintType,
                          g.Key.TableName,
                          Columns = g.Select(x=>x.ColumnName).ToList()
                      };

Now, if I want to get all the constraints for a table and print it to the console window I can do this:

var tableConstraints = constraints.Where(x => x.TableName == table.Name);

foreach (var tableConstraint in tableConstraints)
{
    Console.Out.WriteLine("Constraint Name:{0}, Table:{1}, Type:{2} Columns:", 
        tableConstraint.ConstraintName , 
        tableConstraint.TableName, 
        tableConstraint.ConstraintType);
    foreach (var column in tableConstraint.Columns)
    {
        Console.Out.WriteLine(column);
    }
}

 

Find out the calling method

This is one that I found really interesting. I needed to log which methods were calling a certain method, I knew that reflection was the answer but I never thought it would be so easy.

Have you used the CallStack window on your VisualStudio when you are debugging? Well, all that information is available through the System.Diagnostics.StatckTrace class. This means that you have access to method calling stack to do whatever you like.

The StackTrace is composed of an array of StackFrames which represent each method on the stack.

To demonstrate this I’ll create a class with four methods (Method1, Method2, Method3, Method4) which will be called in the following order:

Main -> Method1 -> Method2 -> Method3 -> Method4

class Program
{
    static void Main(string[] args)
    {
        StackTraceTest stt = new StackTraceTest();
        stt.Method1();
    }
}

class StackTraceTest
{
    public void Method1()
    {
        Console.Out.WriteLine("Inside Method1");
        Method2();    
    }

    private void Method2()
    {
        Console.Out.WriteLine("Inside Method2");
        Method3();
    }

    private void Method3()
    {
        Console.Out.WriteLine("Inside Method3");
        Method4();
    }

    private void Method4()
    {
        Console.Out.WriteLine("Inside Method4");
        StackTrace st = new StackTrace();
        StackFrame[] frames = st.GetFrames();
        for (int i = 0; i < frames.Count(); i++)
        {
            Console.Out.WriteLine("StackTrace info: Index: {0}/Method: {1}", 
                i, frames[i].GetMethod().Name);
        }
    }
}

Each method displays a message on the console letting you know that it has been invoked. When the program gets to Method4 it will print the name of the methods on the stack.

Here is the output:

Put a break point on the end of the Method4 and you can take a look at VisualStudios CallStack window to compare with the console output.

As a test you might want to move the StackTrace code to the other methods to see that it will show all the method that led to method currently executing.

For more information look at the StackFrame and MethodBase classes at MSDN.