I was looking to refactor my User Management class to use SubSonic to do all the DAL processing and I decided to take advantage of SubSonic's Partial Classes to extend
upon my "Account" ActiveRecord and merge my User Management class into the partial class. Note: I'm not referring to the AccountCollection object.
To be completely honest I'm not sure if this is the best way to handle this type of thing but thought it would be a fun exercise if nothing else.
SO let me share with you the code. Some of you may look at it and laugh, some may think it's really cool. Either way I'm throwing this out there so that whatever I learn as a result will help me (and hopefully you).
First lets take a look at the Account Partial Class that SubSonic generates:
[Serializable]
public partial class Account : ActiveRecord<Account>
{
...
}
Now there's nothing really important here other than the fact that it's a "Partial Class." So moving on let's see how we extend the class with one of our very own methods: LoginUser().
First we'll look at the code:
namespace DAL {
public partial class Account
{
public void LoginUser()
{
this.LastLogin = DateTime.Now;
this.LoginHash = new Guid().ToString();
HttpCookie c = new HttpCookie( "LoginCookie" );
c.Expires = DateTime.Now.AddDays( 5.0f );
c.Values.Add( "lastlogin", this.LastLogin );
c.Values.Add( "loginhash", this.LoginHash );
this.Save( "app-ext-user" );
HttpContext.Current.Response.Cookies.Add( c );
}
}
}
Now what's really important is how our class is defined. Notice that our class is also a "Partial Class" and it has the same class name as the SubSonic generated class. It's also important to note that our class is defined within the same namespace as the SubSonic generated code - leaving out the namespace will not give you access to the Account constructors. Note: My previous code was inheriting from DAL.Account which was not necessary as pointed out by Kevin in the Comments section.
Within our class definition we have created the LoginUser method. This is the method we're creating to extend the Account class - in other words the method did not exist in the original SubSonic generated Account class.
Within the LoginUser method we use "this" to access the object's properties. "this" is pretty cool because it refers to the currently instantiated Account object (including our newly added method). However you should note that using "this" is not required... you can access the properties, methods, etc... simply by their name. (Kevin - Comments)
So we set a few properties: LastLogin and LoginHash, create a cookie, then we use the Save method to save our changes and also add our newly created login cookie to the Cookies collection.
We've now extended the original SubSonic ActiveRecord class with our LoginUser() method. Give it a shot:
Account a = new Account(acctid);
if( a.IsLoaded ) a.LoginUser();
This is a great way to extend a single SubSonic ActiveRecord with well defined functionality.