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

C# Generic List – Copy by value

Posted by admin

Yesterday I came across an interesting issue. We have a source for our product information. This product are then published onto two websites with different tenant id. Now if we process 116K items two times, we are looking for ways to improve the performance. So what we did was we selected those SKU onlys once and updated them into a list twice with different tenant id each time.  Here's the code to explain it.

More coming soon ...


  • Print
  • PDF
  • RSS

Share
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

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
11May/100

Adding a reference of a WCF task hosted into a test Harness

Posted by Janak Gheewala

TDD is the in thing...

Recently I had to write a WCF task which was to be hosted in Windows services rather than IIS.

Although I did write a some test cases around it, the business case I was working on required me to write a test harness (it was a long running process & hence the decision to host it in Windows service & write a test harness)

Now since I already had a WCF service host client within the solution (see this post for more details), I could not add the reference to the test harness without an error as shown below

System.ServiceModel.AddressAlreadyInUseException: There is already a listener on IP endpoint 0.0.0.0:8532. Make sure that you are not trying to use this endpoint multiple times in your application and that there are no other applications listening on this endpoint. ---> System.Net.Sockets.SocketException: Only one usage of each socket address (protocol/network address/port) is normally permitted

at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress)

at System.Net.Sockets.Socket.Bind(EndPoint localEP)

at System.ServiceModel.Channels.SocketConnectionListener.Listen()

--- End of inner exception stack trace ---

at System.ServiceModel.Channels.SocketConnectionListener.Listen()

at System.ServiceModel.Channels.BufferedConnectionListener.Listen()

at System.ServiceModel.Channels.ExclusiveTcpTransportManager.OnOpen()

at System.ServiceModel.Channels.TransportManager.Open(TransportChannelListener channelListener)

at System.ServiceModel.Channels.TransportManagerContainer.Open(SelectTransportManagersCallback selectTransportManagerCallback)

at System.ServiceModel.Channels.ConnectionOrientedTransportChannelListener.OnOpen(TimeSpan timeout)

at System.ServiceModel.Channels.TcpChannelListener`2.OnOpen(TimeSpan timeout)

at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)

at System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen(TimeSpan timeout)

at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)

at System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan timeout)

at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)

at Microsoft.Tools.SvcHost.ServiceHostHelper.OpenService(ServiceInfo info)Only one usage of each socket address (protocol/network address/port) is normally permitted

The reason for this error is that as soon as your try and add a reference to the WCF task, it will spin up the existing WCF host client in the solution and hence the error above. To be fair, it will still add the reference to the test harness.

I wanted to get rid of this, it is then that I had a chat with Mr. Fenton and he suggested me a quick work around for this issue. Here's what I did.

* Remove the test harness from the solution
* spin up the test harness project as a separate project.
* then add the reference to the wcf task.

lo, job done.

  • Print
  • PDF
  • RSS

Share
Tagged as: , , No Comments
11May/100

Issues with hosting WCF in a Windows Service Using TCP

Posted by Janak Gheewala

I wanted to set up a WCF task hosted in windows services. I surfed a bit on the internet and found this explanatory example from microsoft. Job done? nay ... I could not start up service, When i checked the event log it had the following exception

Service cannot be started. System.InvalidOperationException: Service
'WindowsService1.Service1' has zero application (non-infrastructure)
endpoints. This might be because no configuration file was found for your
application, or because no service element matching the service name could
be found in the configuration file, or because no endpoints were defined in
the service element.
at
System.ServiceModel.Description.DispatcherBuilder.EnsureThereAreNonMexEndpoints(ServiceDescription
description)
at
System.ServiceModel.Description.DispatcherBuilder.InitializeServiceHost(ServiceDescription
description, ServiceHostBase serviceHost)
at System.ServiceModel.ServiceHostBase.InitializeRuntime()
at System.ServiceModel.ServiceHostBase.OnBeginOpen()
at System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan
timeout)
at System.ServiceModel.Channels.CommunicationObject.Open()
at WindowsService1.Service1.OnStart(String[] args) in C:\Program
Files\...

It was after a bit of thinking I realised that there was a reference problem. Because the reference should be

myServiceHost = new ServiceHost(typeof(WcfServiceLibrary1.Service1));

and not
myServiceHost = new ServiceHost(typeof(Service1));

The reason for this is both the WcfService and Windows Service contains class as Service1 and if you use the Service1 as given in the link, it refers to WindowsService class file.

  • Print
  • PDF
  • RSS

Share
Tagged as: , No Comments
9May/100

Adding a reference of a WCF task hosted into a test Harness – Invalid Class Defination

Posted by Janak Gheewala

One of the difference that I found between hosting a WCF in IIS against hosting it in Windows Services is that you can't start the service if its not interfaced properly.

Let me give you an example


[ServiceBehavior(Namespace  = "some Namespace", Name = "some name")]

public class  ServiceClass: BaseClass

{

// some code

}

The above example failed in my case because the BaseClass was implementing and interface IBaseClass. To make the above example work I had to implement the interface as well.


[ServiceBehavior(Namespace  = "some Namespace", Name = "some name")]

public class  ServiceClass: BaseClass, IBaseClass

{

// some code

}
  • Print
  • PDF
  • RSS

Share
Tagged as: , , No Comments
9May/100

integrating MVC 1.0 NUnit project template in Visual Studio

Posted by Janak Gheewala

I found some interesting links to add Nunit project templates to visual studio.  It also creates Item templates for MVC based .net development and traditional .net development.

Getting Started With TDD in Visual Studio - Alan Stevens

Updated NUnit Templates for ASP.Net MVC - Joe Ca rtano

Setting Up ASP.NET MVC with NUnit for Visual Studio - Nik Markis

How to: Add a Custom MVC Test Framework

  • Print
  • PDF
  • RSS

Share
Tagged as: , , No Comments