Janka's rambilng on boring stuff
Janka's Blog
8Jul/100

Disposing Proxy calls to WCF Services

Posted by Janak Gheewala

How many times have we had this issue, you call a WCF (of infact any other service) and due to some exception the the call to the service is not disposed and will eventually eat up all the resource.

A classic example of such issue is

<pre>
<pre>	public void Save(Message message)
	{
		IService _service = new ServiceClient();
		SaveMessageRequest request = new SaveMessageRequest{Message = message};
		_service.SaveMessage(request);
	}


To resolve this ussye we will make changes in two steps.

Step 1:

We will define a partial class with dispose method.


    public partial class ServiceClient : IDisposable
    {
        /// <summary>
        /// A partial class for ServiceClient
        /// Used to correctly close or abort a WCF proxy call.
        /// You MUST wrap the proxy call with a USING statement as DISPOSE will ALWAYS be called
        /// </summary>
        void IDisposable.Dispose()
        {
            // Check to see if the call has faulted
            if (State == CommunicationState.Faulted)
            {
                // We must abort the proxy as closing it will cause an exception
                Abort();
            }
            else
            {
                // Close the proxy
                Close();
            }
        }
    }

Step 2:

 We will change the save method to look as below. This will make sure that before the execution exits the using, the dispose method is called to dispose the service client.  

	public void Save(Message message)
	{
		using (ServiceClient smsProxy = new ServiceClient())
		{
			SaveMessageRequest request = new SaveMessageRequest{Message = message};
			smsProxy.SaveMessage(request);
		}
	}
  • Print
  • PDF
  • RSS

Share
8Jul/100

AJAX & JQuery Paging with ASP.NET MVC

Posted by Janak Gheewala

I am currently doing a small project on MVC. With web development, there is a basic requirement for presentiong data. paging ... you will find a lot of articles on both this. I came across an article which was very useful. This article by Martijn Boland is a very good article if you want to use microsoft ajax.

Of course, in these days, nothing is ever good enough if it's not using JQuery. I have done a small demo app to show this. You can download the demo app from here.

Right.  After a bit of tweaking I have the code ready. I have used the sample application of NerdDinner for this demo. So you can get the code from Codeplex and make the necessary change. Please complete the following steps to make the changes.

Step 1:

We will first Add a list Model. We will call it DinnerListModel. The definition of which is given below.

<pre>using System.Collections.Generic;
namespace NerdDinner.Models
{
public class DinnerListModel
{
public IEnumerable<Dinner> Dinners { get; set; }
public int TotalRowsCount { get; set; }
}
}

Step 2:

We will Add a partial view to show the paged data. The contents of the partial view is listed below.

<pre><%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<DinnerListModel>" %>
<%@ Import Namespace="NerdDinner.Models" %>
<ul>
<% foreach (var dinner in Model.Dinners)
{
%>
<li>
<%= Html.ActionLink(dinner.Title,"Details", new{id=dinner.DinnerId})%>
on
<%=Html.Encode(dinner.EventDate.ToShortDateString())%>
@
<%=Html.Encode(dinner.EventDate.ToShortTimeString())%>
</li>
<%
}%>
</ul>

Note that the partial class is now inheriting from DinnerListModel instead of IEnumerable<Dinner>. Also the foreach loop now selects from Models.Dinner instead of Model.

Step 3:

The contents of content placeholder "MainContents" will look as follows.

<pre><pre>	<script type="text/javascript">
	    function pageselectCallback(page_index, jq) {
		    $.get("/Dinners/", { page: page_index, pageSize: 10 },
				   function (data) {
				       $('#ListResults').html(data);
				   });
		}

		jQuery(function ($) {
			$('#Pagination').pagination('<%= Model.TotalRowsCount %>', {
				callback: pageselectCallback
			});
		});
	</script>
	<h2>Upcoming Dinners</h2>
<div id="ListResults">
<%
Html.RenderPartial("~/Views/Dinners/DinnerResults.ascx", Model); %>
</div>
<div id="Pagination"></div><br />
	<p>
		<%: Html.ActionLink("Create New", "Create") %>
	</p>

The changes we have made is replacing the foreach loop to show data by a div tag called "ListResults" which will load the partial view. Also added is a div tag for pagination. The JQuery code will fetch the records based on page selected and number of record per page. Here as well the Page tag will change to

<pre><%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<DinnerListModel>" %>

Step 4:

Don't forget to add the Jquery files to script folder and Pagination.css to Content folder. These will be referenced in the site.master file by the following lines.

<script src="/Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.pagination.js" type="text/javascript"></script>

You can download the JQuery library from here. The pagination css can be downloaded from here.

Step 5:

After this I will a a new Method Called GetDinnerResults on DinnersControls.

<pre>        private DinnerListModel GetDinnerResults(int? page, int? pageSize)
{
IEnumerable<Dinner> upCommingDinners = _repository.FindUpCommingDinners().ToList();
IEnumerable<Dinner> selectedDinners = upCommingDinners.Skip((page ?? 0) * (pageSize ?? 10)).Take(10);

return    new DinnerListModel
{
Dinners = selectedDinners,
TotalRowsCount = upCommingDinners.Count()
};
}

Step 6:

The Index method will change to

<pre>        public ActionResult Index(int? page, int? pageSize)
{
DinnerListModel dinners = GetDinnerResults(page, pageSize);

if (Request.IsAjaxRequest())
{
return PartialView("DinnerResults", dinners);
}
else
{
return PartialView(dinners);
}
}

The above code indicates that we should load the partial onto the index page when the code is executed for the first time. For all other subsequent pages it will not the load he whole page but only load the partial view DinnersResults.

  • Print
  • PDF
  • RSS

Share
8Jul/100

How to use Inversion of Control containers

Posted by Janak Gheewala

Today I came up with a very good blog entry on IOC  by Krzysztof Koźmic. This, together with RichP's blog would form a very good understanding on IOC.

  • Print
  • PDF
  • RSS

Share
8Jul/100

Building a class from type defined in config

Posted by Janak Gheewala

Last week I came across a situation where it was required that a class was to be created of type provided in config. Ideally this should be done via IOC. But there is an alternative way.

the following method explains the same

public static ISomeClass Build(string typeToCreate)
{
	Type instanceType = Type.GetType(typeToCreate);
	ISomeClass someClass = (ISomeClass)Activator.CreateInstance(instanceType);

	return someClass;
}

the class type in config is as follows

<?xml version="1.0" encoding="utf-8" ?>
<SomeClassConfiguration
...
  someClassType="Some.Class.Defined.SomeClass, Some.Class.Defined"
...
>
</SomeClassConfiguration>
  • Print
  • PDF
  • RSS

Share