Thursday, August 13, 2009

Secure Twitter Pic Part 1

Back Story
So after having our baby early, I wanted a convenient way to share pictures and updates to the family and I thought what better way than Twitter. So we set our baby up with a Twitter account and set it to protected. I found the best way to post pictures is through TwitPic, but found that when people post comments through TwitPic, the links show up on their Twitter page. Obviously this defeats the point of making her account protected since the main thing we wanted to protect was the pictures. We also know that it is extremely difficult to protect pictures on the Web, but we like to make it somewhat difficult for weirdos.

My solution to the problem is to write a small app so I can post a pic and a status from my iPhone and have it somewhat secure. I'm going to use Twitterizer as my C# Twitter framework, SQL 2008, and ASP.NET MVC. The flow will go like this...

if not authenticated to Twitter
authenticate

if a follower of the baby
show pic and allow comments
(comments will post to the viewer's Twitter like this: "@baby STP:1234 comment here")
Notice there is not a link to the picture, but still a reference so the baby knows which pic they're talking about
else
deny access to pic

As of right now, I have two services, ITwitterService & IUploadService, which look like this:

public interface ITwitterService
{
void Update(string status);
bool IsAuthenticated { get; }
}
public interface IUploadService
{
void Upload(HttpRequestBase request);
}
Here's my implementation:

public class
TwitterService : ITwitterService
{
private readonly Twitter _twitter;
private readonly string _username;
private readonly string _password;

public TwitterService(string username, string password) : this(username, password, null) {}

public TwitterService(string username, string password, string source)
{
_username = username;
_password = password;
if (string.IsNullOrEmpty(source))
_twitter = new Twitter(_username, _password);
else
_twitter = new Twitter(_username, _password, source);
}

public void Update(string status)
{
if (!string.IsNullOrEmpty(status))
_twitter.Status.Update(status);
}

public bool IsAllowed(string username)
{
var paras = new TwitterParameters();
paras.Add(TwitterParameterNames.ScreenName, username);
return _twitter.User.Followers(paras).Count > 0;
}

public bool IsAuthenticated
{
get { return Twitter.VerifyCredentials(_username, _password); }
}
}
public class UploadService : IUploadService
{
public void Upload(HttpRequestBase request)
{
   foreach (string file in request.Files)
{
var hpf = request.Files[file];
if (hpf.ContentLength == 0)
continue;
var savedFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Path.GetFileName(hpf.FileName));
hpf.SaveAs(savedFileName);
}
}
}
I ended up creating a helper service that takes the Twitter & Upload interfaces to do the upload and post at once…pretty simple.

public class
STPService
{
   private readonly ITwitterService _twitterservice;
private readonly IUploadService _uploadservice;
public STPService(ITwitterService twitterService, IUploadService uploadService)
{
_twitterservice = twitterService;
_uploadservice = uploadService;
}

public void UploadAndPost(HttpRequestBase request, string status)
{
_uploadservice.Upload(request);
_twitterservice.Update(status);
}
}
Here are my integration tests:

[TestFixture]
public class
TwitterTests
{
[Test]
public voidIsAuthenticated_user_is_authenticated_returns_false()
{
var twit = newTwitterService("baby", "badpassword");

Assert.IsFalse(twit.IsAuthenticated);
}

[Test]
public voidIsAuthenticated_user_is_authenticated_returns_true()
{
var twit = newTwitterService("baby", "password");
Assert.IsTrue(twit.IsAuthenticated);
}

[Test]
public voidIsAllowed_user_is_not_allowed_returns_false()
{
var twit = newTwitterService("baby", password");
Assert.IsFalse(twit.IsAllowed("test"));
}

[Test]
public voidIsAllowed_user_is_allowed_returns_true()
{
var twit = newTwitterService("baby", "password");
Assert.IsTrue(twit.IsAllowed("derans"));
}
}

Okay so that’s my Core & Impl now for the MVC stuff…my first real app using it…so let’s see!

I started with the default ASP.NET MVC stuff and just started modifying it. I added a method to the HomeController like this:

[AcceptVerbs(HttpVerbs.Post)]
publicActionResult Index(stringstatus)
{
var stpService = DI.CreateSTPService();
stpService.UploadAndPost(Request, status);

ViewData["UploadMessage"] = "Posted.";
returnView();
}

My Index.aspx page looks like this:

<%using(Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{ %>

<p><%=Html.Label("file", "Picture to Upload:") %><br />
<%=Html.File("file") %></p>

<
p><%=Html.Label("status", "Status:") %><br />
<%=Html.TextArea("status", "", 5, 30, null) %></p>

<
input type="submit" name="submit" value="Send" />
<%=Html.Encode(ViewData["UploadMessage"])%>

<%
} %>
I added a couple HTML Helper Extension methods in a helper file.

public static class
HtmlExtensions
{
public static stringLabel(thisHtmlHelper html, stringtarget, stringtext)
{

returnString.Format("<label for=\"{0}\">{1}</label>", target, text);
}

public static stringFile(thisHtmlHelper html, stringname)
{
returnString.Format("<input type=\"file\" name=\"{0}\" id=\"{0}\" />", name);
}
}

That’s all I got for now…as always, let me know if there is anywhere I can improve or if you have any comments. Thanks!

kick it on DotNetKicks.com

Wednesday, July 22, 2009

LINQ to SQL or NHibernate

So I’ve been trying to figure out which direction I wanted my team to go in as far as O/RMs go and I think I’ve decided. I’ve heard the only good things about Entity Framework are the portions taken from the LINQ to SQL team. Therefore, I spent some time playing with LINQ to SQL and definitely think it’s a great tool for quick and dirty projects. However, after spending a few days and actually using NHibernate in a major project…I love it. So far, we haven’t come across anything that it can’t do and after hearing some stories indirectly from Jeffrey Palermo I’m pretty sure we won’t. So on to the example.

The application I was needing to build was a simple information request form and I used LINQ to SQL first and wanted to plug in a NHibernate version later. Kind of like the Rob Conery & Jimmy Bogard challenge on the MVC Storefront.

Here’s my Core project: (Really small I know...needed something to get the point across)

image

I won’t go into all the details on the implementation, but the main thing I want to show is the difference in mapping and implementation of the repository. If you don’t know how to configure NHibernate, I recommend the NHibernate in Action book. As for LINQ to SQL, create a DBML and drag some tables over…DONE.

First I’ll show a few methods of IRequestRepository implemented with NHibernate and then the LINQ to SQL version.

public Core.Model.InformationRequest GetById(Guid id)
{
using (ISession session = NHibernateHelper.OpenSession())
return session.Get<Core.Model.InformationRequest>(id);
}
public IList<Core.Model.InformationRequest> GetAll()
{
using (ISession session = NHibernateHelper.OpenSession())
{
var records = session
.CreateCriteria(typeof(Core.Model.InformationRequest))
.List<Core.Model.InformationRequest>();
return records;
}
}

public IList<Core.Model.InformationRequest> GetAllCompleted()
{
using (ISession session = NHibernateHelper.OpenSession())
{
return session
.CreateQuery("from InformationRequest WHERE IsCompleted='true'")
.List<Core.Model.InformationRequest>();
}
}
public void Save(Core.Model.InformationRequest newRequest)
{
using (ISession session = NHibernateHelper.OpenSession())
using (ITransaction transaction = session.BeginTransaction())
{
session.Save(newRequest);
transaction.Commit();
}
}
Obviously I’m still learning NHibernate because we haven’t encapsulated anything or really figured out the best way to refactor it.

Here is the implementation of the same methods using LINQ to SQL.

image

public Core.Model.InformationRequest GetById(Guid id)
{
return dc.GetById(id);
}

public IList<Core.Model.InformationRequest> GetAll()
{
return dc.GetAll()
.ToList();
}

public IList<Core.Model.InformationRequest> GetAllCompleted()
{
return dc.GetAll()
.WithCompletionStatus(true)
.ToList();
}
public void Save(Core.Model.InformationRequest request)
{
using (var db = new OPIDataContext(_connstring))
{
var newrequest = RequestMap.GetDbRequestFrom(request);
db.InformationRequests.InsertOnSubmit(newrequest);

db.SubmitChanges();
}
}
With LINQ to SQL, I used a few filters and some mapping, but I’ll show those once I’ve shown the mapping file for NHibernate.
<?xml version="1.0" encoding="utf-8" ?>
<
hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
namespace="TPIAR.Core.Model"
assembly="TPIAR.Core">

<
class name="InformationRequest" table="[opi].[InformationRequest]">
<
id name="Id" column="RequestId">
<
generator class="guid.comb" />
</
id>
<
component class="Sample.Core.Model.Common.PersonName,Sample" name="Name">
<
property name="FirstName"/>
<
property name="LastName"/>
</
component>
<
property name="CompanyName" />
<
component class="Sample.Core.Model.Common.Address,Sample" name="Address">
<
property column="Address" name="StreetLine1"/>
<
property name="City"/>
<
property name="State"/>
<
property name="PostalCode"/>
</
component>
<
property name="TelephoneNumber"/>
<
property name="FaxNumber"/>
<
property name="EmailAddress"/>
<
property name="RequestSummary"/>
<
property name="RequestDate"/>
<
property name="CompletionDate"/>
<
property name="IsCompleted"/>
</
class>
</
hibernate-mapping>
With NHibernate, that’s it! Really easy once you know the syntax. Also, as a general rule, I like to write things from scratch when I’m learning so I fully understand what’s going on. So I won’t be using CodeSmith or some other similar tool.

Now for LINQ to SQL:
internal static InformationRequest GetById(this OPIDataContext dataContext, Guid Id)
{
var r = Enumerable.SingleOrDefault(dataContext.InformationRequests, x => x.RequestId == Id);

return new InformationRequest
{
Id = r.RequestId,
Name = new PersonName(r.FirstName, r.LastName),
CompanyName = r.CompanyName,
Address = new Address{City = r.City, PostalCode = r.PostalCode, State = r.State, StreetLine1 = r.Address},
TelephoneNumber = r.TelephoneNumber,
FaxNumber = r.FaxNumber,
EmailAddress = r.EmailAddress,
RequestSummary = r.RequestSummary,
RequestDate = r.RequestDate,
CompletionDate = r.CompletionDate,
IsCompleted = r.IsCompleted
};
}

internal static IQueryable<InformationRequest> GetAll(this OPIDataContext dataContext)
{
var requests = from r in dataContext.InformationRequests
select new InformationRequest
{
Id = r.RequestId,
Name = new PersonName(r.FirstName, r.LastName),
CompanyName = r.CompanyName,
Address =
new Address
{
City = r.City,
PostalCode = r.PostalCode,
State = r.State,
StreetLine1 = r.Address
},
TelephoneNumber = r.TelephoneNumber,
FaxNumber = r.FaxNumber,
EmailAddress = r.EmailAddress,
RequestSummary = r.RequestSummary,
RequestDate = r.RequestDate,
CompletionDate = r.CompletionDate,
IsCompleted = r.IsCompleted
};

return requests;
}

internal static DataAccess.InformationRequest GetDbRequestFrom(InformationRequest request)
{
var ir = new DataAccess.InformationRequest
{
RequestId = (request.Id == new Guid("99999999-9999-9999-9999-999999999999") ? Guid.NewGuid() : request.Id),
Address = request.Address.StreetLine1,
City = request.Address.City,
CompanyName = request.CompanyName,
CompletionDate = request.CompletionDate,
EmailAddress = request.EmailAddress,
FaxNumber = request.FaxNumber,
FirstName = request.Name.FirstName,
IsCompleted = request.IsCompleted,
LastName = request.Name.LastName,
PostalCode = request.Address.PostalCode,
RequestDate = request.RequestDate,
RequestSummary = request.RequestSummary,
State = request.Address.State,
TelephoneNumber = request.TelephoneNumber
};

return ir;
}
Here is the filter I used:
internal static IQueryable<InformationRequest> WithCompletionStatus(this IQueryable<InformationRequest> qry, bool status)
{
return qry
.Where(x => x.IsCompleted == status);
}
So there you go…LINQ to SQL & a NHibernate implementation that use exactly the same Core & UI. I also have a couple integration tests, which look like this:
[Test]
public void should_get_all_completed_using_linqtosql()
{
IRequestRepository rep = new SqlRequestRepository("connstring");
IList<InformationRequest> list = rep.GetAllCompleted();

Assert.AreEqual(2, list.Count);
}

[Test]
public void should_get_all_completed_using_nhibernate()
{
IRequestRepository rep = new NhRequestRepository();
IList<InformationRequest> list = rep.GetAllCompleted();

Assert.AreEqual(2, list.Count);
}
So I guess that’s about it. Please post comments or questions. I love feedback! Thanks!

kick it on DotNetKicks.com

Wednesday, June 03, 2009

Preload Images with JQuery

So I've been playing with JQuery for I don't remember how long and every time I revisit it, I think it's awesome all over again.

Anyhow, I thought I'd share a couple of scripts that I wrote that are pretty useful. The first one is a image preloader script that I wrote for my wife's photography site. I used the jQuery fade effect to display a set of images, but she wasn't happy because it would start fading even though the load wasn't complete. So in order to please my wife, I did a little research and found some sample scripts that ended up inspiring my script. I posted this script on the inspiration site as well after I did it back in January. So here we go...

    $(document).ready(function() {
vCycleImages = setInterval(
function() {
var bImgLoaded = true;
var images = $("#slideshow img");
for (var i = 0; i < images.length; i++) {
var img = images[i];
if (img.complete == false)
bImgLoaded =
false;
}
if (bImgLoaded) {
$(
"#slideshow").cycle({ delay: 1000, speed: 1000 });
clearInterval(vCycleImages);
}
},
1000);
});

So the way this script works is it sets an interval checking whether or not the images in the #slideshow1 div have completed and flags a bool on way or the other. Then the script checks if the flag is true. If so, then I start the cycle and clear the internal. Pretty simple stuff. The other sample script I have is for resizing a textbox horizontally while typing in it. So here we go again...

    $(document).ready(function() {
$(
".rtb").keypress(function() {
$(
this).width((this.value.length * 9));
this.value = this.value;
});
});

This script works by getting all the textboxes with a class of rtb and then setting the width to the length * 9 on each key stroke. The reason I set the value = value is so that the text starts over and you can see where you started.


Well, that's all I have for now. I'm planning on posting some test cases in my next entry. I've been spending most of my time lately trying to improve my management skills, so my play time with coding has been limited the past couple weeks. Til next time...


As always, please leave your comments if you like or hate the post. Thanks!

kick it on DotNetKicks.com

Saturday, May 09, 2009

LINQ to SQL Mapping…Saving

Okay, so I made a new Save method on my repository like so:

public interface ISchoolRepository
{
void Save(School school); //School of my model not the db school object
School GetSchoolById(int schoolId);
IQueryable<School> GetAll();
IQueryable<Student> GetEnrolledStudentsBy(int schoolId);
}

So then I implemented the new Save method like this:

public void Save(Core.Model.School school)
{
using (var db = new LearningDataContext())
{
var currentSchool = SchoolMap.GetDbSchoolFrom(school);
var originalSchool = dc.Schools.SingleOrDefault(x => x.SchoolId == school.Id);
     if (originalSchool == null)
db.Schools.InsertOnSubmit(currentSchool);
else
db.Schools.Attach(currentSchool, originalSchool);

db.SubmitChanges();
}
}

You should notice two things about the above method. One is that I have a static method called GetDbSchoolFrom(Core.Model.School school), which maps my model school to the db school. The other being that I’m using two datacontexts. One of them is defined on the class, dc, like in this post and the other is local to the method, db. So I still have my db/linq to sql objects as internal, which was one of my main goals and I feel pretty comfortable with this setup and maintainability.

Here is the GetDbSchoolFrom method:
internal static DataAccess.Impl.School GetDbSchoolFrom(School school)
{
var s = new DataAccess.Impl.School();
s.ContactNumber = school.ContactNumber;
s.FullName = school.FullName;
s.SchoolId = school.Id;
s.ShortName = school.ShortName;
s.CountyId = school.County.Id;
return s;
}
On another project, I went ahead and made a lot of DB changes so I could really test my model dependency on the db schema. I was happy to say that I only had to touch my mapper classes. Everything else remained the same.

As always, please make any comments you feel necessary and definitely let me know if you find any holes or issues with my code. Thanks!

Thank you Jimmy Bogard for telling me about the Windows Live Writer from Visual Studio plugin.


kick it on DotNetKicks.com

Tuesday, April 28, 2009

LINQ to SQL Mapping...I think it could work

This coding sample was inspired by Rob Conery's ASP.NET MVC Storefront videos. So here are the reasons I decided to go this route rather than NHibernate for this project.

1. I can always change it...the beauty of programming to interfaces
2. LINQ to SQL is crazy easy...and yes I've heard...it's dead, but just not being supported
3. It's something different that I haven't really seen implemented successfully
4. I'm curious to see if my method strikes up any other new ideas in the community

So first off I create my base model, which looks like this:

Next I created my LINQ to SQL, which looks like this: ( of course this is assuming I've already written my tests :)


So now I create an ISchoolRepository like this:

public interface ISchoolRepository
{
School GetSchoolById(int schoolId);
IQueryable<school> GetAll();
IQueryable<student> GetEnrolledStudentsBy(int schoolId);
}

Okay, so now we're on to the fun stuff...the maybe innovative? I'm not sure, but I hope. Now be fair warned that I did some SQL profiling on this, but not a whole lot and I plan on doing more because I'm big on performance and not having a lot of connections. Now if anyone sees immediate holes or concerns, please let me know. The newest thing I added was instead of making my mappers static classes, I made them extension methods on the datacontext...I thought it made more sense that way. Okay, let's continue...

So here is my implementation of the ISchoolRepository:

public class SqlSchoolRepository : ISchoolRepository, IDisposable
{
private readonly LearningDataContext dc;
public SqlSchoolRepository()
{
dc = new LearningDataContext();
}

public Core.Model.School GetSchoolById(int schoolId)
{
return dc.GetSchoolById(schoolId); //EXTENSION METHOD
}

public IQueryable<Core.Model.School> GetAll()
{
return dc.GetAllSchools(); //EXTENSION METHOD
}

public IQueryable<Core.Model.School> GetEnrolledStudentsBy(int schoolId)
{
return dc.GetAllStudents() //EXTENSION METHOD
.WhereIsEnrolled(true) //FILTER
.WithSchoolId(schoolId);//FILTER
}

public void Dispose()
{
dc.Dispose();
}
}
Now you see how I have the filters added on too like Rob did in his videos? I think the filters are very cool! Mainly for the readability. Okay, so here are my extension methods on the datacontext:

internal static class SchoolMap
{
internal static School GetSchoolById(this LearningDataContext dataContext, int schoolId)
{
var s = dataContext.Schools.SingleOrDefault(x => x.SchoolId == schoolId);

return new School()
{
ContactNumber = s.ContactNumber,
County = s.LookupCounty.FullName,
FullName = s.FullName,
ShortName = s.ShortName
};
}

internal static IQueryable<School> GetAllSchools(this LearningDataContext dataContext)
{
var schools = from s in dataContext.Schools
orderby s.FullName
select new School()
{
ContactNumber = s.ContactNumber,
County = s.LookupCounty.FullName,
FullName = s.FullName,
ShortName = s.ShortName
};

return schools;
}
}
One thing you should notice is that the mapping is EXACTLY the same on the GetSchoolById & GetAllSchools...unfortunately I have not found a way to get around that problem. I think that is a limitation of my LINQ knowledge more than an issue with this type of structure though. Hopefully a LINQ expert can help me out. Ideally it'd be something like this:

private static Core.Model.School getSchoolFrom(Impl.School sqlschool)
{
return new School()
{
ContactNumber = sqlschool.ContactNumber,
County =sqlschool.LookupCounty.FullName,
FullName = sqlschool.FullName,
ShortName = sqlschool.ShortName
};


Surely something like that is possible. Anyhow, now the StudentMap looks exactly the same with the exception of it being WAY longer. So you'd do the same thing as above for the student mapping and then you'd create these filters:

internal static class StudentFilters
{
internal static IQueryable<Student> WhereIsEnrolled(this IQueryable<Student> qry, bool enrolledStatus)
{
return qry
.Where(x => x.IsEnrolled == enrolledStatus);
}

internal static IQueryable<Student> WithSchoolId(this IQueryable<Student> qry, int schoolId)
{
return qry
.Where(x => x.HomeSchool.Id == schoolId);
}
}
Now I'm sure you'll ask what do I do about many to many and how am I saving and all that other jazz. The answer to the many to many is on a per case basis for instance, I'm loading the attendancedata with the student because it's an attendance application and just about every page that I use the student class I need the attendance data too. I do not load the contacts with the student because I don't always need them. So I created a GetAllContactsByStudentId method on my student repository to get that information. This is obviously not as flexible as NHibernate and will probably never replace it, but I do think it's good for small apps that don't require a lot of transactions.

You should also notice that I keep all my LINQ to SQL objects internal and really only use them in the mapping extension methods. I noticed that Rob was not able to keep his internal and I think that started making the storefront way more confusing than it should've been. I need to go download the latest version and see how it has come along. As for saving and what not I have not gotten to that point. The app I'm working on is mostly read-only, but there are a few items that require updating & saving and I'll post again when I get to that point.

So my UI only has access to the repositories & the model...that's it. Since that's true, it seems like it'd be really easy to completely switch out LINQ to SQL to NHibernate if I decided to go that route. Again, I don't think I'd recommend this method if you had a lot of read/writes and needed HIGH performance as in you only want to load certain fields when required, etc.

Anyhow, I thought this was pretty cool and thought I'd share. Once I setup how I'm going to save, I'll post it on here too. Thanks and please provide feedback!

kick it on DotNetKicks.com

Monday, April 27, 2009

What page am I on?

So it's been 4 years since my last post and obviously I was right about it not being addicting...at least for me it's not. Anyhow, this is my first post as a developer learning from peers or at least hoping to. I keep seeing all these posts about automapper, dependency injection, TDD, MVC, being agile, etc, etc.

Apparently I'm just not seeing the big picture or something because I can get behind a couple of the things mentioned above, but not everything.

I see the benefit of dependency injection and I believe I'm doing it with StructureMap. I have a web forms app that seems to be working with it, but a lot of people have made it look a lot more complicated than the way I'm using it. I'll give an example in a bit.

I see the benefit of TDD and again, I believe I'm doing it with NUnit & ReSharper. I have only really gotten into the unit tests and not so much into regression or integration testing. I even have a few tests that use Rhino.Mocks, but I'm not 100% sure they're setup right. They pass and fail when I want them to so I guess they're right. Again...example in a bit.

I definitely see the benefit of agile development and I REALLY like the idea of user stories instead of requirements. My team is about to start our first true agile project from start to finish and it's definitely going to be interesting. There are a few people on my team that aren't crazy about change and tend to do things because that's the way they're done.

Now automapper is one thing I'm not sure I'll benefit from yet. I think Jimmy Bogard is probably the best developer I know at the moment and I'm sure he created something great, but I don't see the benefit for me and my team right now. I'm pretty confident that I will eventually slap myself in the face for posting this just because I'm sure it is an awesome tool that I will one day see as VERY cool, but right now...I don't. Maybe it's because I work for a school district and our projects just aren't big enough to warrant this type of implementation. I don't know, but I'm confident that the community will shine some light.

MVC is something else that I will be behind eventually, but right now I'm too busy learning the agile approach to things. I can definitely see the benefit of MVC especially when it comes to TDD, but it's pretty much exactly like going from classic ASP to ASP.NET. Hopefully Jeffrey, Jimmy, and Ben's book, ASP.NET MVC in Action sheds a lot of light on the topic for my team and me. I bought the early edition and I really liked what I read primarily because they're doing things the right way and not concerned with whether or not you understand. Seems like that last statement could be taken as a bad thing, but it's really not. I'm tired of buying books that go over the same crap, but using common practices instead of recommended methods. For example, if you pick up ANY ASP.NET book, they ALL have the same exact stuff and not one that I own shows you the correct way to do any of it. Like the using statement for disposing of objects. Jimmy showed me that and I own at least 8 .NET books. Maybe I was just buying the wrong books, but they all seem the same to me.

Okay...let's get to the examples. Hopefully Jimmy reads this at some point and he can point me in the direction of how he does his code samples on his blog. I'm sure there is some tool he uses...I don't see him doing anything by hand.

So dependency injection...I watched most of Rob Conery's videos on MVC and I think he did a great job of getting the right people on his videos to help out. Although I'm pretty sure my least favorite video is the one with his boss on the AJAX stuff. I think it's video 14..some where around there.

So this is how I handled my dependency injection using web forms:

First thing I did was created a static Bootstrapper class in the App_Code and it looks like this:

public static class Bootstrapper
{
public static void BootStrapStructureMap()
{
ObjectFactory.Initialize(x => x.AddRegistry(new SampleRegistry()));
}
}

The SampleRegistry is a class that inherits from StructureMap's Registry and it looks like this:

public class SampleRegistry : Registry
{
public SampleRegistry()
{
ForRequestedType<ISampleRepository>()
.TheDefaultIsConcreteType<SqlSampleRepository>();
}
}


So once I created my Registry class and static Bootstrapper, I throw it in the Application_Start of the global.asax, which looks like this:

void Application_Start(object sender, EventArgs e)
{
Bootstrapper.BootStrapStructureMap();
}


I think the syntax for StructureMap's GetInstance method is ugly and I didn't want to depend on them not changing that syntax, so I created a helper method that looks like this:

public class DI
{
public static ISampleRepository CreateSampleRepository()
{
return ObjectFactory.GetInstance<ISampleRepository>();
}
}


Now I can create my IndependentPage that has a protected field for my repository like this:

public class IndependentPage : Page
{
protected ISampleRepository samplerepository = DI.CreateSampleRepository();
}


And now I can use it in any page that inherits IndependentPage like so...

public partial class _Default : IndependentPage
{
protected void Page_Load(object sender, EventArgs e)
{
}

protected void GetAllOfSomething(object sender, EventArgs e)
{
gvList.DataSource = samplerepository.GetAll();
gvList.DataBind();
}
}


I'll show my example of my use of Rhino.Mocks in another post...this one has gotten WAY longer than I expected. So please give me some feedback. I'm really curious to see where I'm at in the community...newb...okay I guess...decent...good...great...who cares

kick it on DotNetKicks.com

Wednesday, November 23, 2005

I've setup this blog just so I can see what all the fuss is about. Personally...I think blogging is too impersonal to become addictive. I may be wrong...we'll see.

kick it on DotNetKicks.com

Related Posts Plugin for WordPress, Blogger...