May 2009 - Posts

In my last post, two important issues are raised

  1. The justification of having server side components for jQuery UI.
  2. The style of syntax.

The intension of my last post was to get the feedback of the type of syntax the ASP.NET MVC developer prefers, so I did not mention anything on the server side side integration, this might be the reason why few people were unable to find the benefits of this server side support. In this post, I will try to show few simple examples of the server side integration, lets say that you are creating a Task submit form, you can use the Slider as completed percent field instead of regular input field, like the following:

View:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Task>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Slider Value Form Submit Example
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <% using(Html.BeginForm()){%>
        <fieldset>
            <legend>Submit Task</legend>
            <span style="color:Blue;font-weight:bold">
                <%= ViewData.Get<string>("successMessage") %>
            </span>
            <%= Html.ValidationSummary("Please correct the following errors:") %>
            <div>
                <label for="name">Name:</label>
            </div>
            <div style="margin-top:5px">
                <%= Html.TextBox("task.Name", null, new { style = "width:200px" })%>
            </div>
            <div style="margin-top:5px">
                <%= Html.ValidationMessage("task.Name")%>
            </div>
            <div style="margin-top:10px">
                Completed: <span id="completedPercent" style="color:Black"></span>%
            </div>
            <div style="margin-top:5px;width:200px">
                <% Html.jQuery().Slider()
                                .Name("task.Completed")
                                .UpdateElements("#completedPercent")
                                .Render(); %>
            </div>
            <div style="margin-top:5px">
                <%= Html.ValidationMessage("task.Completed")%>
            </div>
            <div style="margin-top:10px">
                <input type="submit" value="Submit"/>
            </div>
        </fieldset>
    <% }%>
</asp:Content>

Controller:

[AcceptVerbs(HttpVerbs.Get)]
public ActionResult FormSubmitWithValue()
{
    return View(new Task());
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult FormSubmitWithValue([Bind]Task task)
{
    if (string.IsNullOrEmpty(task.Name))
    {
        ModelState.AddModelError("task.Name", "Name cannot be blank.");
    }

    if (task.Completed <= 0)
    {
        ModelState.AddModelError("task.Completed", "Invalid task complete percent.");
    }

    if (ModelState.IsValid)
    {
        //Save here;
        ViewData.Set("successMessage", "Task saved successfully.");
    }

    return View(task);
}

[Live Version]

Check that (line 26- 29 in the above View) you are using the same kind of naming as you do in strongly typed view for regular input fields, you can use the slider for non-strongly typed view too.

In case of Slider is ranged, we can use the following:

View:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Slider Values Form Submit Example
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <% using(Html.BeginForm()){%>
        <fieldset>
            <legend>Submit Department</legend>
            <span style="color:Blue;font-weight:bold">
                <%= ViewData.Get<string>("successMessage") %>
            </span>
            <%= Html.ValidationSummary("Please correct the following errors:") %>
            <div>
                <label for="name">Name:</label>
            </div>
            <div style="margin-top:5px">
                <%= Html.TextBox("name", null, new { style = "width:200px" })%>
            </div>
            <div style="margin-top:5px">
                <%= Html.ValidationMessage("name") %>
            </div>
            <div style="margin-top:10px">
                Salary: $<span id="rangeFrom" style="color:Black"></span> - $<span id="rangeTo" style="color:Black"></span>
            </div>
            <div style="margin-top:5px;width:600px">
                <% Html.jQuery().Slider()
                                .Name("salary")
                                .Range(jQuerySliderRange.True)
                                .Values(1000, 2500)  //Initial value
                                .UpdateElements("#rangeFrom", "#rangeTo")
                                .Minimum(1000)
                                .Maximum(10000)
                                .Steps(500)
                                .Render(); %>
            </div>
            <div style="margin-top:5px">
                <%= Html.ValidationMessage("salary")%>
            </div>
            <div style="margin-top:10px">
                <input type="submit" value="Submit"/>
            </div>
        </fieldset>
    <% }%>
</asp:Content>

Controller:

[AcceptVerbs(HttpVerbs.Get)]
public ActionResult FormSubmitWithValues()
{
    return View();
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult FormSubmitWithValues(string name, IList<int> salary)
{
    if (string.IsNullOrEmpty(name))
    {
        ModelState.AddModelError("name", "Name cannot be blank.");
    }

    if (salary.Count != 2)
    {
        ModelState.AddModelError("salary", "Invalid salary range.");
    }

    if (salary.Count == 2)
    {
        if (salary[0] <= 1000)
        {
            ModelState.AddModelError("salary", "Salary minimum range should be greater than 1000.");
        }

        if (salary[1] <= 2500)
        {
            ModelState.AddModelError("salary", "Salary maximum range should be greater than 2500.");
        }
    }

    if (ModelState.IsValid)
    {
        //Save here;
        ViewData.Set("successMessage", "Department saved successfully.");
    }

    return View();
}

[Live Version]

Since the slider is a range slider, it will have an array of values, that is why the controllers accepts IList<int> for the slider. This will also work for strongly typed view.

You can also use the ProgressBar to auto retrieve the value directly from ViewData, for example,

View:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    ProgressBar Auto Retrieve Value Example
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <% Html.jQuery().ProgressBar()
                    .Name("myProgressBar")
                    .Render(); %>
</asp:Content>

Controller:

public ActionResult AutoRetrieve()
{
    ViewData["myProgressBar"] = 40;

    return View();
}

[Live Version]

As mentioned in the past that the goal of this component is to add some RAD support for the ASP.NET MVC Developers. For example, in the original jQuery UI both Slider and ProgressBar does not have any built-in support to show the value(s) in an associated html element(s), but it does have this support to attach any html elements to show the numeric value(s), check the UpdateElements method in the above (works on jQuery Selector), behind the scene it generates the necessary javascript codes to hook the events and update the elements, the same is true for the above slider form submit examples, it generates the required hidden input(s) to support form submit. It will not discourage you from writing javascript codes, instead it automates some common repetitive tasks. The next thing of my previous blog post was the benefits of server side generating the necessary html and javascript codes even when there is no integration of server side like the above slider or progressbar, to demonstrate it, I will first create a dynamic jQuery UI tab with raw html and javascripts, lets assume the tab items are disabled and selected based upon some condition.

Raw Html and JavaScript:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IList<DynamicTabContent>>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Tab Dynamic Item Example
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <% var disabledIndexes = new List<string>(); %>
    <% var selectedIndex = 0; %>
    <div id="tabs">
        <ul>
            <% for (var i = 0; i < Model.Count; i++) {%>
                <li><a href="#section-<%= i %>"><%= Html.Encode(Model[i].Header)%></a></li>
            <% }%>
        </ul>
        <% for (var i = 0; i < Model.Count; i++) {%>
            <% var dynamicContent = Model[i]; %>
            <div id="section-<%= i %>">
                <p><%= Html.Encode(dynamicContent.Content) %></p>
            </div>
            <% if (dynamicContent.IsDisabled)
               {
                   disabledIndexes.Add(i.ToString());
               }
               //The last selected will win
               if (dynamicContent.IsSelected && (i > selectedIndex))
               {
                   selectedIndex = i;
               }
            %>
        <% }%>
    </div>
    <script type="text/javascript">
        $(document).ready(function(){
            $('#tabs').tabs({
                                selected : <%= selectedIndex %>,
                                disabled : [<%= string.Join(", ", disabledIndexes.ToArray()) %>]
                            });
        });
    </script>
</asp:Content>

In the above, we are first iterating the Model to generate the tab headers, next we are again iterating it to generate the content panes and this time we are also populating the disabled index list and selecting the selected index. At last, we are dumping the selected index and converting the disabled indexes to a comma delimited string to create the tab in javascript.

Now lets see how this can simplify the above situation, we can do the exact same thing with the following codes.

Simple Fluent:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IList<DynamicTabContent>>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Tab Dynamic Item Example
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <% Html.jQuery().Tab().Name("tabs")
                          .Items(item =>
                                         {
                                             for(var i = 0; i < Model.Count; i++)
                                             {
                                                 var dynamicContent = Model[i];

                                                 item.Create()
                                                     .HeaderText(dynamicContent.Header)
                                                     .Content(() =>
                                                                      {%>
                                                                        <p><%= Html.Encode(dynamicContent.Content) %></p>
                                                                      <%}
                                                             )
                                                     .Selected(dynamicContent.IsSelected)
                                                     .Disabled(dynamicContent.IsDisabled);
                                             }
                                         }
                                )
                          .Render(); %>
</asp:Content>

[Live Version]

As you can see it is much more simpler and concise and with the above, we do not have to iterate the model again and again, no need to maintain the selected index and disabled index list, the component takes these responsibility and generates the Tab. I hope this clarifies the issue.

The second issue is the style of syntax, first, let me post the result of my previous Poll (total 48 votes):

  • Regular Methods (9 votes, 19%)
  • Simple Fluent (14 votes, 29%)
  • Progressive Fluent(25 votes, 52%)

Though the progressive has more votes, but I think once you are familiar with the syntax, the verboseness of the progressive fluent will start to irritate you and this is the reason why I have changed it to simple fluent from progressive fluent. You can download the latest version from the bottom of the post. Another interesting syntax proposed my Chad Myer. The difference between mine with this is that it first creates the component, but instead of returning the component it provides an Action to configure the component. Let us do a side by side comparison of this syntax with the simple fluent, here we will see the basic tab:

Factory + Action Syntax:

<% Html.jQuery<jQueryTab>(tab =>
                                       {
                                           tab.Name = "myTab";
                                           tab.Items(items =>
                                                             {
                                                                 items.Create(item =>
                                                                                        {
                                                                                            item.HeaderText = "Nunc tincidunt";
                                                                                            item.Content = () =>
                                                                                                                {%>
                                                                                                                     <p>
                                                                                                                         Proin elit arcu, rutrum commodo, vehicula tempus,
                                                                                                                         commodo a, risus. Curabitur nec arcu. Donec
                                                                                                                         sollicitudin mi sit amet mauris. Nam elementum
                                                                                                                         quam ullamcorper ante. Etiam aliquet massa et
                                                                                                                         lorem. Mauris dapibus lacus auctor risus. Aenean
                                                                                                                         tempor ullamcorper leo. Vivamus sed magna quis
                                                                                                                         ligula eleifend adipiscing. Duis orci. Aliquam
                                                                                                                         sodales tortor vitae ipsum. Aliquam nulla. Duis
                                                                                                                         aliquam molestie erat. Ut et mauris vel pede
                                                                                                                         varius sollicitudin. Sed ut dolor nec orci
                                                                                                                         tincidunt interdum. Phasellus ipsum. Nunc
                                                                                                                         tristique tempus lectus.
                                                                                                                    </p>
                                                                                                                 <%};
                                                                                        }
                                                                               );

                                                                 items.Create(item =>
                                                                                        {
                                                                                            item.HeaderText = "Proin dolor";
                                                                                            item.Content = () =>
                                                                                                                {%>
                                                                                                                     <p>
                                                                                                                        Morbi tincidunt, dui sit amet facilisis feugiat,
                                                                                                                        odio metus gravida ante, ut pharetra massa metus
                                                                                                                        id nunc. Duis scelerisque molestie turpis. Sed
                                                                                                                        fringilla, massa eget luctus malesuada, metus eros
                                                                                                                        molestie lectus, ut tempus eros massa ut dolor.
                                                                                                                        Aenean aliquet fringilla sem. Suspendisse sed
                                                                                                                        ligula in ligula suscipit aliquam. Praesent in
                                                                                                                        eros vestibulum mi adipiscing adipiscing. Morbi
                                                                                                                        facilisis. Curabitur ornare consequat nunc. Aenean
                                                                                                                        vel metus. Ut posuere viverra nulla. Aliquam erat
                                                                                                                        volutpat. Pellentesque convallis. Maecenas feugiat,
                                                                                                                        tellus pellentesque pretium posuere, felis lorem
                                                                                                                        euismod felis, eu ornare leo nisi vel felis.
                                                                                                                        Mauris consectetur tortor et purus.
                                                                                                                    </p>
                                                                                                                 <%};
                                                                                        }
                                                                               );

                                                                 items.Create(item =>
                                                                                        {
                                                                                            item.HeaderText = "Aenean lacinia";
                                                                                            item.Content = () =>
                                                                                                                {%>
                                                                                                                    <p>
                                                                                                                        Mauris eleifend est et turpis. Duis id erat.
                                                                                                                        Suspendisse potenti. Aliquam vulputate, pede vel
                                                                                                                        vehicula accumsan, mi neque rutrum erat, eu congue
                                                                                                                        orci lorem eget lorem. Vestibulum non ante. Class
                                                                                                                        aptent taciti sociosqu ad litora torquent per
                                                                                                                        conubia nostra, per inceptos himenaeos. Fusce
                                                                                                                        sodales. Quisque eu urna vel enim commodo
                                                                                                                        pellentesque. Praesent eu risus hendrerit ligula
                                                                                                                        tempus pretium. Curabitur lorem enim, pretium nec,
                                                                                                                        feugiat nec, luctus a, lacus.
                                                                                                                    </p>
                                                                                                                    <p>
                                                                                                                        Duis cursus. Maecenas ligula eros, blandit nec,
                                                                                                                        pharetra at, semper at, magna. Nullam ac lacus.
                                                                                                                        Nulla facilisi. Praesent viverra justo vitae neque.
                                                                                                                        Praesent blandit adipiscing velit. Suspendisse
                                                                                                                        potenti. Donec mattis, pede vel pharetra blandit,
                                                                                                                        magna ligula faucibus eros, id euismod lacus dolor
                                                                                                                        eget odio. Nam scelerisque. Donec non libero sed
                                                                                                                        nulla mattis commodo. Ut sagittis. Donec nisi
                                                                                                                        lectus, feugiat porttitor, tempor ac, tempor vitae,
                                                                                                                        pede. Aenean vehicula velit eu tellus interdum
                                                                                                                        rutrum. Maecenas commodo. Pellentesque nec elit.
                                                                                                                        Fusce in lacus. Vivamus a libero vitae lectus
                                                                                                                        hendrerit hendrerit.
                                                                                                                    </p>
                                                                                                                 <%};
                                                                                        }
                                                                               );
                                                             }
                                                    );
                                       }
                            ); %>

Simple Fluent:

<% Html.jQuery().Tab()
                .Name("myTab")
                .Items(items =>
                              {
                                 items.Create()
                                      .HeaderText("Nunc tincidunt")
                                      .Content(() =>
                                                     {%>
                                                         <p>
                                                             Proin elit arcu, rutrum commodo, vehicula tempus,
                                                             commodo a, risus. Curabitur nec arcu. Donec
                                                             sollicitudin mi sit amet mauris. Nam elementum
                                                             quam ullamcorper ante. Etiam aliquet massa et
                                                             lorem. Mauris dapibus lacus auctor risus. Aenean
                                                             tempor ullamcorper leo. Vivamus sed magna quis
                                                             ligula eleifend adipiscing. Duis orci. Aliquam
                                                             sodales tortor vitae ipsum. Aliquam nulla. Duis
                                                             aliquam molestie erat. Ut et mauris vel pede
                                                             varius sollicitudin. Sed ut dolor nec orci
                                                             tincidunt interdum. Phasellus ipsum. Nunc
                                                             tristique tempus lectus.
                                                        </p>
                                                     <%}
                                                );

                                  items.Create()
                                       .HeaderText("Proin dolor")
                                       .Content(() =>
                                                     {%>
                                                         <p>
                                                            Morbi tincidunt, dui sit amet facilisis feugiat,
                                                            odio metus gravida ante, ut pharetra massa metus
                                                            id nunc. Duis scelerisque molestie turpis. Sed
                                                            fringilla, massa eget luctus malesuada, metus eros
                                                            molestie lectus, ut tempus eros massa ut dolor.
                                                            Aenean aliquet fringilla sem. Suspendisse sed
                                                            ligula in ligula suscipit aliquam. Praesent in
                                                            eros vestibulum mi adipiscing adipiscing. Morbi
                                                            facilisis. Curabitur ornare consequat nunc. Aenean
                                                            vel metus. Ut posuere viverra nulla. Aliquam erat
                                                            volutpat. Pellentesque convallis. Maecenas feugiat,
                                                            tellus pellentesque pretium posuere, felis lorem
                                                            euismod felis, eu ornare leo nisi vel felis.
                                                            Mauris consectetur tortor et purus.
                                                        </p>
                                                     <%}
                                                );

                                  items.Create()
                                       .HeaderText("Aenean lacinia")
                                       .Content(() =>
                                                     {%>
                                                        <p>
                                                            Mauris eleifend est et turpis. Duis id erat.
                                                            Suspendisse potenti. Aliquam vulputate, pede vel
                                                            vehicula accumsan, mi neque rutrum erat, eu congue
                                                            orci lorem eget lorem. Vestibulum non ante. Class
                                                            aptent taciti sociosqu ad litora torquent per
                                                            conubia nostra, per inceptos himenaeos. Fusce
                                                            sodales. Quisque eu urna vel enim commodo
                                                            pellentesque. Praesent eu risus hendrerit ligula
                                                            tempus pretium. Curabitur lorem enim, pretium nec,
                                                            feugiat nec, luctus a, lacus.
                                                        </p>
                                                        <p>
                                                            Duis cursus. Maecenas ligula eros, blandit nec,
                                                            pharetra at, semper at, magna. Nullam ac lacus.
                                                            Nulla facilisi. Praesent viverra justo vitae neque.
                                                            Praesent blandit adipiscing velit. Suspendisse
                                                            potenti. Donec mattis, pede vel pharetra blandit,
                                                            magna ligula faucibus eros, id euismod lacus dolor
                                                            eget odio. Nam scelerisque. Donec non libero sed
                                                            nulla mattis commodo. Ut sagittis. Donec nisi
                                                            lectus, feugiat porttitor, tempor ac, tempor vitae,
                                                            pede. Aenean vehicula velit eu tellus interdum
                                                            rutrum. Maecenas commodo. Pellentesque nec elit.
                                                            Fusce in lacus. Vivamus a libero vitae lectus
                                                            hendrerit hendrerit.
                                                        </p>
                                                     <%}
                                                );
                              }
                       )
                .Render(); %>

To me the simple fluent is much simpler than Chad’s Factory + Action. But I think, it completely depends upon the personal preference. If you think, Factory + Action is much preferable than the simple fluent or even you want to revert back to the initial progressive fluent, do let me know I will change it  based upon your feedback.

[Live Version]

[Download Sample]

Shout it

Few days back I ran a Poll to gather the feedback on ASP.NET MVC View Components that I am planning to build building. Though it is certainly not possible to get everyone’s vote of the ASP.NET MVC Community, but I think the result has enough votes to represents the whole community:

Which View Engine do you use in ASP.NET MVC (Total votes 276)?

  • Webform (185 votes, 67%)
  • Spark (60 votes, 22%)
  • NHaml (16 votes, 6%)
  • NVelocity (6 votes, 2%)
  • Brail (4 votes 1%)
  • Others (5 Votes, 2%)

What kind of UI Components do you prefer for Webform view engine? (Total votes 186)?

  • UI components as HtmlHelper methods (108 votes, 58%)
  • UI components as lightweight controls similar to mvc future assembly (38 votes, 20%)
  • Any of the above (40 votes, 22%)

Which Javascript framework your ASP.NET MVC UI component should depend? (Total votes 214)?

  • jQuery (185 votes, 86%)
  • ExtJS (11 votes, 5%)
  • MS ASP.NET AJAX (3 votes, 1%)
  • Can depend any of the above (8 votes, 4%)
  • Do not bother if it has multiple dependency (7 votes, 3%)

As you can see the Webform+HtmlHelper+jQuery is far ahead from its competitor. Now, let us asses the options that we have to create UI components that extends the HtmlHelper. In this post I will use the jQuery UI Slider for discussing the options. If you are not familiar with jQuery UI Slider, I would suggest to visit the previous link,  the slider has properties like value, min, max, step, range and events start, stop change, slide etc. Lets assume that the method we will have in the HtmlHelper will create the necessary html elements and emits required javascripts in the page.

Option#1 Create Regular Methods

We can create regular methods like the ASP.NET MVC Framework, for example:

public static class HtmlHelperExtension
{
    public static void Slider(this HtmlHelper htmlHelper, string id, int value, int min, int max, object htmlAttributes)
    {
        // Implementation
    }
}

And few more overloads, the number of parameter will vary based upon the complexity of the object that we are building:

//Range
public static void Slider(this HtmlHelper htmlHelper, string id, int value1, int value2, int min, int max, object htmlAttributes)
{
    // Implementation
}

public static void Slider(this HtmlHelper htmlHelper, string id, int value)
{
    // Implementation
}

So, in the view we will be able to use it like the following:

<% Html.Slider("mySlider", 10, 20, 0, 100, new { style = "border: #000 1px solid" }); %>
<% Html.Slider("mySlider", 10, 0, 100, null); %>
<% Html.Slider("mySlider", 10, 20, 0, 100, null); %>
<% Html.Slider("mySlider", 10); %>

Option#2 Create Simple Fluent Syntax

We can create a slider object similar to the following:

public class jQuerySlider
{
    private readonly HtmlHelper _htmlHelper;

    private string _id;
    private RouteValueDictionary _htmlAttributes;
    private int _value;
    private int[] _values;
    private int _minimum;
    private int _maximum;

    public jQuerySlider(HtmlHelper htmlHelper)
    {
        _htmlHelper = htmlHelper;
    }

    public jQuerySlider Id(string elementId)
    {
        _id = elementId;
        return this;
    }

    public jQuerySlider HtmlAttributes(object attributes)
    {
        _htmlAttributes = new RouteValueDictionary(attributes);

        return this;
    }

    public jQuerySlider Value(int sliderValue)
    {
        _value = sliderValue;
        return this;
    }

    // Range
    public jQuerySlider Values(int slider1Value, int slider2Value)
    {
        _values = new int[2];

        _values[0] = slider1Value;
        _values[2] = slider1Value;

        return this;
    }

    public jQuerySlider Minimum(int value)
    {
        _minimum = value;

        return this;
    }

    public jQuerySlider Maximum(int value)
    {
        _maximum = value;

        return this;
    }

    public void Render()
    {
        //Write html and register script
    }
}

And create an extension method of HtmlHelper:

public static jQuerySlider Slider(this HtmlHelper helper)
{
    return new jQuerySlider(helper);
}

Now, we will be able to use it in the view like:

<% Html.Slider()
       .Id("mySlider")
       .HtmlAttributes(new { style = "border:#000 1px solid" })
       .Values(10, 20)
       .Minimum(0)
       .Maximum(100)
       .Render(); %>

<% Html.Slider()
       .Id("mySlider")
       .Value(10)
       .Minimum(0)
       .Maximum(100)
       .Render(); %>

<% Html.Slider()
       .Id("mySlider")
       .Value(10)
       .Render(); %>

A bit verbose, but lot more readable comparing to the regular methods (option #1), but the problem with this approach is, it is really easy to write:

<% Html.Slider()
       .Id("mySlider")
       .Value(10)
       .Value(20)
       .Value(30)
       .Render(); %>

And VS will always show the method names no matter how many times it is called:

VS-AutoComplete

This makes the syntax a bit confusing and ambiguous.

Option#3 Create Progressive Fluent Syntax

This solves the exact problem that I have just mentioned. Rather than returning the same object in the methods, it returns different interface that is applicable in that context. For example:

VS-AutoComplete-p1

VS-AutoComplete-p2

VS-AutoComplete-p3

As you can see, once a method is called it does not appears in the auto complete list, also the next available methods in that context are shown. I have implemented the jQuery UI Accordion, Tab, ProgressBar, Slider and Theme Switcher (DatePicker and Dialog are under development) following this approach. You can find the fully functional version:

[Live version]

[Download Demo]

This option also has a drawback, it does not support method overlapping like the option #2, which means, we always have to call the methods in the exact same order and it becomes a bit painful when we want to change a specific value that is a few level deep. For example, if we want to change only the Steps of the Slider we have to use:

<% Html.jQuery().Slider()
                .Id("mySlider")
                .NoExtraHtmlAttributes()
                .DoNotAnimate()
                .UseDefaultOrientation()
                .NoRange()
                .Value(0)
                .UseDefaultMinimum()
                .UseDefaultMaximum()
                .Steps(5)
                .Render(); %>

Instead of:

<% Html.jQuery().Slider()
                .Id("mySlider")
                .Steps(5)
                .Render(); %>

Though I prefer it over the above two, but it completely depends upon you, which way you want to shape up the API. So dear readers, please download the demo, do play with it and leave your opinion in this poll.

Shout it

Justin Etheredge recently wrote about the RAD support that he would like to see in ASP.NET MVC and I do agree with him very much (as a side note, I highly recommend his blog you should subscribe). I am also planning to create some reusable UI components for ASP.NET MVC and I need your feedback prior starting it.

Please answer the following three Polls (Yes I am a Twitter fan):

  1. Which View Engine do you use in ASP.NET MVC – Webform Vs. Spark Vs. NHaml Vs. ….?
  2. What kind of UI Components do you prefer for Webform View Engine - HtmlHelper Vs. Control?
  3. Which Javascript framework your ASP.NET MVC UI component should depend – jQuery Vs. ExtJS Vs. MS Ajax?

Thanks for participating.

Shout it

My last post on Script and CSS Management in ASP.NET MVC has well accepted by the community and I have got few valuable suggestions, specially from Jake Scott. Beside those, there are one more awkward things I found while working with the Fluent html version which makes me to change few public signatures. Lets see the issue that I am talking about, in the initial version when you want to add multiple script lines, you have to do:

Html.jQuery().OnPageLoad("utility.init();\r\ntest.init();")

Did you get the issue, yes for formatting I have to add the \r\n at the end of each statement and enclose the whole thing in a “”, a better version would be:

Html.jQuery().OnPageLoad(
                             () =>
                             {%>
                                 utility.init();
                                 test.init();
                             <%}
                         );

With the above, I do not have to worry about the formatting or enclosing, I can type the same way as I do for regular javascript codes. This is the change in this version with just one exception, you have to explicitly call the Render() method instead of <%= like the previous version. A complete example of the previous version’s master page would be:

<% Html.jQuery().Scripts(
                            script =>
                            {
                                script.Source("http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js");
                                script.Source("~/Scripts/utility.js");
                            }
                         )
                 .OnPageLoad(
                                () =>
                                {%>
                                    utility.init();
                                    test.init();
                                <%}
                            )
                 .OnPageUnload(
                                () =>
                                {%>
                                    alert('Cleanup for master page.');
                                <%}
                              )
                .Render();%>

Since this version use Lambda syntax for javascript statements and to capture the output, I have to use a fake ASP.NET Response filter to capture and then rewrite it in the original stream, one of the pitfall of using ASP.NET Response filter and using response.Flush() in it is,  it is not possible to modify the ASP.NET Response header later on in that request. But I don’t think modifying the response header is not all required in our regular scenarios. Next, in the previous version I was using an implicit operator to convert the helper to string which no longer works when using the lambda in view, that is why it is required to call the Render() where you want to dump the output.

The next two changes does not have any impact on the public signatures, First the file caching, although the cache duration that is specified in the web.config applies to the http response header nothing to do with the server side caching but in this version, to make the development life easier, the server side caching is also depends upon this value (otherwise we have to compile the project each time we make a change in the script/css file), if you want to disable caching in server side just set this value to 0 (zero).

And the last one is adding an overloaded extension method for UrlHelper, as Jake mentioned he wants to use separate handlers for css and js files, with the overloaded version now you will be able specify the handler when mentioning the asset.

Enjoy!!!

Download: Full Source

Shout it

No, this is not at all a post of FubuMVC, I just borrowed the words for this post.

Jeff Atwood & Joel Spolsky thinks it is a compliment when they found there site design is copied by a Chinese site and I do agree it completely, specially when it is serving the same community that I belong to. And I also agree with Joel Spolsky that most (at least in my case) English as second language speaking developers prefer the local language when they are communicating between them. We made KiGG an Open Source Project from the very beginning and since the v2.0 is released people are really picking it for creating local .NET community sites in their own language:

 

dotnetomaniak_pl
Polish version

 

progg_ru
Russian version

 

9efish_com
Chinese version (I guess it is still under development)

And this is the power of Open Source, the existing version contains absolutely zero support for localization, but the community picked and made it local for them, it has the same features and power as the original version and my sincere thanks to them who are behind these. As a side note I want to mention that localization is the highest priority that we will be adding in v3.0

Recently, I got few requests about the story publishing process from the peoples who are also planning to launch sites based upon KiGG. So instead of answering them individually, I preferred to write a post to explain it.

Like the many social news/links site the story appearing in the front-page is done based upon some algorithms and it has the complete support to add/replace/remove any of those algorithms. By default, it comes with 6 different algorithms.

The story publish process starts when the Publish method of StoryService is called.

public virtual void Publish()
{
    using(IUnitOfWork unitOfWork = UnitOfWork.Begin())
    {
        DateTime currentTime = SystemTime.Now();

        IList<PublishedStory> publishableStories = GetPublishableStories(currentTime);

        if (!publishableStories.IsNullOrEmpty())
        {
            // First penalty the user for marking the story as spam;
            // It is obvious that the Moderator has already reviewed the story
            // before it gets this far.
            PenaltyUsersForIncorrectlyMarkingStoriesAsSpam(publishableStories);

            //Then Publish the stories
            PublishStories(currentTime, publishableStories);

            unitOfWork.Commit();
        }
    }
}

As you can see, it first calls the GetPublishableStories to prepare a list which is publishable at this moment, next it reduces the score of the users who have incorrectly marked any of those stories as spam (will explain  later) and at last it calls another method PublishStories to actually publish it.

private IList<PublishedStory> GetPublishableStories(DateTime currentTime)
{
    List<PublishedStory> publishableStories = new List<PublishedStory>();

    DateTime minimumDate = currentTime.AddHours(-_settings.MaximumAgeOfStoryInHoursToPublish);
    DateTime maximumDate = currentTime.AddHours(-_settings.MinimumAgeOfStoryInHoursToPublish);

    int publishableCount = _storyRepository.CountByPublishable(minimumDate, maximumDate);

    if (publishableCount > 0)
    {
        ICollection<IStory> stories = _storyRepository.FindPublishable(minimumDate, maximumDate, 0, publishableCount).Result;

        foreach (IStory story in stories)
        {
            PublishedStory publishedStory = new PublishedStory(story);

            foreach (IStoryWeightCalculator strategy in _storyWeightCalculators)
            {
                publishedStory.Weights.Add(strategy.Name, strategy.Calculate(currentTime, story));
            }

            publishableStories.Add(publishedStory);
        }
    }

    return publishableStories;
}

The GetPublishableStories first gets a list of active stories (the stories that has been voted, viewed, commented since the last publish, there is also an age factor which means story in specific age range will only qualify, default is 4-240 hour) form the database, next it applies the different algorithm to calculate its weight. This algorithm (Strategy Pattern) is defined as IStoryWeightCalculator interface and injected in the StoryService by the DI container. Once the calculation is done the PublishStories method is called.

private void PublishStories(DateTime currentTime, IList<PublishedStory> publishableStories)
{
    // Now sort it based upon the score
    publishableStories = publishableStories.OrderByDescending(ps => ps.TotalScore).ToList();

    // Now assign the Rank
    publishableStories.ForEach(ps => ps.Rank = (publishableStories.IndexOf(ps) + 1));

    // Now take the stories for front page
    ICollection<PublishedStory> frontPageStories = publishableStories.OrderBy(ps => ps.Rank).Take(_settings.HtmlStoryPerPage).ToList();

    if (!frontPageStories.IsNullOrEmpty())
    {
        foreach (PublishedStory ps in frontPageStories)
        {
            ps.Story.Publish(currentTime, ps.Rank);
        }

        _eventAggregator.GetEvent<StoryPublishEvent>().Publish(new StoryPublishEventArgs(frontPageStories, currentTime));
    }

    // Mark the Story that it has been processed
    publishableStories.ForEach(ps => ps.Story.LastProcessed(currentTime));
}

The PublishStories first ranks the stories based upon its total weight, then it takes the first 20 story (defined in the web.config) for the front-page and marks it as for front-page by updating its rank and published date, at last it updates the last process date of all the stories regardless its publish status so that we can verify its active status for the next publish.

As you can see the story qualifying is completely decided based upon those weight calculators and by adding/removing/replacing the new calculators you can tweak the whole story publishing process. Now lets see how the default calculators works.

VoteWeight: Returns higher value if the vote is given from a different IP address than the story was actually submitted, for example 10 if it is given from a different IP address and 5 from the same IP address. If you do not like it, you can level it in the web.config.

<type name="vote" type="IStoryWeightCalculator" mapTo="VoteWeightCalculator">
    <lifetime type="PerWebRequest"/>
    <typeConfig extensionType="Microsoft.Practices.Unity.Configuration.TypeInjectionElement, Microsoft.Practices.Unity.Configuration">
        <constructor>
            <param name="voteRepository" parameterType="IVoteRepository">
                <dependency/>
            </param>
            <param name="sameIPAddressWeight" parameterType="System.Single">
                <value type="System.Single" value="5"/>
            </param>
            <param name="differentIPAddressWeight" parameterType="System.Single">
                <value type="System.Single" value="10"/>
            </param>
        </constructor>
    </typeConfig>
</type>

CommentWeight: Returns higher value if comment is given from a different Ip  and not by the actual submitter. For example, 4 for different IP, 2 for same IP and 1 for the actual submitter no matter from which IP it was submitted. This can be changed from web.config:

<type name="comment" type="IStoryWeightCalculator" mapTo="CommentWeightCalculator">
    <lifetime type="PerWebRequest"/>
    <typeConfig extensionType="Microsoft.Practices.Unity.Configuration.TypeInjectionElement, Microsoft.Practices.Unity.Configuration">
        <constructor>
            <param name="commentRepository" parameterType="ICommentRepository">
                <dependency/>
            </param>
            <param name="ownerWeight" parameterType="System.Single">
                <value type="System.Single" value="1"/>
            </param>
            <param name="sameIPAddressWeight" parameterType="System.Single">
                <value type="System.Single" value="2"/>
            </param>
            <param name="differentIPAddressWeight" parameterType="System.Single">
                <value type="System.Single" value="4"/>
            </param>
        </constructor>
    </typeConfig>
</type>

ViewWeight: Returns the sum of each unique IP address view (view means when a user clicks a link which takes the user to the original source) multiplied by a factor, this can be also changed from the web.config.

<type name="view" type="IStoryWeightCalculator" mapTo="ViewWeightCalculator">
    <lifetime type="PerWebRequest"/>
    <typeConfig extensionType="Microsoft.Practices.Unity.Configuration.TypeInjectionElement, Microsoft.Practices.Unity.Configuration">
        <constructor>
            <param name="storyViewRepository" parameterType="IStoryViewRepository">
                <dependency/>
            </param>
            <param name="weightMultiply" parameterType="System.Single">
                <value type="System.Single" value="0.1"/>
            </param>
        </constructor>
    </typeConfig>
</type>

UserScoreWeight: Returns the sum of user score multiplied by a factor who voted the story, so that stories voted by the higher score users has much more chance to appear in the front-page. The factor can be also changed from the web.config.

Freshness: Returns value depending upon the story age, the young the story the higher the value. The freshness threshold and interval can also be changed from web.config.

KnownSource: Returns a value based upon the source grade. This ensures that stories from an well known source get higher chance to appear in the front-page. For example, a blog post from Gu should take precedence than a blog post of mine. These sources are maintained in the KnownSource database table. If the source is not known, then it returns nothing.

So, as you can understand with the above algorithms even a story that got less votes might rank better than a more voted story and another important things I would like to mention that it does not update any specific part (top/bottom) of the front-page, instead it updates the whole page, the existing story of the front-page might also appear in the front-page at the same or different location based upon its recent rank, the benifit is it will never replace much more popular but old story by a less popular new story.

Okay, if you think the above is a solid publishing process or the process su*ks or you need a much simpler algorithm, my recommendation is to create a new strategy inheriting from the StoryWeightBaseCalculator. Let us see how to create a dumb strategy which rank the story based upon the number of votes and comments it got.

public class SimpleWeightCalculator : StoryWeightBaseCalculator
{
    private readonly IVoteRepository _voteRepository;
    private readonly ICommentRepository _commentRepository;

    public SimpleWeightCalculator(IVoteRepository voteRepository, ICommentRepository commentRepository) : base("Simple")
    {
        _voteRepository = voteRepository;
        _commentRepository = commentRepository;
    }

    public override double Calculate(DateTime publishingTimestamp, IStory story)
    {
        ICollection<IVote> votes = _voteRepository.FindAfter(story.Id, story.LastProcessedAt ?? story.CreatedAt);
        ICollection<IComment> comments = _commentRepository.FindAfter(story.Id, story.LastProcessedAt ?? story.CreatedAt);

        return (votes.Count + comments.Count);
    }
}

Next, remove the existing strategies and add it in the web.config (I am assuming you know the configuration of MS Unity application block):

<type name="simple" type="IStoryWeightCalculator" mapTo="SimpleWeightCalculator">
    <lifetime type="PerWebRequest"/>
    <typeConfig extensionType="Microsoft.Practices.Unity.Configuration.TypeInjectionElement, Microsoft.Practices.Unity.Configuration">
        <constructor>
            <param name="voteRepository" parameterType="IVoteRepository">
                <dependency/>
            </param>
            <param name="commentRepository" parameterType="ICommentRepository">
                <dependency/>
            </param>
        </constructor>
    </typeConfig>
</type>

Now, when you publish stories, it will rank based upon the vote and comments it got since the last publish.

I hope the above clarifies the story publish process of KiGG and do let me what else of KiGG you want to highlight next.

Shout it
More Posts