Saturday, November 19, 2011

ScrollToBottom extension method in ScrollViewer - Silverlight 4

ScrollViewer is one among the commonly used Silverlight control. When you develop Silverlight application, at some time, you'll come across using ScrollViewer. Using ScrollViewer is straightforward in most of the cases. In some scenarios (like displaying chat history messages, stock history update), we might want to bind values to elements inside the ScrollViewer and then scroll to the bottom in order to make the latest message appear in the visible region.

ScrollToBottom() is one among the several extension methods available for ScrollViewer which helps us to achieve scrolling vertically to the end of the ScrollViewer content. While using this ScrollToBottom() method some developers won't see the ScrollViewer scrolls upto the bottom. So, why it is like that what need to be done to make it work? Let us dive into the implementation of ScrollToBottom() method and find out the solution.

Snippet 1: (ScrollToBottom() implementation)

public static void ScrollToBottom(this ScrollViewer viewer)
{
    if (viewer == null)
    {
        throw new ArgumentNullException("viewer");
    }

    viewer.ScrollToVerticalOffset(viewer.ExtentHeight);
}

As most of us might guess, it scrolls the veritical offset to the height of the content inside the ScrollViewer. Actually the values for properties like ScrollViewer.ExtentHeight, ScrollViewer.VerticalOffset are not recalculated immediately. It seems that they placed such restrictions due to performance considerations.

We can force to recalculate and update values of related properties by calling the UpdateLayout() method of the ScrollViewer. Anyhow be sure to call the UpdateLayout() only required. Please view the remarks section here at msdn documentation.

Ultimately, calling the UpdateLayout() method on the ScrollViewer before ScrollToBottom() is called will solve the obstacle.

Following is a sample snippet to help you understand the above specified scenario. Try executing the following snippet and inspect the value of ExtentHeight(and related properties) property by inserting the breakpoint in the call to UpdateLayout() method.

Snippet 2:
ScrollViewerTest.xaml

<UserControl x:Class="TestSilverlightApplication1.ScrollViewerTest"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="500" d:DesignWidth="500">
    <Grid Background="DeepSkyBlue">
        <Grid x:Name="LayoutRoot" Background="SkyBlue" Height="300" Width="400">
            <Grid.RowDefinitions>
                <RowDefinition></RowDefinition>
                <RowDefinition Height="Auto"></RowDefinition>
                <RowDefinition Height="70"></RowDefinition>
                <RowDefinition Height="Auto"></RowDefinition>
                <RowDefinition Height="70"></RowDefinition>
                <RowDefinition></RowDefinition>
            </Grid.RowDefinitions>
            <StackPanel>
                <TextBlock Text="ScrollToBottom Check" HorizontalAlignment="Center" FontWeight="Bold" ></TextBlock>

            </StackPanel>
            <TextBlock Grid.Row="1" Text="Enter multiline text here......"></TextBlock>
            <ScrollViewer Grid.Row="2">
                <TextBox AcceptsReturn="True" Text="{Binding SampleTextString, Mode=TwoWay}"></TextBox>
            </ScrollViewer>
            <Button Content="...and click here...." Click="ScrollDownCheck_Click" Width="150" Grid.Row="3" Margin="10"></Button>
            <ScrollViewer Grid.Row="4" Name="TestScrollControl">
                <TextBox AcceptsReturn="True" Name="TestTextBox" Text="{Binding AlteredTextString}"></TextBox>
            </ScrollViewer>
        </Grid>
    </Grid>
</UserControl>


ScrollViewerTest.xaml.cs

using System.Windows;
using System.Windows.Controls;
using System.ComponentModel;

namespace TestSilverlightApplication1
{
    public partial class ScrollViewerTest : UserControl, INotifyPropertyChanged
    {
        public ScrollViewerTest()
        {
            InitializeComponent();
            InitControls();
        }

        private string sampleTextString;

        public string SampleTextString
        {
            get { return sampleTextString; }
            set
            {
                sampleTextString = value;
                NotifyPropertyChanged("SampleTextString");
            }
        }

        private string alteredTextString;

        public string AlteredTextString
        {
            get { return alteredTextString; }
            set
            {
                alteredTextString = value;
                NotifyPropertyChanged("AlteredTextString");
            }
        }
         
        private void ScrollDownCheck_Click(object sender, RoutedEventArgs e)
        {
            ManipulateScrollDownCheck();
        }

        private void InitControls()
        {
            this.DataContext = this;
        }

        private void ManipulateScrollDownCheck()
        {
            this.AlteredTextString = this.SampleTextString;
            //Insert breakpoint here and validate the value of 
            //ExtentHeight before and after the execution of UpdateLayout().
            TestScrollControl.UpdateLayout();
            TestScrollControl.ScrollToBottom();
        }

        #region INotifyPropertyChanged Members

        protected void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion
    }
}


You can infer from the above example that the call to UpdateLayout() is made before calling ScrollToBottom() and after assinging the value to the property bound to the content(UIElement contained inside the ScrollViewer) of the ScrollViewer. Since developers will face such problem only at certain workflows, call the UpdateLayout() only when you encounter that problem.

Reference
http://msdn.microsoft.com/en-us/library/system.windows.controls.scrollviewer.scrolltoverticaloffset(v=vs.95).aspx
http://msdn.microsoft.com/en-us/library/system.windows.controls.scrollviewer.scrolltobottom.aspx
https://epiinfo.svn.codeplex.com/svn/Silverlight.Controls.Toolkit/Controls.Toolkit/Common/ScrollViewerExtensions.cs

Sunday, November 13, 2011

n layer web app with Entity Framework 4.1/4.2 - Things to consider

With Entity Framework 4.1, it releases DbContext API and CodeFirst development model. It is recommended to work with DbContext which exposes the commonly used features of ObjectContext.
Creating object context in DatabaseFirst or ModelFirst approach can be done with the help of ADO.NET DbContext Genrator template in Visual Studio. To achieve that open the .edmx file and right click the base surface >> Add Code Generation Item >> Code >> ADO.NET DbContext Generator. This template is available only when you install EF 4.1 directly. If you install the EF4.1 with NuGet packages, the reference will get added but the ADO.NET DbContext Generator template won't be available. You can use NuGet packages for adding(and managing) the reference to the specific project or solution.

Repository pattern suits best for this case, so that we can create an individual repository for each entity. For details on repository pattern please visit msdn() and Martin Fowler's explanation. Following is a simple and common representation of repository that developers adopt using EF4.1. Please note that following snippet is just to understand the concept.

Snippet 1

public class CompanyRepository: IDisposable
{
    private HSMDBEntities Context { get; set; }

    public CompanyRepository()
    {
        this.Context = new HSMDBEntities();
    }

    public void Create(Company company)
    {
        this.Context.Companies.Add(company);
        this.Context.SaveChanges();
    }

    public Company GetCompanyById(int id)
    {
        //this.Context.Companies.Load();
        //return this.Context.Companies.Where(c => c.Id == id).Single();
        return this.Context.Companies.Find(id);
        
    }

    public IEnumerable<Company> GetAll()
    {
        return this.Context.Companies.ToList();
    }
    
    public void Update(Company company)
    {
        Company currentEntry = this.Context.Companies.Where(c => c.Id == company.Id).First();

        //Client wins model.
        this.Context.Entry(currentEntry).CurrentValues.SetValues(company);
        this.Context.SaveChanges();
    }

    public void Remove(Company company)
    {
        Remove(company.Id);
    }

    public void Remove(int id)
    {
        Company currentEntry = this.Context.Companies.Where(c => c.Id == id).Single();
        this.Context.Companies.Remove(currentEntry);
    }

    public void Dispose()
    {
        this.Context.Dispose();
    }
}

The above Repository snippet exposes the basic operations performed over the entity. Most of the methods are straight forward to understand and the two methods we need to concentrate are GetCompanyById() and Update().

GetCompanyById()  - The DbSet<T> property of the DbContext instance exposes a Find method which uses the primary key to find the entity. The speciality of this method is that the database will be hit only if the entity with the specific key is not found in the context. If the specific entity already got loaded, that entity will be returned upon request without hitting the database. That's why I've commented out the default way of retrieving the entity.

Update() - Consider the following scenario. In n layer architecture, the data model/entity retrieved will be converted into domain specific model and other DTOs(Data Transfer Objects), while passing across the layer to reach the client application(like web app). Similarly the modified data from the client reaches the data tier passing several transitions, and we simply update the database with the values from client. If any other request updates some column value of the entity in the interim time, those changes won't be respected, and whatever value reaches the data tier is updated in a brutal manner. This approach is called as client wins approach which is used common among n layer web applications. I restrict myself ending this update scenario with this short detail as this discussion itself can extend as a separate article. This client wins model is achieved in the above snippet by fetching the current status from the database and overwriting the values got from the client and continue saving it. The highlight here is the SetValues() method of the property DbPropertyValue, which assigns all the current values of individual properties with that of the properties of the parameter object supplied to it. This eradicates the great work of reassigning the individual property values explicitly.

this.Context.Entry(currentEntry).CurrentValues.SetValues(company);


in the place of

var entityEntry = this.Context.Entry(currentEntry);
entityEntry.Property(p => p.Id).CurrentValue = 1;
entityEntry.Property(p => p.CompanyName).CurrentValue = "Company name altered";

 

Now comes the reason for implementing the IDisposable. The best practice regarding the creation of DbContext instance when handling with a web application is - one context instance per request. Hence in n layer web application architecture, components in other layer(most of the times will be Business components) should take the responsibility of handling the lifetime of the context. This can be achieved by handling the respective repository instance with the using construct which automatically calls the dispose method of the repository instance.

using (CompanyRepository companyRepository = new CompanyRepository())
{
...............................
}


In real cases a base and a generic repository will be created based on the project nature and repository  created for each entities will be extended from the base repository. At that situation the base repository class will implement the IDisposable which handles the context instance creation and its lifetime.

public class CompanyRepository : BaseRepository
{        
    public CompanyRepository()
        :base()
    {
        
    }

    public void Create(Company company)
    {
        this.Context.Companies.Add(company);
        this.Context.SaveChanges();
    }

    public Company GetCompanyById(int id)
    {
        //this.Context.Companies.Load();
        //return this.Context.Companies.Where(c => c.Id == id).Single();
        return this.Context.Companies.Find(id);

    }

    public IEnumerable<Company> GetAll()
    {
        return this.Context.Companies.ToList();
    }

    public void Update(Company company)
    {
        Company currentEntry = this.Context.Companies.Where(c => c.Id == company.Id).First();

        //Client wins model.
        this.Context.Entry(currentEntry).CurrentValues.SetValues(company);
        this.Context.SaveChanges();
    }

    public void Remove(Company company)
    {
        Remove(company.Id);
    }

    public void Remove(int id)
    {
        Company currentEntry = this.Context.Companies.Where(c => c.Id == id).Single();
        this.Context.Companies.Remove(currentEntry);
    }

}

public class BaseRepository : IDisposable
{
    protected HSMDBEntities Context { get; set; }

    public BaseRepository()
    {
        this.Context = new HSMDBEntities();
    }

    public void Dispose()
    {
        this.Context.Dispose();
    }
}


The BaseRepository also need to be extended further. Its good to have the above things in mind while developing n layer web application. 

Saturday, October 29, 2011

ASP.NET MVC 3 - Representing contents in Razor View

The Razor view engine in ASP.NET MVC 3, throws error when we specify the content block directly without enclosing it in tags especially inside the coding constructs like if, for loop and so on.

Following Snippet throws error
@if(condition) {
    Any direct content.......
}


In such cases, developers usually specify tags like <span> as a workaround in order to specify the contents. But there exists two ways for directly represent this case.
  1. @: - for indicating the characters following it are content items and usually used for representing single line content.
  2. <text>....</text> - entire content block is enclosed within the <text>....</text> element and usually used for representing multi line contents.

@if(condition) {
    <text>Multi line statement 1
    Multi line statement 1
    ..................
    Multi line statement n</text>
}


@if(condition) {
    @:single line content goes here....
}


This is a straight forward feature but unexposed to several developers. It is simple but effective.

Sunday, October 23, 2011

Parsing and Manipulating HTML strings - C#

Recently I came across a situation, where I need to retrieve an HTML string created and stored by an ASP application. Upon retrieving the html string, I need to parse the string and manipulate html string by removing some deprecated attributes and us some other equivalent alternate instead. For instance the size attribute in the font element need to be replaced with css font-size attribute.

Snippet 1:

<font size="1">......</font>

to 

<font style="font-size: 9px;">......</font>


One additional thing we need to note here is, since we don't have any direct equivalent of the unit and value for the size attribute, I simply changed it to the expected size for the invoking applications.

Fine, now comes core of the issue about how to manipulate the HTML string. Initially I thought of using regex. Suddenly, I remembered of the nice tool Html Agility Pack which I explored few months back. Its an HTML parser that allows us to select an HTML element and manipulate it very easily. It uses the XPath to navigate through the elements. If you don't know XPath, no problem. You can refer to examples over the net (like in msdn and w3schools ) and find the XPath that suits better your requirement in less than a minute.

Following is the code for the situation I mentioned above.
Snippet 2:

private string RestructureDeprecatedAttributes(string htmlText)
{
    HtmlDocument document = new HtmlDocument();
    HtmlNodeCollection fontNodeCollection;
    
    document.LoadHtml(htmlText);
    fontNodeCollection = document.DocumentNode.SelectNodes("//font[@size]");

    if (fontNodeCollection != null)
    {
        foreach (HtmlNode fontNode in fontNodeCollection)
        {
            HtmlAttribute sizeAttribute = fontNode.Attributes["size"];

            if (!string.IsNullOrWhiteSpace(sizeAttribute.Value) && int.Parse(sizeAttribute.Value) > 0)
            {
                if (sizeAttribute.Value.Equals("1"))
                {
                    fontNode.SetAttributeValue("style", "font-size: 9px;");
                }
                else
                {
                    fontNode.SetAttributeValue("style", "font-size: 11px;");
                }
                
                fontNode.Attributes["size"].Remove();
            }
        }
    }

    return document.DocumentNode.WriteTo();
}

The selectors are really powerful which allows us to select the nodes that perfectly matches our criteria. The Html Agility Pack provides several methods that supports the manipulation of HTML strings in a very easy manner. You can infer this from the above code.

Sunday, October 9, 2011

ASP.NET MVC - Html.Partial vs Html.RenderPartial

RenderPartial writes the result directly to the response, technically speaking, directly into the calling object's TextWriter.

Partial on the other hand returns the HTML markup as string, which buffers the content. It achieves by creating and using a separate TextWriter.

Syntactic representation:
RenderPartial should be used inside a code block (obviously followed by a semicolon).

@{
    Html.RenderPartial("TestPartialView1");
}

Partial can be used directly as it returns the HTML markup as string.

@Html.Partial("TestPartialView1")

Usage:
Considering the performance RenderPartial is a bit faster and hence developers prefer using it inside the looping constructs and related scenarios.

Preference of Partial prevails in the case of regular syntax usage(meaning - uniform syntax usage as we don't need to wrap inside the code block) and if we need to perform any manipulation with the resultant HTML markup string.

Monday, September 12, 2011

ASP.NET MVC 3 - jQuery template tag inside Url.Action method

In this post we're going to deal with handling the jQuery template tag inside the Action method of the UrlHelper class(Url.Helper). To get a basic idea on jQuery templates and its implementation in ASP.NET MVC 3, have a glimpse on my previous posts ASP.NET MVC 3 and jQuery templates part1 and part2. Also for easier understanding I'll be using the same example explained in the post part2.

Let us consider a scenario to display list of members in a table format where each row represents each member and their related details represented in the subsequent columns. Let the final column represent a view hyperlink which onclick calls the action method MemberDetails of the ProjectMemberDetails with the id(EmployeeId) as parameter.

So our focus is to create a hyperlink with href something like "..../ProjectMemberDetails/MemberDetails/E1001", where "E1001" corresponds to the employee id. Also note that my map route is specified in such a way that the URL accepts id parameter.

Snippet 1: (Global.asax.cs - Default map route)

routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);

Following is my controller holding the related actions.

Snippet 2: (Controller)

public class ProjectMemberDetailsController : Controller
{
    public ActionResult ProjectMemberListForTemplateCheck(string experience)
    {
        return View("JqueryTemplateTagInAction");
    }

    [HttpPost]
    public JsonResult ProjectMemberListForTemplateCheckJson(string experience)
    {
        SampleData sampleData = new SampleData();

        if (string.IsNullOrEmpty(experience) || experience.Equals("All"))
        {
            return Json(sampleData.ProjectMemberList, JsonRequestBehavior.AllowGet);
        }
        else
        {
            return Json(sampleData.GetProjectMembersWithExpGreaterThan(int.Parse(experience)), JsonRequestBehavior.AllowGet);
        }
        
    }

    public ActionResult MemberDetails(string id)
    {
        SampleData sampleData = new SampleData();

        return View("MemberDetails", (object)sampleData.GetProjectMemberDetails(id));
    }
}

Snippet for SampleData is same as in ASP.NET MVC 3 and jQuery templates part2.

Now just concentrate on the template part for building the hyperlink.

Snippet 3: (template part with template tag inside @Url.Action(....))

<script id="memberDetailTemplate" type="text/x-jquery-tmpl">
    <tr>
        <td>
            ${EmployeeName}
        </td>
        <td>
            ${Experience}
        </td>
        <td>
        {{if Designation == 'Tech Lead'}}
        <span style="color:Green; font-weight: bold;">${Designation}</span>
        {{else}}
        <span style="color:Blue;">${Designation}</span>
        {{/if}}            
        </td>
        <td style="text-align:center;">
            <a href="@Url.Action("MemberDetails", "ProjectMemberDetails", new { id = "${EmployeeId}" })">View</a>
        </td>
    </tr>  
</script>


The idea is when the view engine renders the page, the href should be rendered like "..../ProjectMemberDetails/MemberDetails/${EmployeeId}", which on applying templ function with data, the "${EmployeeId}" should be replaced with the employee id.

Upon executing the application with the above template as specified in the Snippet 3, the href is rendered as "..../ProjectMemberDetails/MemberDetails/%24%7BEmployeeId%7D".

What went wrong here? Have close look again. Yes, the string "${EmployeeId}" is url encoded and represented as is, which the jQuery template (.tmpl method)  is unable to detect and parse it. So once the specific part of the URL is rendered as "${EmployeeId}" instead of "%24%7BEmployeeId%7D", the jQuery template will parse and evaluate the template tag correctly and we'll get the expected result.

In order to achieve this, we need to apply the url decode(for attaining the reverese effect) over the resultant url action(Url.Action(....)).

Snippet 4:

<a href="@HttpUtility.UrlDecode(Url.Action("MemberDetails", "ProjectMemberDetails", new { id = "${EmployeeId}" }))">View</a>


Following is the full version of the code.

Snippet 5:

@model string
@{
    ViewBag.Title = "Jquery template tag inside Url.Action";
}
<h2>
    Jquery template tag inside Url.Action</h2>
@if (false)
{
    <script type="text/javascript" src="../../Scripts/jquery-1.6.2-vsdoc.js"></script>
}
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>

<script type="text/javascript" src="@Url.Content("~/Content/MVC3TestApp2/Scripts/jquery.tmpl.js")"></script>
<script id="memberDetailTemplate" type="text/x-jquery-tmpl">
    <tr>
        <td>
            ${EmployeeName}
        </td>
        <td>
            ${Experience}
        </td>
        <td>
        {{if Designation == 'Tech Lead'}}
        <span style="color:Green; font-weight: bold;">${Designation}</span>
        {{else}}
        <span style="color:Blue;">${Designation}</span>
        {{/if}}            
        </td>
        <td style="text-align:center;">
            <a href="@HttpUtility.UrlDecode(Url.Action("MemberDetails", "ProjectMemberDetails", new { id = "${EmployeeId}" }))">View</a>
        </td>
    </tr>  
</script>
<script type="text/javascript">
    $(document).ready(function () {
        $.ajax({ type: "POST", url: '@Url.Action("ProjectMemberListForTemplateCheckJson", "ProjectMemberDetails")', success: jsonProjectMemberListSuccessCallback });
    });

    function jsonProjectMemberListSuccessCallback(data) {
        var targetElement = $('#memberData');
        targetElement.empty();

        $("#memberDetailTemplate").tmpl(data).appendTo('#memberData');
    }
</script>
<div id="loadingFeedback" style="display: none; color: Red; font-weight: bold;">
    <p>
        Loading details....
    </p>
</div>
@using (Ajax.BeginForm(new AjaxOptions
{
    LoadingElementId = "loadingFeedback",
    OnSuccess = "jsonProjectMemberListSuccessCallback",
    Url = Url.Action("ProjectMemberListForTemplateCheckJson", "ProjectMemberDetails")
}))
{
    <table border="1" cellpadding="0" cellspacing="0" >
        <thead>
            <tr>
                <th>
                    Member Name
                </th>
                <th>
                    Experience
                </th>
                <th>
                    Designation
                </th>
                <th>
                    View Details
                </th>
            </tr>
        </thead>
        <tbody id="memberData">
        </tbody>
    </table>
    <p>
        @Html.Label("", "Member with experience greater than : ")
        @Html.DropDownList("experience", new SelectList(new[] { "All", "1", "2", "3", "4", "5", "6", "7", "8", "9" }, (Model ?? "All")))
        <input type="submit" name="Submit" value="Submit" />
    </p>   
     
}

Saturday, August 20, 2011

ASP.NET MVC 3 updating and handling the jQuery libraries

When installing the ASP.NET MVC 3, we'll be getting some tools for Visual Studio 2010 along with Nuget.Nuget is nothing but an Visual studio extension which can be used to install and update open source libraries. It handles the task of including the library files into the project, adding the required references, including the respective entries in the config files and some other tasks based on the package we install.

We can access the Nuget tools using Visual Studio 2010 from, Tools > Library Package Manager > Package Manager Console / Manage Nuget Packages. One we add the ASP.NET MVC 3 project to a solution, by default we'll get few jQuery and related packages got installed.

Package Manager Console
We can view the installed packages by typing the "get-package" command in the Package Manager Console. By default jQuery packages like jQuery (core library), jQuery.UI.Combined, jQuery.Validation and jQuery.vsdoc will be installed while adding the ASP.NET MVC 3 project. In order to update these default jQuery packages, use the following command in the Package Manager Console.

update-package jquery

In order to get info about Nuget Package Manager commands type "get-help nuget".    

Manage Nuget Packages
Apart from the Tools menu this option is also avaliable when we right click(context menu) on the project. This option is some what similar to the Extension Manager menu where we can visually manage the packages.



Summary
Using any of the above specified two options you can update the packages which will update the related files by removing the old ones and adding the new ones. This helps us handling the updating process smoothly without any miss-outs.
Creative Commons License
This work by Tito is licensed under a Creative Commons Attribution 3.0 Unported License.