Monthly Archives: February 2012

HOW TO: Use Events From An Inherited Class

When designing objects I will always think that not only will I be coding functionality in the object, but potentially someone else could be extending this functionality.  Almost every time I have written an object I have come back to it to expand it out to help usability.  One big subject that I have struggled a little with is how to expose events to descendant classes.  This becomes a point of focus when working in an Agile environment, because the requirements can shift and change and you want to be able to shift and change with them.  Designing a base class like a persistent Person object requires that you release as much control to the descendant while protecting any logic that is completely necessary.

Let’s take the following example of a person that notifies applications when today is their birthday:

VB.NET

Public Class Person

    Public BirthDate As Date
    Public Sub DateChanged(ByVal NewDate As Date)
        If NewDate = BirthDate Then
            RaiseEvent ItsMyBirthday()
        End If
    End Sub
    Public Event ItsMyBirthday()
End Class

C#

    public class Person
    {
        public DateTime BirthDate;
        public void DateChanged(DateTime NewDate)
        {
            if (NewDate == BirthDate)
                ItsMyBirthday(this,new EventArgs());
        }
        public event EventHandler ItsMyBirthday;
    }

You cannot implicitly call RaiseEvent for a base class event, so to work around this issue we create a method in the base that as always should be overridable.  Typically I will call this On<EventName>.  In this case I would call it OnBirthday and have the base method raise the event.  This change would look something like this:

VB.NET

    Public Overridable Sub OnBirthday()
        RaiseEvent ItsMyBirthday()
    End Sub

C#

    public void OnBirthday()
    {
        ItsMyBirthday(this, new EventArgs());
    }

Now you can call OnBirthday in your base class if you wanted to have two birthdays and inform your application of such.  Happy coding!

Primary Keys in SQL (Guid or Integer?)

Primary keys in SQL have come up quite a few times in my career so far. Let’s start by going back to the beginning with what a key really is and how it is used.

Each concept in programming typically starts with a record or a target. In the case of bank applications this would be an account, or sales would be a customer or an order. Regardless there is always some sort of unique object in coding that needs to be identified, tinkered with and some task completed. For a customer you would call them by their full name, Mike Calvert as an example. Unfortunately there are a lot of people named Mike Calvert in the world, so we need to learn to identify the specific Mike Calvert we are talking to.

From here a key was identified by using some sort of numbering scheme. Dynamics GP uses a limited alphanumeric scheme which you can use to assign a number such as MIKECALVERT01. This works until you run out of letters or you hit the maximum combinations and start coming up with one offs. The next step in the equation was to jump to auto incrementing integers, so Mike Calvert becomes 1, Mike Calvert 2 becomes 2, Jason Mills becomes 3, Howard Roberts becomes 4 etc. Everything was solved in the world because we now had an endless number that works forever. Moving into actual SQL syntax, you would have an issue with connecting up data links. Lets say you had to insert 50,000 records into this customer table, and you had a relationship table that referenced these people.

You now have to insert 50,000 records into the table, and then determine which of the 50,000 got assigned to a customer record because that record ID is generated when you insert it into the database. There are some tips and tricks around it but it is very messy. In a nut shell, if I wanted to find out what the ID was of Mike Calvert after I inserted 50,000 people into the database I would have to do a select to find Mike Calvert, and we run into the same issue we ran into before where there may be more than one Mike Calvert. At this point someone at Microsoft (thankfully) decided to put a Guid into play. Guid’s are by far the best key choice that I have come across as they provide three awesome things that keys need. The first and biggest requirement is being unique. Each Guid is unique no matter what table or database. If I put a customer record into a table with a Guid, I know that I can find that same customer record using that Guid from anywhere, without having to worry if that Guid will show up anywhere. The next big advantage is indexing. Indexing a guid is very efficient as they are the same length of characters, the same types of digits and are always unique. Finally, Guids can be generated prior to insert.

Generating a key prior to insert is a major advantage, as you can wrap up your 50,000 inserts into a single statement as well as the relationship. .NET provides a function called System.Guid.NewGuid that returns back a guid that you can use as a unique identifier in your inserts. Let us say that we generated our customer Mike Calvert and we created his guid. Any additional tables that required a relationship to Mike Calvert would already have this guid prior to inserting Mike Calvert, so I can create Mike Calvert and his sales histories and payment histories and insert it in one transaction instead of making multiple calls to fetch IDs. Fun stuff eh?

HOW TO: Use Facebook Registration In .NET

As we all know Facebook is too big of a monster to not consider when developing our web applications.  Time and time again I have received the request to add a Facebook registration process to a store or blog that allows users to “Connect With Facebook” and remember their settings.  Luckily, Facebook has begun alpha support of a C# library which lets us have some fun with JSON.  Facebook uses a signed response method which encrypts information passed back and forth using your application secret and ID.  Here is some sample code for a page that would call to the Facebook API for registration/logging in.

HTML

<iframe src="https://www.facebook.com/plugins/registration.php?
client_id=xxxx&
redirect_uri=http://localhost/fbtest/completed.aspx&
fields=name,first_name,last_name,birthday,gender,location"
scrolling="auto"
frameborder="no"
style="border:none"
allowTransparency="true"
width="100%"
height="330">
</iframe>

When using this approach Facebook will pass you back to the page you specify in the redirect_url with a Form field setup called signed_request.  The nice thing about this is you create a page that accepts this call back and handles the Form field appropriate to login or register a user.  The C# library that Facebook has started working on exposes some methods which allow you to interpret this response and get some data. Here is an example on how to retrieve the response and fetch some fields from it:

VB.NET

Imports Newtonsoft.Json.Linq
'...
Partial Class FacebookRegistrationPageHandler
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        Dim fbaFacebookApp As New Facebook.FacebookApp
        Dim fsrSignedRequest As Facebook.FacebookSignedRequest
        Dim jobJSONObject As JObject

        fbaFacebookApp.AppId = "xxxx"
        fbaFacebookApp.AppSecret = "xxxx"
        fsrSignedRequest = fbaFacebookApp.SignedRequest

        jobJSONObject = JObject.Parse(fsrSignedRequest.Dictionary("registration"))
        Dim strReturnedName = CType(jobJSONObject("name"), Newtonsoft.Json.Linq.JValue).Value

    End Sub
End Class

C#

using Newtonsoft.Json.Linq;
// ...
Partial;
class FacebookRegistrationPageHandler : System.Web.UI.Page {

    protected void Page_Load(object sender, EventArgs e) {
        Facebook.FacebookApp fbaFacebookApp = new Facebook.FacebookApp();
        Facebook.FacebookSignedRequest fsrSignedRequest;
        JObject jobJSONObject;
        fbaFacebookApp.AppId = "xxxx";
        fbaFacebookApp.AppSecret = "xxxx";
        fsrSignedRequest = fbaFacebookApp.SignedRequest;
        jobJSONObject = JObject.Parse(fsrSignedRequest.Dictionary("registration"));
        object strReturnedName = ((Newtonsoft.Json.Linq.JValue)(jobJSONObject["name"])).Value;
    }
}

Microsoft Web Matrix

I’ve been using the Microsoft Web Matrix more and more lately to install CMS and eCommerce solutions.  This application is a simply install which has links on most popular Microsoft style web products allowing you to directly install and setup your IIS instance without any fuss or mess.

The Web Matrix also let’s you create templates based on sites, or use existing templates.  I have also agreed with using templates as bases, because a good template will give you the proper wire frame for your site and you simply need to tweak styles to get what you need.  Finally, the Web Matrix sets up your database for whatever web application you install, and also has plenty of options for automatically tuning your IIS instance.  Definitely a great tool to have in your tool shed.

Take a look at this video for some information about the Web Matrix:

[tube]fxCEcPxUbYA[/tube]

Here are some popular sites that use the Web Matrix for installation:

DotNetNuke

Umbraco