0 Comments

*cheer*

All right, ladies and gentlemen.  I'm your host with the most, BuggyFixius.  *cheer and clappings*

Today we have an exciting web bug for you.  Let's see if you can... *altogether now* SPOT THE BUG!!

We have with us today, an ASP.NET website project *clappings*.  The project contain a helper class like so:

using System.Web;

public class WebHelper
{
    const string PARAM_USER_ID = "u";

    static HttpRequest request;

    static WebHelper()
    {
        request = HttpContext.Current.Request;
    }

    public static string GetUserId()
    {
        return getRequest(PARAM_USER_ID);
    }

    static string getRequest(string key)
    {
        string value = request[key];
        return string.IsNullOrEmpty(value) ? string.Empty : value;
    }
}

*Ooo, Aaaa and some gasps*

It also has a Default.aspx file containing a plain Label control

  <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>   
     
  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">   
     
  <html xmlns="http://www.w3.org/1999/xhtml" >   
  <head runat="server">   
      <title>Untitled Page</title>   
  </head>   
  <body>  
      <form id="form1" runat="server">  
      <div>  
          <asp:Label ID="Label1" runat="server" />  
      </div>  
      </form>  
  </body>  
  </html>

and the following Page Load event handler:

using System;   
using System.Web.UI.WebControls;   
     
public partial class _Default : System.Web.UI.Page    
{   
    protected void Page_Load(object sender, EventArgs e)   
    {   
        Label1.Text = WebHelper.GetUserId();   
    }  
}

*Some more Ooo, Aaaa and some more gasps*

Contestants... it's time to *altogether now* SPOT THE BUG!!

Hints: open Default.aspx in the browser 2 or more times given a different u querystring.  For example: http://localhost:34939/Default.aspx?u=3959 and then replace the url with http://localhost:34939/Default.aspx?u=4000.

0 Comments

When you use .NET Activator.CreateInstance to create a new object of a certain type, make sure you reference the Project / DLL that contain the type definition or load it manually somehow to an AppDomain.  Otherwise your call will fail. Say you have the following solution:

Solution Foo
    Project Bar1
        IUser
        IDataMapper
          IUser Load(...);
    Project Bar2 (references Bar1)
        ADSpecificDataMapper : Bar1.IDataMapper
          IUser Load(...) { ... }
    Project Bar3
       User : IUser
          IDataMapper m_Mapper = Settings.Instance.UserMapper
          IUser Load(...) { return m_Mapper.Load(...) }
    Project Baz (references Bar1)
        Settings
           Settings Instance = new Settings() //singleton
           IDataMapper Mapper = CreateMapper(ConfigurationManager.AppSettings[...])
           IDataMapper CreateMapper(SpecificMapperClassNameFromAppConfig)
    Project ConsoleTester (references Baz, Bar3)
       Main
          IUser user = User.Load(...);

Note that ConsoleTester is not referencing Project Bar2 (which contain the ADSpecificDataMapper that will be created through the Factory Method CreateMapperin Baz.Settings class.  This will cause it to fail.  Adding Bar2 to the ConsoleTester project reference will remedy the problem.

0 Comments

Yet another post to remind myself just in case I forgot... again.

Troubleshooting Kerberos authentication is a pain. 

Rules of thumb:

"Thou shalt not have more than one service account delegating for the same service to the same server at one one time."

"If thou has ever find thyself in need to violate rule #1, consider assigning the SPN ONLY to the server account itself."

Say you have Server1 and Server2 which belong to domain DOMAIN and ServiceAccount1 and ServiceAccount2 which need to do HTTP delegation.

See the following scenarios:

Forbidden (2 service accounts are mapped to delegate HTTP service on the same server):

HTTP/Server1 DOMAIN\ServiceAccount1
HTTP/Server1 DOMAIN\ServiceAccount2

Allowed (1 service accounts mapped to delegate HTTP service on 2 different servers):

HTTP/Server1 DOMAIN\ServiceAccount1
HTTP/Server2 DOMAIN\ServiceAccount1

Forbidden (service account and server are mapped to delegate HTTP service on the same server):

HTTP/Server1 DOMAIN\ServiceAccount1
HTTP/Server1 DOMAIN\Server1

Allowed (only server account is allowed to delegate HTTP service on that particular server):

HTTP/Server1 DOMAIN\Server1

Tools that you can use to troubleshoot SPNs issues are:

CSVDE + Excel: You can use these two to find out if you have duplicate SPNs.

For example, run CSVDE -f results.csv -r "(objectClass=User)" -l "sAMAccountName,servicePrincipalName" from Command Prompt and then open results.csv using Excel and do your data filtering there to find out the duplicates.  After you found them, you can remove the offending SPN using SETSPN.

KERBTRAY: You can use this tool to remove cached Kerberos tickets on the fly.  Waiting for the ticket to expire by itself is a pain in the butt.

0 Comments

I was reading this particular entry from AlexJ's blog, in which he discussed how to use anonymous type returned from one function in another function.  I strongly recommend you read it first before reading any further.

Basically, most people would think that there is no easy way to return a strongly typed anonymous type from a function since you wouldn't know what it is that you are returning beforehand. Thus, if you wish to return an anonymous type from a function, you are forced to return it as object like so:

object CreateAnonymousObject() 
{
    return new { Name = "John Doe" };
}

The problem of doing it like this is that you lost the ability to access the Name property since object does not have a Name property.  So, your option is to cast it back to its original anonymous type, but alas, how could you do it?

It turned out that there is a way to do this using generic.  If you create a generic function that will return a generic type T and also pass an object of type T in the parameter, you can cast whatever object that you pass as T.  In effect, you are using the object of type T as your example to cast the boxed object to.  See the following code:

T CastByExample<T>(object source, T example)
{
      return (T)source;
}

So now, you can do something like this (for the sake of clarity, I am not going to shorthand these examples):

var o = CreateAnonymousObject();
var prototype = new { Name = "" };
var result = CastByExample(o, prototype);
Console.WriteLine(result.Name); //This should work just fine

To make things a little bit easier to read, we can use the new extension method feature of .NET 3.5 like so:

public static class MyExtensions
{
    public static T CastToTypeOf<T>(this object source, T example)
    {
        return (T)source;
    }
}

And rewrite the example to:

var o = CreateAnonymousObject();
var prototype = new { Name = "" };
var result = o.CastToTypeOf(prototype);
Console.WriteLine(result.Name); //This should work just fine.

This is great.  I don't know what I am going to use it for, but it's nice to know that I can do it when I need it.

And then, another idea comes to my mind.  Hey, what if we need to do similar thing to an anonymous object collection.  How could I do that? How could one creata a generic list of anonymous object?  As it turned out, Kirill Osenkov already solve this particular problem.  You can see it here.

So, let's come up with something interesting to explore this problem.  Lets say that you are querying a Contact database through LINQ, but instead of returning the entire Contact fields, you wish to only return some of them.

Making thing simpler, I decided to mock the Contact class like so (too lazy to create a dbml, so I am querying from in-memory object :) ):

   public class Contact
   {
       public string FirstName { get ; set; }   
       public string LastName { get; set; }   
       public string PhoneNumber { get; set; }   
       public string StreetAddress { get; set; }   
       public string City { get; set; }
   }

And here is an example function that will return you a list of Contacts:

IEnumerable<Contact> GetContacts()
{
    return new List<Contact> {
        new Contact {
            FirstName = "John", 
            LastName = "Doe", 
            PhoneNumber = "555-5501", 
            StreetAddress = "123 Lala Lane", 
            City = "Los Angeles" 
        },           
        new Contact {
            FirstName = "Jane", 
            LastName = "Doe", 
            PhoneNumber = "555-5502", 
            StreetAddress = "567 Lala Lane", 
            City = "New York" }       
        };
    }
}

And you only wish to return the FirstName and LastName from your LINQ query like so:

var query = from c in GetContacts()
            select new { Name = c.FirstName + " " + c.LastName };

Again, for whatever reason, you really really want to encapsulate this as a method, so, you do something like this:

    object GetContactNamesFrom(IEnumerable<Contact> contacts)
    {
        var query = from c in contacts 
                    select new { Name = c.FirstName + " " + c.LastName }; 
        return query.AsEnumerable();
    }

Great!  Now you have something that can return a generic collection of an anonymous type.  But how can we use this in our own function and allow our function to access the Name property?

Well, combining what we've learnt so far, we can come up with something like this...

First, we know we can now cast something to an anonymous type (sort of) using the generic method CastByExample or CastToTypeOf as seen above.

Second, we need a way to create an anonymous collection.

Let's start with the second one first.  We need a way to create an anonymous collection.  So let's think about this a bit.  i hope you've read the blog post by Kirill by now.  If not, well, here is how you do it...

Now you can do something like:

var prototype = new { Name = "" };   
var prototypeCollection = CreateEnumerablesByExample(prototype); //This is now a generic collection of anonymous.

What's left for us to do is cast our LINQ result back as the prototypeCollection so we can get access to the Name property from our code like so:

var contactInfo = GetContactNamesFrom(GetContact()); 
var prototype = new { Name = "" }; 
var prototypeCollection = CreateEnumerablesByExample(prototype); 
var result = contactInfo.CastToTypeOf(prototypeCollection);
foreach (var c in result)
{
    Console.WriteLine(c.Name);
};

We can do one better by using extension method.  Let's refactor CreateEnumerableFrom as an extension method like so:

public static IEnumerable<T> CreateEnumerablesOfThis<T>(this T prototype)
{
    return new List<T>();
}

The refactored code of our final example will look like this:

var contactInfo = GetContactNamesFrom(GetContact()); 
var prototype = new { Name = "" }; 
var protoypeCollection = prototype.CreateEnumerablesOfThis(); 
var result = contactInfo.CastToTypeOf(prototypeCollection);
foreach (var c in result)
{
    Console.WriteLine(c.Name);
}

So, why would go through all these trouble?  Honestly, I have no idea.  I am just exercising my brain just to see if I can do such a thing.  I have no real need for this type of things yet.  Who knows... maybe someday...

0 Comments
  • Posted in:
  • Fun

Off development topic on this one...

One thing that I love to do to relax is read Fantasy and Sci-Fi novels during my spare time.  A chapter here before sleep, a chapter there while eating, a chapter while ...., well *cough* *cough*, use your imagination. I've been working my way through a couple of excellent titles / series for some time now.  One of them is Robert Jordan's Wheel of Time series and the other is Orson Scott Card's Ender's Game series.

The first is in the fantasy camp with magic, sword fighting, bad god, prophecy, evil creatures, big scale battle, etc. etc.  If you need a better mental picture, picture Lord of the Ring movies on steroid.  Personally, I love this work better than J.R.R. Tolkien's LoTR series.  I found it more to my pace and style.  Vivid battles, tension, etc.  Tolkien's a bit of boring read compared to this series (the movies were great though).  Too bad the author has not finished the last book (Memory of Light) in which he promise will bring the series into conclusion.  I hope Robert can finish this book before he pass away, I can't wait to read it.  (Robert Jordan is suffering from amyloidosis and cardiomyopathy, which I think is not curable).

The second one is in the Science Fiction camp, particularly intergalactic war, space opera sort of thing.  I've just started reading the series (finished Ender's Game and halfway through Speaker for the Death) and so far, I like it a lot.  The pace is just right, the characters are interesting and the plot are moving along just nicely. Looks like there are some more books yet to be written in this series also.  But, I am not desperate for them yet since I am just starting on this series.

Other authors whose books I often frequent are R.A. Salvatore, specifically anything with Drizzt and his companions in them. They are just awesome. Smile with tongue out  If you are into fantasy Dungeon and Dragon style, go pick his books up, you won't regret it.

Piers Anthony is another favorite author of mine.  His books are a little bit out there, but they make interesting read, especially the Immortality series.  I also read some of his Xanth's novel and the Geodyssey series. 

Last but not least, David Eddings.  Edding started me reading on series that span multiple books, starting with the Belgariad, which I still think is excellent. Although lately, I've been having a different opinion about this particular author.  I am not sure I am a fan of his anymore since his books lately are not up to par with his earlier works.  I suggest reading Belgariad, Mallorean, Elenium, and Tamuli series and stop there.  The rest are ... uhm ... well, crappy, predictable and boring. Sad smile  I supposed I read too many Eddings at that point and so he seems to be repeating the same story over and over again.  Good gods help heroes beat bad gods.  Hero is pretty much invincible and blah blah blah.  Been there, done that. Don't feel I need to read more of these kind of stories.

I also picked up other authors from time to time in these genre, for example, Timothy Zahn wrote some excellent titles revolving around Star Wars universe, and I also found some other authors that are not quite to my taste like Terry Brook.  I found his book a bit bland and there was just too much description and narration and very little dialogue between the characters thus I found it quite boring (I'm talking about Sword of Shannara), well that kind of put me off from ever picking up his other books. 

I also read the DragonLance series by Margaret Weiss and Tracy Hickmann.  I supposed those are a classic when it comes to Dungeon and Dragon.  They were okay, but I think R.A. Salvatore's are much better :).

Well, don't just take my words for it, go give them a try, perhaps you'll agree or disagree with my opinion, but we'll never know if you don't try, yes?.  Happy reading.
Let me know if you find good fantasy / sci-fi books that are worth reading Smile

Next time, we'll discuss computer gaming Smile...