UnityWeb

So my UnityWeb project (Unity for DI/IoC, MVP pattern, Fluent-Nhibernate) is nearing release stages. I posted the initial source copy on Assembla. I still have some work to do before I feel it’s closer to a final version and do my full write up on here about it. It will most likely become a multipart series for how much technology it encompasses. The majority of which I am no proven expert on but I have made efforts to learn as much as I could and went through alot of the growing pains trying to figure it out on my own and various blogs online. I feel my combined release should make the adaption of a UnityWeb type solution for your personal usage (or in your organization) much easier and quicker than rolling it from the ground up alone.

BloggingContext.ApplicationInstance.CompleteRequest();

Not getting intellisense with nHibernate

I was having problems with not being able to get intellisense to work right with the XML mapping files with nHibernate latest release. I searched around and from everything I was reading it was just drop the files in C:\Program Files\Microsoft Visual Studio 9.0\Xml\Schemas (for VS2008) and it’s good to go but it definitely was not working.

Eventually I stumbled upon .Net musings’s Intellisense for NHibernate 2.0 in Visual Studio 2008 , where the solution was to rename the files and append -2.2 after the file name and before the extension giving you nhibernate-mapping-2.2.xsd, nhibernate-configuration-2.2.xsd, nhibernate-generic-2.2.xsd.

BloggingContext.ApplicationInstance.CompleteRequest();

Working with QueryStrings, a critique and different solution.

Today I was reading DotNetKicks like I normally do and came across this article in the up and coming section, Parsing query string in ASP.NET safely. I felt the author had quite a bit of conflicting code in his blog post.

I was not a fan of having get properties that had associated private member backing fields but the backing fields weren’t even reliably used. The other issue I had was the fact the int? return property would default to 0 instead of null which overrides the point of using nullables, the last issue I had was the GET properties would cause conversion to be done on the RequestString every time.

private string QueryText
{
    get { return (string) (ViewState["ViewStateQueryText"] ??
 (ViewState["ViewStateQueryText"] = string.Empty)); }
    set { ViewState["ViewStateQueryText"] = value; }
}

private int? QueryId
{
    get { return (int?) (ViewState["ViewStateQueryId"]); }
    set { ViewState["ViewStateQueryText"] = value; }
}

private Guid? QueryGuid
{
    get { return (Guid?) (ViewState["ViewStateQueryGuid"]); }
    set { ViewState["ViewStateQueryGuid"] = value; }
}

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        QueryText = ConverQuerystringToString("QueryText");

        QueryId = ConverQuerystringToInt("QueryId");

        QueryGuid = ConvertQueryStringToGuid("QueryGuid");

        bool hasValue = QueryGuid.HasValue;
        hasValue = QueryId.HasValue;
    }
}

/// <summary>
/// Converts the query string to GUID.
/// </summary>
/// <param name="key">The key.</param>
/// <returns></returns>
private Guid? ConvertQueryStringToGuid(string key)
{
    if (string.IsNullOrEmpty(Request.QueryString[key]))
        return null;

    try
    {
        return new Guid(Request.QueryString[key]);
    }
    catch
    {
        return null;
    }
}

/// <summary>
/// Convers the querystring to string.
/// </summary>
/// <param name="key">The key.</param>
/// <returns></returns>
private string ConverQuerystringToString(string key)
{
    return Request.QueryString[key] ?? string.Empty;
}

/// <summary>
/// Convers the querystring to int.
/// </summary>
/// <param name="key">The key.</param>
/// <returns></returns>
private int? ConverQuerystringToInt(string key)
{
    int tmpParse;
    return int.TryParse(Request.QueryString[key], out tmpParse) ?
tmpParse : (int?) null;
}

This is how I handle reading the query string in my applications. If you’re wondering what’s going on inside the QueryText property I am doing 1 line lazy loading on the ViewState. This takes advantage of the lesser known fact that the assignment operator does not return void but actually returns itself which you can combine with the null coalescing operator to create 1 line lazy loading.

Let me know what you think about my practices. I love nullables for always having .HasValue and .GetValueOrDefault() to handle how I want to deal with defaults. I hate having to pick arbitrary values for default checks like -1 or 0 for ints etc.

UPDATE: 11/12

So I’m going to include a version for us on 3.5 where these methods are in an extension method over the querystring NameValueCollection.

public static class QueryStringExtensions
{
    /// <summary>
    /// Converts the query string to GUID.
    /// </summary>
    /// <param name="queryString">The query string.</param>
    /// <param name="key">The key.</param>
    /// <returns></returns>
    public static Guid? GetGuid(this NameValueCollection queryString, string key)
    {
        if (string.IsNullOrEmpty(queryString[key]))
            return null;

        try
        {
            return new Guid(queryString[key]);
        }
        catch
        {
            return null;
        }
    }

    /// <summary>
    /// Convers the querystring to string.
    /// </summary>
    /// <param name="queryString">The query string.</param>
    /// <param name="key">The key.</param>
    /// <returns></returns>
    public static string GetString(this NameValueCollection queryString, string key)
    {
        return queryString[key] ?? string.Empty;
    }

    /// <summary>
    /// Convers the querystring to int.
    /// </summary>
    /// <param name="queryString">The query string.</param>
    /// <param name="key">The key.</param>
    /// <returns></returns>
    public static int? GetInt(this NameValueCollection queryString, string key)
    {
        int tmpParse;
        return int.TryParse(queryString[key], out tmpParse) ?
tmpParse : (int?) null;
    }
}

Usage example (using same .aspx page as above)

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        QueryText = Request.QueryString.GetString("QueryText");

        QueryId = Request.QueryString.GetInt("QueryId");

        QueryGuid = Request.QueryString.GetGuid("QueryGuid");

        bool hasValue = QueryGuid.HasValue;
        hasValue = QueryId.HasValue;
    }
}

BloggingContext.ApplicationInstance.CompleteRequest();

kick it on DotNetKicks.com

Unity LifetimeManagers + ASP.NET

So recently I’ve really been looking into Unity and how to use it to handle IoC/DI for a future project of mine, I compeltely gave up on Web Client Software Factory (WCSF) something happened to that project where it just doesn’t work right anymore after having to deal with “Invalid owner for DynamicMethod” over and over again from ObjectBuilder(1.0 that’s in WCSF) I finally scrapped it and started looking at ways to use Unity to handle the MVP pattern instead.

This really had me scratching me on head on the implications of the page life cycle and correctly resolving instances, I’ve seen some examples around that go as far as creating HttpHandlers to intercept the BuildUp event to handle the injection which while I could go that route it definitely adds some complexity to the project. Which sadly I’ve learned especially when using new technology the code needs to be as simple as possible to avoid getting pushback from other developers but simple is good so I’d rather end up with a simple elegant solution vs a complex elegant solution.

Today I ran across a blog post (it’s a little old from May 08) regarding all of this Unity – lifetime management in a web application

I also did alot of referencing back and forth with the MSDN – Using Lifetime Managers

After doing some implemenation of all this I started to see why it makes sense to use the HttpModule to handle processing the build up. I used the HttpModule / Container wrapper extension method that Michael Puleio wrote on his blog Proof of Concept: a simple DI solution for ASP.NET WebForms.

Pretty soon I will be deploying a new solution to Assembla with links on here that will have an Unity driven DI model using the Model View Presenter (MVP) design pattern with a NHibernate back end (since LINQ-TO-SQL is on the death march) over the Microsoft Northwind db sample.

C# ASP.NET Response.Redirect Open Into New Window

UPDATED: 11/04/2008 (see bottom of post)

So I came across the day the desire to have a button open up a new window instead of just using an anchor tag, as usual I run the idea through google and mostly come back with responses saying it’s not possible that way, or to add javascript to the page to capture events. Not quite the solution I was looking for after doing some more searching I came across a javascript solution that would work but wasn’t elegant at all which led me to ponder on adapting it to be cleaner and this is what I came up with.

<asp:Button ID="btnNewEntry" runat="Server" CssClass="button" Text="New Entry"

OnClick="btnNewEntry_Click" OnClientClick="aspnetForm.target ='_blank';"/>

protected void btnNewEntry_Click(object sender, EventArgs e)
{
    Response.Redirect("New.aspx");
}

It even works using Server.Transfer. There you have it a simple unobtrusive solution to handle Response.Redirect into a new window without needing to add any javascript tags and only take advantage of the OnClientClick event on the button itself.

Update 10/22/2008:

I’d like to thank one of my commenters, Dan, for his solution for accessing the form inside a master page on the child page level.

Button1.OnClientClick=string.Format(”{0}.target=’_blank’;”,

 ((HtmlForm)Page.Master.FindControl(”form1″)).ClientID);

This code will dig down into the controls collection and find your form and allow you to get access to the client id so you can be sure you have proper naming of it for the javascript to function correctly. Make sure you replace “form1″ with whatever you have your parent form id=”name” set to inside your Master’s page markup.

Update 11/04/2008:

If you have multiple buttons on a single page and only want a specific button to launch into a new windows and want the rest to stay on the current form make sure you decorate your other buttons like

<asp:Button ID="btnStayOnPage" runat="Server" CssClass="button" Text="Stay here"

OnClick="btnStayOnPage_Click" OnClientClick="aspnetForm.target ='_self';"/>

protected void btnStayOnPage_Click(object sender, EventArgs e)
{
   //Do normal code for postback
}

BloggingContext.ApplicationInstance.CompleteRequest();

kick it on DotNetKicks.com