Generics Primer – Part 1

When generics were first released, the generic collections where the first place that I used them. They removed a lot of the boilerplate code when it came to creating strongly typed collections. In 1.x you would inherit from the base class of the type of collection you wanted, and then implement strongly typed versions of methods such as Add, Remove, Contains. An example of this can be found here. Thanks to generics you don’t need to create a MyClass1List and a MyClass2List you can simply instantiate a new List<MyClass1>() and new List<MyClass2> without needing to write the plumbing code to have this work.

When .Net 3.5 was released it included one of my favorite features in .Net, LINQ which is a set of extension methods that make extensive use of generics, allowing for removal of much of the boilerplate involved with searching collections.

In my next post I will talk about creating some simple generic classes and methods.

Getting imports working with dotless and CssBundles

I was watching Single Page Apps with HTML5, Web API, Knockout and jQuery by John Papa on pluralsight and one of the pieces was sending compiled less files down using the bundling.

Unfortunately this did not work while using @import because the current directory was set to my IIS Express directory. After searching most suggestions were to use Directory.SetCurrentDirectory but didn’t really like that solution so this is what I decided on:

Migrating to WordPress with URL Rewriting

Recently I switched from using SubText to WordPress as my blog engine. The reason for the switch was to get access to all of the plug ins available, I could have added the functionality, but unfortunately I find myself a bit time starved as of late.

In order to prevent all of my old permalinks links from breaking, while moving from a /year/month/day/postname format to simply having postname as the url, I am using IIS7’s URL Rewriting Module. It turned out to be quite simple to do this, and here are the entries that change the requests to the new Url Scheme:

<rule name="Aspx" enabled="false" stopProcessing="true">
<match url="archive/[0-9][0-9][0-9][0-9]/[0-9][0-9]/[0-9][0-9]/([A-Za-z0-9-_.]+).aspx" />
<conditions logicalGrouping="MatchAny" />
<action type="Redirect" url="{R:1}" />
<rule name="Rss" enabled="false" stopProcessing="true">
<match url="rss.aspx" />
<conditions logicalGrouping="MatchAny" />
<action type="Redirect" url="/feed" redirectType="Permanent" />

This has been working well, the only issue that I have run into so far is that categories in subtext were marked with numbers by default, and google’s crawler is finding them as broken links. I haven’t decided how to handle these links yet.

DotNetOpenAuth with AppDirectory removed

In my previous post I had talked about my decision to implement OpenId, and how DotNetOpenAuth worked well for this. In this post I will talk a little about the only issue that I ran into while doing this.

The root of this issue had to do with how my hosting is setup for sites that have low traffic. I host these sites on winhost which allows for an unlimited number of domain pointers. They also have the URL Rewrite module, so I can rewrite to enabling the site to be moved later when demand requires more horsepower without having to deal with the removal of the sub directory.

The problem that came from this setup was that DotNetOpenAuth determined that the releam was instead of, and returned from openid with to the sitedir/authenticate.  Andrew Arnott pointed me in the right direction pretty quick after my tweet. Here is what I ended up with to fix this, it is in 2 parts.

The first is making the request:

if (isInSubDir)
request = openid.CreateRequest(Request.Form["openid_identifier"], new Realm(""),
new Uri(""));
request = openid.CreateRequest(Request.Form["openid_identifier"]);

The second part is dealing with the response:

var isInSubDir = Request.ApplicationPath!="/";
IAuthenticationResponse response;
if (isInSubDir)
var absoluteUri = httpRequest.Url.AbsoluteUri;
var rawUrl = httpRequest.RawUrl;
absoluteUri = absoluteUri.Replace(Request.ApplicationPath, "");
rawUrl = rawUrl.Replace(Request.ApplicationPath, "");
var httpRequestInfo = new HttpRequestInfo(httpRequest.HttpMethod, new Uri(absoluteUri), rawUrl, headers, httpRequest.InputStream);
response = openid.GetResponse(httpRequestInfo); �
response = openid.GetResponse();

Open Id with DotNetOpenId

I recently integrated OpenId into a project that I am working on with my wife, WebQuest Builder in order to avoid the extra considerations related to storing user password.

Originally I had planned on using RPXNow in order to do this. But after reading about how realms worked, specifically that  Google gives a different identifier for each realm, I decided against this option. Because

while RPXNow does have support  for custom realms, instead of, it would cost $99/month in order to get this. And after my wife made a comment that it seemed almost like someone phishing for her account do to the in Googles OpenId form.

The other option that I had been considering had been DotNetOpenAuth which was very simple to integrate. It took about an hour to get it running in my development environment. I only had one issue when I pushed it live, which I will go into in a future post. For the OpenId selector I used Jarrett Vance’s Id selector for the Sign In.

After showing it to a few people I ended up making a few tweaks to the Id Selector. The first  chance that I made was to change it so that the OpenId checkbox did not show up, because a couple of the people I showed it to tried entering in their gmail address instead of Google’s OpenId Url. The other change I did was order them by which providers I thought they were most likely to be using, I hope the Microsoft gets their OpenId provider going soon so that I can integrate hotmail/live accounts into this.

ScriptControl question

As of late I have gotten a chance to use the ASP.Net AJAX extenders and script controls, and so far am really liking how they work, though it would be nice if adding the .js was a little cleaner then manually adding them to the assembly wether in the AssemblyInfo.cs or the controls cs file.

I have to say I really like the extender and script controls that come with the ASP.NET AJAX. They really are so much nicer to work with then building up Javascript strings in the CS file of the server control.

I do have a question about them though. One of the ScriptControls I made uses a webservice to pull data if the service name is set. At the moment I have it dynamically registering an JSON script service based webservice. Unfortunately I have found that this is not an optimal solution since the name of the Javascript object created by the ScriptService changes depending on the namespace and class name of the service.

I am sure that there is a better way to do this, but I am not exactly certain of it. Any suggestions or links would be appreciated.

Lazy list

I have been following Rob Conery’s posts on the MVC Storefront, and trying the repository/pipes-filters for data access that he has been using.

While trying out the implementation of a LazyList he was using, I had noticed that the example table was being joined onto the category table. At the time however, I really had not thought much of it, until I read MVC Storefront: Brainbender Intermission which got me thinking.

Admittedly, I don’t really have to much of a problem with it loading all of the examples for all the categories at one time at the moment. However, I figured it would be nice to have it work the way intended, and query the database for the examples in a category only when asked for.

I liked the idea of the LazyList, and since I was already using a Service class for all data access, along with setting up the category hierarchy I moved the creation of the LazyList of examples property into the the GetCategories method of the service class.

It seems that as long as the LazyList is created after the categories .ToList() call it properly works. So I ended up with this code:

            categories.ForEach(category =>
                category.Examples =
                    new LazyList
                        from e in repository.GetExamples()
                        where e.CategoryId == category.ID
                        select e);

                var subCategories = (from sub in categories
                                     where sub.ParentId == category.ID
                                     select sub).ToList();
                category.SubCategories = subCategories;

                subCategories.ForEach(c => c.Parent = category);



Technorati Tags:

Custom Rss Admin feeds

I fixed up the Rss Admin feeds so that modifying web.config (along with new handler classes) would not needed to add a new Admin Rss feed.

Also added a simple form to allow administrators to created their own. It is a bit limited, but adding additional options should not be to hard. Though those will have to wait till a later date.

On a side note, I found that if I had the option of returning the non-generic  base class, or a generic subclass it makes the code a lot more flexible if you return the non-generic base class if you do not have a need to have the generic type.



Technorati Tags:

Login via Usercontrol View + jQuery

Since administration was the next part I wanted to work on.

I decided that for the moment I just want a little login for in the upper corner

I decided to put the login screen view logic into a user control, and added the following user control named Login.ascx and placed it into the Shared

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>

<%if(!Page.User.Identity.IsAuthenticated) {%>
    <form action="/Home/Login" method="post" id="LoginForm">
        <span id="EmailLabel">Username:</span><br />
        <%=Html.TextBox("Username")%><br />
        <span id="PasswordLabel">Password:</span><br />
        <%=Html.Password("Password")%><br />
         <span id="Error">
            <%=ViewData.ContainsDataItem("Message") ? ViewData["Message"] + 
               "<BR />" : ""%>
        <%=Html.SubmitButton("Submit", "Login")%>
<%}else {%>
        <span>Not <%=Page.User.Identity.Name %><br />    
        <%=Html.ActionLink<DevExamples.Controllers.HomeController>(c => c.Logout()
            , "Logout", new { id = "LogoutLink" })%></span>

<%} %>


And added the user control to the masterpage using

<div id="Login"><%=Html.RenderUserControl("~/Views/Shared/Login.ascx") %><div>


I was going to use

using (Html.Form<DevExamples.Controllers.HomeController>(c=>c.Login()
   ,,new {id="LoginForm"}))


to create the form (because it is a lot cooler), but couldn’t get the html attributes to work and was more interested in getting the dynamic stuff working then looking at the code for the extension method in the MVCToolKit, in other words being lazy.


I thought about putting the authentication checking logic into the controller. But handling it this way made it a bit simpler, and more self contained, so until I find a compelling enough reason I will be leaving it this way.

After I had the user control showing up, I decided to hook up the actual authentication. I decided to go with forms authentication, and set it up using the button in the solution explorer.

Next it was time to create the login and logout controller actions, which I decided would best fit in the HomeController, At first I had thought to create two separate views, one for when logged in and one for logged out, then remembered Phil Haack, at least I think it was him, something about being able to use user controls in the RenderView method of the controller.

I ended up with the following two controller actions:

public void Login()
    if (!ControllerContext.HttpContext.User.Identity.IsAuthenticated)
        if (Request.RequestType == "POST")
            string userName = Request.Form["Username"];
            string password = Request.Form["Password"];

            if (Membership.ValidateUser(userName, password))
                FormsAuthentication.SetAuthCookie(userName, true);
                //Set cookie and redirect
                ViewData.Add("Message", "Invalid Username/Password");
public void Logout()


Since it was allowing me to just render out the user control, I decided there was no point to refreshing the whole page, so decided to use a AJAXish way of doing it. So I decided it was time to pick a javascript library. And since Phil had provided a link to  Using with ASP.NET MVC by Chad Myers,I decided to go with jQuery for this (that and it seemed to fit better).

After a bit of reading through their tutorials I added this to the header section of the master page.

<script src="../../Content/jquery.js" type="text/javascript"></script>
<script src="../../Content/jquery.form.js" type="text/javascript"></script>
<script type="text/javascript">
    var readyFuncs = function() { 
        $('#LoginForm').ajaxForm(function(result) { 
            return false;

The only real snag I had run into with this was that each time the Login div was refreshed I had to reregister the events.

.Net based SVN client library

As an exercise to figure out socket programming I have been messing around with creating an SVN client library to use with, well actually a generic SC client library that would allow me to change what repository site I was working against, SVN just seemed like the simplest of them at the moment.

However, after thinking about it, I think it would be better to use one that is already built if possible. I just have not been able to find a pure .Net client library. It is also seems rare for a source control library to work without a working folder, which is somewhat limiting when I want to check the propagation of examples using this method on the same machine.

Though I think it would be interesting to write a LINQ to Source provider, as a way to learn expression trees better. Plus it would be nice to be able to not only easily switch hosting providers (the reason I am looking for a pure .Net library) but also to have a standard syntax to allow me to easily switch from SVN to SourceGear’s Vault (which I use for my personal development projects) to TFS (which we use at work) as the storage system for the examples.

Though SvnBridge could possibly help with that too.

Technorati Tags: ,,,