May 01

Having used NUnit and Rhino for middle and service layer for past 4-5 years, I was feeling very comfortable with TDD. And then I joined this new WPF/Prism project and faced the real pain!
Using TDD in middle, service or data layer is normally easier and straight forward but when it comes to presentation layer it seems it still little cumbersome even though you are using MVVM . Using DI, IoC and MEF are adding the complexity to write simple unit test in presentation layer. As we are using a Prism like framework for this project, we faced a lot of challenges in writing unit test. Luckily we found solution for almost all these problems.
One of the key problem we faced is mocking the IServiceLocator.  Since we are using a lot of base classes coming from framework (Third Party component with no source code!), it was really a challenge in configuring container for service locator. In most of the cases developer doesn’t have any clue about what and all types need to be register in container so that base type should not throw object reference not set exceptions.
To solve the above problem, I created a MockServiceLocator and MockContainer class that is able to resolve literally any type that is having an interface. Here is the sample code snippet:

Code Snippet
  1. using System;
  2. using Microsoft.Practices.ServiceLocation;
  3. using Microsoft.Practices.Unity;
  4. using System.Collections.Generic;
  5. namespace UnitTestHelper
  6. {
  7. public static class MockServiceLocator
  8. {
  9. public static IServiceLocator GetMockServiceLocator
  10. {
  11. get
  12. {
  13. IUnityContainer container = new UnitTestHelper.MockUnityContainer();
  14. return new UnitTestHelper.UnityServiceLocatorAdapter(container);
  15. }
  16. }
  17. }
  18. public class MockUnityContainer : IUnityContainer
  19. {
  20. public Func<object> ResolveMethod { get; set; }
  21. public Func<IEnumerable<object>> ResolveAllMethod { get; set; }
  22. public IUnityContainer Parent
  23. {
  24. get { throw new System.NotImplementedException(); }
  25. }
  26. public IEnumerable<ContainerRegistration> Registrations
  27. {
  28. get { throw new NotImplementedException(); }
  29. }
  30. #region Implementation of IUnityContainer
  31. public IUnityContainer RegisterType(Type from, Type to, string name, LifetimeManager lifetimeManager, params InjectionMember[] injectionMembers)
  32. {
  33. throw new NotImplementedException();
  34. }
  35. public IUnityContainer RegisterInstance(Type t, string name, object instance, LifetimeManager lifetime)
  36. {
  37. return this;
  38. }
  39. public void Teardown(object o)
  40. {
  41. throw new System.NotImplementedException();
  42. }
  43. public IUnityContainer AddExtension(UnityContainerExtension extension)
  44. {
  45. throw new System.NotImplementedException();
  46. }
  47. public object Configure(Type configurationInterface)
  48. {
  49. throw new System.NotImplementedException();
  50. }
  51. public IUnityContainer RemoveAllExtensions()
  52. {
  53. throw new System.NotImplementedException();
  54. }
  55. public IUnityContainer CreateChildContainer()
  56. {
  57. return this;
  58. }
  59. public IUnityContainer AddNewExtension<TExtension>() where TExtension : UnityContainerExtension, new()
  60. {
  61. throw new NotImplementedException();
  62. }
  63. public object BuildUp(Type t, object existing, string name)
  64. {
  65. throw new NotImplementedException();
  66. }
  67. public object BuildUp(Type t, object existing)
  68. {
  69. throw new NotImplementedException();
  70. }
  71. public T BuildUp<T>(T existing, string name)
  72. {
  73. throw new NotImplementedException();
  74. }
  75. public T BuildUp<T>(T existing)
  76. {
  77. throw new NotImplementedException();
  78. }
  79. public TConfigurator Configure<TConfigurator>() where TConfigurator : IUnityContainerExtensionConfigurator
  80. {
  81. throw new NotImplementedException();
  82. }
  83. public IUnityContainer RegisterInstance(Type t, string name, object instance)
  84. {
  85. throw new NotImplementedException();
  86. }
  87. public IUnityContainer RegisterInstance(Type t, object instance, LifetimeManager lifetimeManager)
  88. {
  89. throw new NotImplementedException();
  90. }
  91. public IUnityContainer RegisterInstance(Type t, object instance)
  92. {
  93. throw new NotImplementedException();
  94. }
  95. public IUnityContainer RegisterInstance<TInterface>(string name, TInterface instance, LifetimeManager lifetimeManager)
  96. {
  97. throw new NotImplementedException();
  98. }
  99. public IUnityContainer RegisterInstance<TInterface>(string name, TInterface instance)
  100. {
  101. throw new NotImplementedException();
  102. }
  103. public IUnityContainer RegisterInstance<TInterface>(TInterface instance, LifetimeManager lifetimeManager)
  104. {
  105. throw new NotImplementedException();
  106. }
  107. public IUnityContainer RegisterInstance<TInterface>(TInterface instance)
  108. {
  109. throw new NotImplementedException();
  110. }
  111. public IUnityContainer RegisterType(Type t, string name, LifetimeManager lifetimeManager, params InjectionMember[] injectionMembers)
  112. {
  113. throw new NotImplementedException();
  114. }
  115. public IUnityContainer RegisterType(Type t, string name, params InjectionMember[] injectionMembers)
  116. {
  117. throw new NotImplementedException();
  118. }
  119. public IUnityContainer RegisterType(Type t, LifetimeManager lifetimeManager, params InjectionMember[] injectionMembers)
  120. {
  121. throw new NotImplementedException();
  122. }
  123. public IUnityContainer RegisterType(Type from, Type to, LifetimeManager lifetimeManager, params InjectionMember[] injectionMembers)
  124. {
  125. throw new NotImplementedException();
  126. }
  127. public IUnityContainer RegisterType(Type from, Type to, string name, params InjectionMember[] injectionMembers)
  128. {
  129. throw new NotImplementedException();
  130. }
  131. public IUnityContainer RegisterType(Type from, Type to, params InjectionMember[] injectionMembers)
  132. {
  133. throw new NotImplementedException();
  134. }
  135. public IUnityContainer RegisterType(Type t, params InjectionMember[] injectionMembers)
  136. {
  137. throw new NotImplementedException();
  138. }
  139. public IUnityContainer RegisterType<T>(string name, LifetimeManager lifetimeManager, params InjectionMember[] injectionMembers)
  140. {
  141. throw new NotImplementedException();
  142. }
  143. public IUnityContainer RegisterType<T>(string name, params InjectionMember[] injectionMembers)
  144. {
  145. throw new NotImplementedException();
  146. }
  147. public IUnityContainer RegisterType<T>(LifetimeManager lifetimeManager, params InjectionMember[] injectionMembers)
  148. {
  149. throw new NotImplementedException();
  150. }
  151. public IUnityContainer RegisterType<TFrom, TTo>(string name, LifetimeManager lifetimeManager, params InjectionMember[] injectionMembers) where TTo : TFrom
  152. {
  153. throw new NotImplementedException();
  154. }
  155. public IUnityContainer RegisterType<TFrom, TTo>(string name, params InjectionMember[] injectionMembers) where TTo : TFrom
  156. {
  157. throw new NotImplementedException();
  158. }
  159. public IUnityContainer RegisterType<TFrom, TTo>(LifetimeManager lifetimeManager, params InjectionMember[] injectionMembers) where TTo : TFrom
  160. {
  161. throw new NotImplementedException();
  162. }
  163. public IUnityContainer RegisterType<TFrom, TTo>(params InjectionMember[] injectionMembers) where TTo : TFrom
  164. {
  165. throw new NotImplementedException();
  166. }
  167. public IUnityContainer RegisterType<T>(params InjectionMember[] injectionMembers)
  168. {
  169. throw new NotImplementedException();
  170. }
  171. public object Resolve(Type t, string name)
  172. {
  173. return Rhino.Mocks.MockRepository.GenerateStub(t);
  174. }
  175. public object Resolve(Type t)
  176. {
  177. return this.ResolveMethod();
  178. }
  179. public T Resolve<T>(string name)
  180. {
  181. throw new NotImplementedException();
  182. }
  183. public T Resolve<T>()
  184. {
  185. throw new NotImplementedException();
  186. }
  187. public System.Collections.Generic.IEnumerable<object> ResolveAll(Type t)
  188. {
  189. throw new NotImplementedException();
  190. }
  191. public System.Collections.Generic.IEnumerable<T> ResolveAll<T>()
  192. {
  193. throw new NotImplementedException();
  194. }
  195. #endregion
  196. #region IDisposable Members
  197. public void Dispose()
  198. {
  199. throw new NotImplementedException();
  200. }
  201. #endregion
  202. public object BuildUp(Type t, object existing, string name, params ResolverOverride[] resolverOverrides)
  203. {
  204. throw new NotImplementedException();
  205. }
  206. public object Resolve(Type t, string name, params ResolverOverride[] resolverOverrides)
  207. {
  208. return Rhino.Mocks.MockRepository.GenerateStub(t);
  209. }
  210. public IEnumerable<object> ResolveAll(Type t, params ResolverOverride[] resolverOverrides)
  211. {
  212. throw new NotImplementedException();
  213. }
  214. }
  215. public class UnityServiceLocatorAdapter : ServiceLocatorImplBase
  216. {
  217. private readonly IUnityContainer _unityContainer;
  218. public UnityServiceLocatorAdapter(IUnityContainer unityContainer)
  219. {
  220. this._unityContainer = unityContainer;
  221. }
  222. protected override object DoGetInstance(Type serviceType, string key)
  223. {
  224. return this._unityContainer.Resolve(serviceType, key);
  225. }
  226. protected override IEnumerable<object> DoGetAllInstances(Type serviceType)
  227. {
  228. return this._unityContainer.ResolveAll(serviceType);
  229. }
  230. }
  231. }

written by Om

Jan 18

While publishing wcf services/asp.net application for the first time on any new server, many times we faced this problem. This happens because of various reasons. While googling I didn’t find all the reasons at one place so  I’m listing here some of the common cases when IIS prompt username and password for a newly hosted website.
1. Anonymous access is not selected in IIS properties .
Solution: Open IIS MMC –>Right click on your website –> Select Properties –>Select Directory Security–>Click Edit under Anonymous access–>Check the Anonymous access check box.

2.    IUSR_servername  is not having read permission.
Solution: Open IIS MMC–>Right click on your website –>Select Properties –>Check read checkbox under Directory tab.
3.    IUSR_servername  user is disabled.
Solution: Right click on My Computer select manage–>Select System Tools–>Local Users and Group–>Usersàright click on  IUSR_servername –>Propertiesàenable the user

4.    Password specified in the IIS MMC for IUSR does not  match the password set for the account in user manager.
Solution: Reset  IUSR_servername   password  as described above.

written by Om

Dec 13

Currently I am working on performance enhancement of a SaaS based web app. In first sprint I started to achieve some significant gain at infrastructure level, without touching any existing code. First thing I found after fine tuning the mysql server and profiling the database and wcf service is that we can avoid some good amount of database and service call just by implementing WCF service layer cache. So, I wrote some code to extend the wcf service and to cache the service response. I first implemented this using simple enterprise library caching application block. But soon found it’s not as scalable as our application needed so I started evaluating some robust distributed caching framework like memcache. I evaluated both .net version of memcached available (EnyimMemcached and BeITMemcached  ) but finally end up with Microsoft Velocity. Believe me working with velocity was more comfortable than any other! (no need to mention I love Microsoft :)   )

I’m writing here the step by step process to implement WCF service layer caching using Velocity. I choose to write very simple code here rather than using standard design n pattern so that it should be understandable to all those who come here by googling…

How to integrate velocity with WCF service layer caching:
Step 1: Configure Velocity
1. Download and install velocity from here (Windows power shell is prerequisite for installing velocity)
2. Prepare the Development Environment (check this )
Step 2: Extending WCF Services
1. Create a velocity cache manager class

Code Snippet
  1. using Microsoft.Data.Caching;
  2. using System.Configuration;
  3. namespace AppServer.Common.ServiceCaching
  4. {
  5. public class VelocityCacheManager
  6. {
  7. private string cacheName = AppSettings["CacheName"];
  8. private DataCacheFactory cacheFactory = new DataCacheFactory();
  9. private DataCache cache;
  10. public DataCache Cache
  11. {
  12. get
  13. {
  14. return cacheFactory.GetCache(cacheName);
  15. }
  16. }
  17. }
  18. }

2. Create operationCaching class by implemanting IOperationInvoker interface
OperationCaching.cs :

Code Snippet

using System.Collections.Generic;

using System.ServiceModel.Dispatcher;

using System.IO;

using System.Globalization;

using System.Xml.Serialization;

using Microsoft.Data.Caching;

namespace AppServer.Common.ServiceCaching

{

public class OperationCaching : IOperationInvoker

{

private VelocityCacheManager _cacheManager;

IOperationInvoker _operationInvoker;

private int _expirationTime;

private bool _isTokenCached;

private bool _isUserSpecific;

public OperationCaching(IOperationInvoker operationInvoker,int seconds, bool isUserSpecific)

{

this._operationInvoker = operationInvoker;

this._expirationTime = seconds;

this._isUserSpecific = isUserSpecific;

}

#region IOperationInvoker Members

public object[] AllocateInputs()

{

return _operationInvoker.AllocateInputs();

}

public object Invoke(object instance,object[] inputs,out object[] outputs)

{

_cacheManager = new VelocityCacheManager();

object request = inputs[0];

string key = Convert.ToString(request,CultureInfo.CurrentCulture);

XmlSerializer xmlSerializer = new XmlSerializer(request.GetType());

MemoryStream stream = new MemoryStream();

xmlSerializer.Serialize(stream, request);

key = System.Text.Encoding.Default.GetString(stream.GetBuffer());

if (!_isUserSpecific)

{

int startIndexUserId = key.IndexOf(“<UserId>”);

int endIndexUserId = key.IndexOf(“</UserId>”);

if (startIndexUserId != -1 && endIndexUserId != -1)

key = key.Remove(startIndexUserId, endIndexUserId – startIndexUserId + 11);

if (_cacheManager.Cache.Get(key) != null)

{

outputs = new object[0];

return _cacheManager.Cache.Get(key);

}

else

{

object response = this._operationInvoker.Invoke(instance,inputs, out outputs);

cacheManager.Cache.Add(key, response, TimeSpan.FromSeconds(_expirationTime));

return response;

}

}

}

public IAsyncResult InvokeBegin(object instance, object[] inputs, AsyncCallback callback, object state)

{

return _operationInvoker.InvokeBegin(instance, inputs, callback, state);

}

public object InvokeEnd(object instance, out object[] outputs, IAsyncResult result)

{

return _operationInvoker.InvokeEnd(instance, out outputs, result);

}

public bool IsSynchronous

{

get { return _operationInvoker.IsSynchronous; }

}

}

}

3. Create OperationCacheBehavior class by implementing attribute and IOperationBehavior
OperationCacheBehavior.cs

using System.Collections.Generic;

using System.ServiceModel.Dispatcher;

using System.IO;

using System.Globalization;

using System.Xml.Serialization;

using Microsoft.Data.Caching;

namespace AppServer.Common.ServiceCaching

{

public class OperationCaching : IOperationInvoker

{

private VelocityCacheManager _cacheManager;

IOperationInvoker _operationInvoker;

private int _expirationTime;

private bool _isTokenCached;

private bool _isUserSpecific;

public OperationCaching

(IOperationInvoker operationInvoker,

int seconds, bool isUserSpecific)

{

this._operationInvoker = operationInvoker;

this._expirationTime = seconds;

this._isUserSpecific = isUserSpecific;

}

#region IOperationInvoker Members

public object[] AllocateInputs()

{

return _operationInvoker.AllocateInputs();

}

public object Invoke(object instance,

object[] inputs,

out object[] outputs)

{

_cacheManager = new VelocityCacheManager();

object request = inputs[0];

string key = Convert.ToString(request,

CultureInfo.CurrentCulture);

XmlSerializer xmlSerializer = new XmlSerializer(request.GetType());

MemoryStream stream = new MemoryStream();

xmlSerializer.Serialize(stream, request);

key = System.Text.Encoding.Default.GetString(stream.GetBuffer());

//remove userId from key if response is not user specific

if (!_isUserSpecific)

{

int startIndexUserId = key.IndexOf(“<UserId>”);

int endIndexUserId = key.IndexOf(“</UserId>”);

if (startIndexUserId != -1 && endIndexUserId != -1)

key = key.Remove(startIndexUserId,

endIndexUserId – startIndexUserId + 11);

}

if (_cacheManager.Cache.Get(key) != null)

{

outputs = new object[0];

return _cacheManager.Cache.Get(key);

}

else

{

object response = this._operationInvoker.Invoke(instance,

inputs, out outputs);

_cacheManager.Cache.Add(key, response,

TimeSpan.FromSeconds(_expirationTime));

return response;

}

}

public IAsyncResult InvokeBegin(object instance, object[] inputs,

AsyncCallback callback, object state)

{

return _operationInvoker.InvokeBegin(instance,

inputs, callback, state);

}

public object InvokeEnd(object instance, out object[]

outputs, IAsyncResult result)

{

return _operationInvoker.InvokeEnd(instance, out outputs, result);

}

public bool IsSynchronous

{

get { return _operationInvoker.IsSynchronous; }

}

#endregion

}

}

Code Snippet
using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel.Description;

namespace AppServer.Common.ServiceCaching
{
public class OperationCacheBehavior : Attribute, IOperationBehavior

{
private int _expirationTime;
public virtual int ExpirationTime

{

get { return expirationTime; }

}

private bool _isTokenCached;

public virtual bool IsTokenCached

{

get { return _isTokenCached; }

set { _isTokenCached = value; }

}

private bool _isUserSpecific;

public bool IsUserSpecific

{

get { return _isUserSpecific; }

set { _isUserSpecific = value; }

}

public OperationCacheBehavior(int seconds, bool isUserSpecific)

{

this._expirationTime = seconds;

this._isUserSpecific = isUserSpecific;

}

#region IOperationBehavior Members

public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters)

{ ;}

public void ApplyClientBehavior(OperationDescription operationDescription, Dispatcher.ClientOperation clientOperation)

{ ;}

public void ApplyDispatchBehavior(OperationDescription operationDescription, Dispatcher.DispatchOperation dispatchOperation)

{

dispatchOperation.Invoker = new OperationCaching(dispatchOperation.Invoker, this.expirationTime, _isUserSpecific);

}

public void Validate(OperationDescription operationDescription)

{ ;}

#endregion

}

}

written by Om

Dec 07

I faced  this very weired problem today while trying to fix a caching problem. In one of our production server, cache manager got currupted due to some unknown reason and while investigating this issue I found the isolated storage folder (C:\Documents and Settings\Default User\Local Settings\Application Data\) not visible even though in the folder option the checkbox to show hidden files and folder was checked. Later I resolve this problem by directly modifying the registry : HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced\Folder\Hidden\SHOWALL and setting the value of the ‘CheckedValue‘ as 1

written by Om