Monday, June 15, 2015

AutoHotkey - Improved Script

Here's an automated GUI test script using objects, coordinates, values, for each loop and if condition.

Numpad1 & Numpad2::

IfWinExist TradingApp
{

;;Activate window
WinActivate

;Create coordinates data
CoList :={}
CoListCount = 6

Loop, % CoListCount 
   CoList[A_Index] := {} 

CoList.1 := {X: "268", Y: "189", Val: ""}
CoList.2 := {X: "255", Y: "111", Val: ""}
CoList.3 := {X: "441", Y: "155", Val: ""}
CoList.4 := {X: "146", Y: "396", Val: "Risky Accounts"}
CoList.5 := {X: "500", Y: "249", Val: "27029445{Enter}"}
CoList.6 := {X: "500", Y: "249", Val: "27029000-28029000{Enter}"}


for each, co in CoList 


    Sleep 1000

    val := co.Val
    MouseClick,Left,co.X, co.Y
    if(val)
    {
      Send, %val%
    }
}
}

Return

Esc::ExitApp
Return

AutoHotkey - Some simple tips.


Say you want to perform series of sequential clicks. The best way to do this with repetition is to store all the co-ordinates in an object, then use a for loop to perform those clicks.

The example below, moves the mouse pointer to the co-ordinates I defined in the Point object (you ca n name it anything you wish).

Point :=   Object(138,168,485,690,733,240)

For x, y in Point
{
  Sleep 2000 ;its too fast
  MouseMove, %x%, %y%
}

MsgBox, The script ended...thanks.

I think the code is self explainatory.

Using objects and properties.

ProfileList := {}
 ProfileCount = 2 

 Loop, % ProfileCount 
   ProfileList[A_Index] := {} 

 ProfileList.1.Name := "MyName"
 ProfileList.1.Password := "MyPassword"
 ProfileList.1.Server := "TheServer" 

 ProfileList.2.Name := "AnotherName" 
ProfileList.2.Password := "AnotherPassword" 
ProfileList.2.Server := "AnotherServer" 

 for each, item in ProfileList 
    MsgBox, % "Name: " item.name "`nPassword: " item.Password "`nServer: " item.server
 }

Sunday, June 14, 2015

AutoHotkey - Magical GUI testing

I've been smitten by AutoHotkey, which is an open source scripting framework which allows you to define to automate your inputs and mouse clicks simply assigning them to some key strokes (it's actually much more than that, but enough introduction)

Here's what i wish to do. I'll simply open up my app. Then I want to type inputs in all of my text boxes and finally click the button.

I'll write the auto hot key script for this with the input values and its done.

Here's what my app looks like:

Here's my .ahk script (explanations later)

Numpad0 & Numpad2:: ;starts when these 2 are pressed

IfWinExist Trading Application
{
    WinActivate

    ;Enter for MF symbol
Sleep 2000 ;sleep for 2 seconds
Click, 81, 98 ;now clicks
Send, MFC02

;Action
Sleep 2000 ;sleep for 2 seconds
Click, 214, 96 ;now clicks
Send, BUY

;Amount
Sleep 2000 ;sleep for 2 seconds
Click, 79, 151 ;now clicks
Send, 5000

;Trade Date
Sleep 2000 ;sleep for 2 seconds
Click, 239, 150 ;now clicks
Send, 13/06/2015

;Verify Trade
Sleep 2000 ;sleep for 2 seconds
Click, 257, 199 ;now clicks
}

return ;end

Escape::
ExitApp
Return

When you run the script and press Numpad 0 followed by 2, the Trading Application window (if open in background) shows up in the front (WinActivate command). Then after 2 seconds (Sleep command), the mouse pointer moves and clicks (using Click command with location) at the MF symbol textbox, and "MFC02" is typed (Send command). This happens for all other textboxes. Then the button is clicked and a message box appears (from the program).

I got all the co-ordinates using the AutoIt3 window spy (which gets installed when you install AutoHotkey). I used the 'Default' mouse co-ordinates.



Return command signals the end of the program. On pressing Esc key the app will exit (it's useful if something nasty happens because of your script)

So, i think you must have got the hang of it more or less. There is certainly a great way to improve this example (eg. use variables for data and read the values from a textfile in a loop). Just try it out and have fun!

Tuesday, April 28, 2015

Crosstalk between modules : Query providers and Event Managers

*Pub-sub mechanism in an LOB application  
 //Account class  
 AccountModule.AccountSearchVM  
 {  
 //property  
      public AccountViewModel SelectedAccount  
      {  
           get...  
           set  
           {  
                //other code here  
                //raise the event when account is selected  
                SelectedAccountEventArgs accountSelectedEvent = new SelectedAccountEventArgs();  
                EventManager.Current.PublishEvent<SelectedAccountEventArgs>(this, accountSelectedEvent);  
           }  
      }  
 }  
 //Positions class (show positions in right pane for selected account in the left pane [in AccountModule]  
 PositionsModule.PositionsVM  
 {  
      //ctor  
      PositionsVM()  
      {  
           ApplicationContext.Current.SubscribeToEvent<SelectedAccountEventArgs>(this, SelectedAccountChanged);  
           //Do something with SelectedAccountChanged method then, make use of SelectedAccountEventArgs  
      }  
 }  
--------------------------------------------------------
//QueryProviders  
 //This code is in Framework module  
 public void RegisterQueryProvider<QueryType>(QueryType query) where QueryType : IQueryProvider  
 {  
      Type type = typeof(QueryType);  
      //QueryManager is a singleton class which manages a dictionary of Dictionary<Type, IQueryProvider>  
      //instance is then added  
      //internal bool AddQuery<QueryType>(QueryType query) where QueryType : IQueryProvider  
   /* {  
           bool ret = false;  
           Type type = typeof(QueryType);  
           if (!m_queries.ContainsKey(type))  
           {  
                m_queries.Add(type, query);  
                ret = true;  
           }  
           return ret;  
      } */  
      if (!QueryManager.Current.AddQuery<QueryType>(query))  
      {  
           throw new Exception("Query is already registered!!.");  
      }  
 }  
 //inside Plugin initialze method, pass the instance of the view model  
 apphost.RegisterQueryProvider<ISelectedAccountQuery>(m_viewModel);  

Tuesday, February 17, 2015

Visitor pattern


Code:
class MutualFundOrderProvider
{
 private Dictionary<string,string> GetKeyValues(MutualFundOrderInfo info)
 {
  ...
 }
}

class GICOrderProvider
{
 private Dictionary<string,string> GetKeyValues(GICOrderInfo info)
 {
  ...
 }
}

class EquityOrderProvider
{
 private Dictionary<string,string> GetKeyValues(EquityOrderInfo info)
 {
  ...
 }
}

//visitor approach
//Create interface
interface IKeyValueComputer
{
 Dictionary<string,string> GetKeyValues(EquityOrderInfo info);
 Dictionary<string,string> GetKeyValues(GICOrderInfo info);
 Dictionary<string,string> GetKeyValues(MutualFundOrderInfo info)
}

//implementation
class KeyValueComputer:IKeyValueComputer
{
 //all implementations...
}

//another interface
interface IComputeKeyValues
{
 Dictionary<string,string> ComputeKeyValues(IKeyValueComputer keyvalcomp)
}

class EquityOrderInfo: IComputeKeyValues
{
 public Dictionary<string,string> ComputeKeyValues(IKeyValueComputer keyvalcomp)
 {
  return keyvalcomp.GetKeyValues(this);
 }
}

//MutualFundOrderProvider
class MutualFundOrderProvider
{
 public void Translate(MutualFundOrderInfo info)
 {
  IKeyValueComputer keyvalcomp=new KeyValueComputer();
  info.ComputeKeyValues(keyvalcomp);
 }
}

Sunday, February 15, 2015

Tuesday, February 10, 2015

Using Channel Factory

Wrapping CreateChannel for WCF calls:


Code:
//view model
public void GetEmployees()
{
 var emp = ServiceFactory.GetService<IEmployeeService>();
}

//IServiceFactory
public interface IServiceFactory
{
 T GetService<T>();
}

//ServiceFactory class
public static class ServiceFactory: IServiceFactory
{
 public T GetService<T>()
 {
  T svc = default(T);
        ChannelFactory<T> factory = new ChannelFactory<T>(typeof(T).FullName);

        //any other logic or conditions you want
        //...

        svc = factory.CreateChannel();

        return svc; 
 }
}

Thursday, February 5, 2015

Scrap One


WCF:

1. Decide which binding to use.
2. Tracing (why, how)
Use system.servicemodel.messagelogging under then add listener, output it to svclog and open the file in Traceviewer.

http://www.easyvectors.com/browse/design-elements1/design-elements-grey-spiral-free-vector

http://cdn.vectorstock.com/i/composite/71,57/abstract-icons-and-logos-vector-147157.jpg

http://t2.ftcdn.net/jpg/00/68/58/99/240_F_68589944_rV9FN8Iu2jAfl1zu3WghBU5edYYyiXoP.jpg

http://veerle.duoh.com/design/article/illustrator_full_spectrum_spirograph

http://veerle.duoh.com/design/article/photoshop_vintage_effect

http://veerle.duoh.com/design/article/creating_a_geometric_star_in_illustrator

http://veerle.duoh.com/design/article/colorful_pattern_masking_in_illustrator1

Photography ---

http://photography.tutsplus.com/tutorials/7-posing-techniques-for-non-models--photo-15608

http://www.iheartfaces.com/2012/03/photography-posing-mistakes-tutorial/

See Step 8 for colouring:
http://designinstruct.com/drawing-illustration/make-watercolor-and-marker-style-portraits-with-illustrator/

VS Extensions

https://visualstudiogallery.msdn.microsoft.com/5396fa4a-d638-471b-ac3d-671ccd2ea369 -- a must
https://visualstudiogallery.msdn.microsoft.com/d4ab8421-147f-4416-8038-d5f7fdcf6a56
https://visualstudiogallery.msdn.microsoft.com/00ec88c2-1553-47d2-8170-3c5baa0c6e44
https://visualstudiogallery.msdn.microsoft.com/dfcb2438-180c-4f8a-983b-62d89e141fe3
https://visualstudiogallery.msdn.microsoft.com/fb5badda-4ea3-4314-a723-a1975cbdabb4
https://visualstudiogallery.msdn.microsoft.com/0e33cb22-d4ac-4f5a-902f-aff5177cc94d
https://visualstudiogallery.msdn.microsoft.com/ab43a471-b840-4d81-ad6f-c9f350cfcd16

interesting--
https://visualstudiogallery.msdn.microsoft.com/d5cd6aa1-57a5-4aaa-a2be-969c6db7f88a
http://blogs.msdn.com/b/visualstudio/archive/2010/07/29/walkthrough-creating-a-custom-start-page-part-1.aspx

http://stackoverflow.com/questions/4144778/get-properties-and-values-from-unknown-object

Thursday, January 15, 2015

Client side threading in WPF (without Dispatcher)

Create a TaskItem class with 4 props:
1. Task name (string)
2. Action (Action)
3. int Priority
4. State (object)

Then create a static TaskProcessor class:
* has a dictionary of TaskItems as value and string as key
* static 'Current' property like this.

private TaskProcessor _current;  
 private int _threadID;  
 public static TaskProcessor Current  
 {  
   get  
   {  
      if (_current == null)  
      {  
        //lock to make thread safe  
        lock (typeof(TaskProcessor))  
        {  
           //create a new instance  
           _current = new TaskProcessor();  
           _threadID = Thread.CurrentThread.ManagedThreadId;  
        }  
      }
      return _current;  
   }  

Create a method in TaskProcessor class like this:

public void AddTaskInQueue(string taskName, Action<object> action, object state, int priority)  
 {  
   lock (this)  
   {  
      TaskItem ti = new TaskItem(this) { TaskName = taskName, Action = action, State = state, Priority = priority };  
      TaskItem currentTask = null;  
      if (_tasks.TryGetValue(taskName, out currentTask))  
      {  
        _tasks[taskName] = ti;  
      }  
      else  
      {  
        _tasks.Add(taskName, ti);  
      }  
      // Cancel the previous task.  
      if (currentTask != null)  
      {  
        //not in scope of this post
        currentTask.CancelTask();  
      }  
      // Identify and Cancel all other lower or equal priority tasks.  
      // Priority = 0 tasks are independent tasks  
      if (priority != 0)  
      {  
        var lowPriorityTasks = (from task in m_queue  
                       where task.Value.Priority > priority && task.Value.TaskName != taskName  
                       select task);  
        foreach (KeyValuePair<string, TaskItem> task in lowPriorityTasks)  
        {  
           task.Value.CancelTask();  
        }  
      }  
      ti.StartTheTask();  
   }  
 }  


Usage in code (upto what we have done till now) will be like this:

TaskProcessor.Current.AddTaskInQueue("SomeTaskName", action =>  
       {  
         //make call to svc to get data  
         ServiceResponse results = GetDataFromService();  
         //update UI after we get the results..  
         //this is covered later in this blog  
       }, null, 0);  



TaskItem class code:

private TaskProcessor _taskprocessor;  
     private SynchronizationContext _synchronizer;  

public TaskItem(TaskProcessor taskprocessor)
        {
            _taskprocessor taskprocessor;
            _synchronizer= new TaskSynchronizationContext(SynchronizationContext.Current);

        }

     public void StartTheTask()  
     {  
       ThreadPool.QueueUserWorkItem(state =>  
       {  
         TaskItem ti = (TaskItem)state;  
         try  
         {  
           ti._taskprocessor.StartTask(ti);  
           ti._taskprocessor.SynchronizationContextValue(ti._synchronizer);  
           ti.ExecuteTask();  
         }  
         catch (Exception ex)  
         {  
           //log ex  
         }  
         finally  
         {  
           try  
           {  
             ti._taskprocessor.EndTask(ti);  
           }  
           finally  
           {  
             ti._taskprocessor.SynchronizationContextValue(null);  
           }  
         }  
       }, this);  
     }  
     private void ExecuteTask()  
     {  
       if (Action != null)  
       {  
         Action.Invoke(State);  
       }  
     }  

Create a TaskProcessorSynchronizationContext derived from SynchronizationContext class. Override all the methods where the sync object got from the ctor and call the base methods.

 public class TaskSynchronizationContext : SynchronizationContext  
   {  
     private SynchronizationContext _synctx;  
     public TaskSynchronizationContext(SynchronizationContext synctx)  
     {  
       _synctx = synctx;  
       SetSynchronizationContext(synctx);  
     }  
     public override SynchronizationContext CreateCopy()  
     {  
       return _synctx.CreateCopy();  
     }  
     //..override all methods as above  
     public override void Post(SendOrPostCallback d, object state)  
     {  
       _synctx.Post(d, state);  
     }  
     public override void Send(SendOrPostCallback d, object state)  
     {  
       string status = "Success";  
       string tid = System.Threading.Thread.CurrentThread.ManagedThreadId.ToString();  
       try  
       {  
         _synctx.Send(x =>  
         {  
           object[] temp = (Object[])x;  
           try  
           {  
             d.Invoke(temp[1]);  
           }  
           finally  
           {  
           }  
         }, state);  
       }  
       catch (Exception)  
       {  
         status = "Failed";  
       }  
       finally  
       {          
       }  
     }  
     public override int Wait(IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout)  
     {  
       return _synctx.Wait(waitHandles, waitAll, millisecondsTimeout);  
     }  
   }  

Now the usage changes to this:

TaskProcessor.Current.AddTaskInQueue("SomeTaskName", action =>  
     {  
       //make call to svc to get data   
       ServiceResponse results = GetDataFromService();  
       //update UI after we get the results..   
       TaskProcessor.Current.Synchronizer.Send(uiAction =>  
       {  
         ProcessResultsAndUpdateUI(results);  
       }, null);  
     }, null, 0);  



Monday, January 12, 2015

T4 Template

<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Collections.Generic" #>
using System;
using MVN.Framework.Views;

namespace Templates
{

//
    public class <#= this.ViewClass #> : IView
    {
        public void Show()
        {
            throw new NotImplementedException();
        }

<#

var fields = GetFields(@"d:\friends.txt");
foreach (var item in fields)
{#>
public string <#= item #> { get; set; }
<#}#>

    }
}
<#+
string ViewClass = "MyClass";
#>
<#+
private List GetFields(string fileName)
    {
        List lines = new List();

        using (StreamReader r = new StreamReader(fileName))
        {
            string line;
            while ((line = r.ReadLine()) != null)
            {
                lines.Add(line);
            }
        }
return lines;
    }
#>

Thursday, January 8, 2015

Creating a parallel task framework


using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Text;  
 using System.Threading;  
 using System.Runtime.Remoting.Messaging;  
 namespace UnderstandingThreading  
 {  
   public class ParallelProcessor2  
   {  
     List<CallContext> _contexts;  
     List<Thread> _workers;  
     private ManualResetEvent _manualWait = new ManualResetEvent(true);  
     public ParallelProcessor2()  
     {  
       _workers = new List<Thread>();  
       _contexts = new List<CallContext>();  
     }  
     public void AddTask(Action taskCallback, string taskname)  
     {  
       lock (this)  
       {  
         //handle abort condition  
         int threadCnt = _contexts.Count;  
         //_contexts.Add(CallContext.SetData(threadCnt.ToString(), this););  
         //Create TaskItem  
         TaskItem tsk = new TaskItem(threadCnt, taskCallback, taskname);  
         //Spawn new thread  
         Thread t = new Thread(Consume);  
         object o = new object();  
         o = tsk;  
         if (_workers.Count == 0)  
           _manualWait.Reset();  
         _workers.Add(t);  
         t.Start(o);  
       }  
     }  
     private void Consume(object item)  
     {  
       object temp = (object)item;  
       TaskItem tsk = (TaskItem)temp;  
       //to do: code to fetch from contexts array by passing identifier name  
       try  
       {  
         tsk.ExecuteTaskItem();  
       }  
       catch (Exception ex)  
       {  
         //create a method to report exception in call context  
         //use call context to report exception  
       }  
       finally  
       {  
         //removing completed threads  
       }  
     }  
   }  
   public class TaskItem  
   {  
     private Action _taskCallback;  
     private string _taskName;  
     private int _taskCounter;  
     public TaskItem(int taskCounter, Action taskCallback, string taskname)  
     {  
       _taskCounter = taskCounter;  
       _taskCallback = taskCallback;  
       _taskName = taskname;  
     }  
     internal void ExecuteTaskItem()  
     {  
       _taskCallback();  
     }  
   }  
 }  

Wednesday, January 7, 2015

Logging: Create a wrapper around MS EntLib Logging

Create a LogManager static class in your framework.
Logger, LogEntry, ShouldLog are all provided by EntLib
LogCategory is an enum which can describe from which layer this log was generated.

public static class LogManager  
 {  
 public static void LogMessage(LogCategory category, LogPriority priority, string message)  
 {  
   string eventCategory = category.ToString();  
   LogEntry le = new LogEntry();  
   le.Priority = (int)priority;  
   le.Categories.Add(eventCategory);  
   if (Logger.ShouldLog(le))  
   {  
      le.TimeStamp = DateTime.Now;  
      le.Message = message;  
      le.ExtendedProperties.Add("Event Source:", eventCategory);  
      if (category == LogCategory.SystemErrorTrace || category == LogCategory.FatalErrorTrace)  
      {  
        le.Severity = System.Diagnostics.TraceEventType.Error;  
      }  
      try  
      {  
        Logger.Write(le);  
      }  
      catch (Exception)  
      {  
      }  
   }  
  }  
 }  

If you need to log an entity as XML:

public static void LogEntity(LogCategory category, LogPriority priority, object valueToLog, string logMessage)  
 {  
   string eventCategory = category.ToString();  
   LogEntry le = new LogEntry();  
   le.Priority = (int)priority;  
   le.Categories.Add(eventCategory);  
   if (Logger.ShouldLog(le))  
   {  
      using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))  
      {  
        if (valueToLog != null)  
        {  
           try  
           {  
             stringWriter.WriteLine(logMessage);  
             // Serailize the input object to stream  
             XmlSerializer xmlSerializer = new XmlSerializer(valueToLog.GetType());  
             xmlSerializer.Serialize(stringWriter, valueToLog);  
           }  
           catch (Exception ex)  
           {  
             stringWriter.WriteLine("Something wrong"+ex.Message);  
           }  
        }  
        else  
        {  
           stringWriter.WriteLine("Entity object = null");  
        }  
        try  
        {  
           le.TimeStamp = DateTime.Now;  
           le.ExtendedProperties.Add("Event Source:", eventCategory);  
           le.Message = stringWriter.ToString();  
           if (category == LogCategory.SystemErrorTrace || category == LogCategory.FatalErrorTrace)  
           {  
             le.Severity = System.Diagnostics.TraceEventType.Error;  
           }  
           Logger.Write(le);  
        }  
        catch (Exception)  
        {  
        }  
      }  
   }  
 }  

How Logging disabling works:
Below is snippet from web.config file:

<logFilters>  
 <add categoryFilterMode="AllowAllExceptDenied" type="Microsoft.Practices.EnterpriseLibrary.Logging.Filters.CategoryFilter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=2.0.0.0, Culture=neutral, PublicKeyToken=7fa4cc4c62ff1809"  
 name="Category Filter">  
 <categoryFilters>  
  <!--<add name="SourceTrace" />  
  <add name="ManagerTrace" />  
  <add name="ProviderTrace" />  
  <add name="InformationTrace" />  
  <add name="ServiceTrace" />-->  
 </categoryFilters>  
 </add>  
 </logFilters>  
 <categorySources>  
 ..  
 </categorySources>  


Logging will be disabled only when a category filter is commented. tracingEnabled="false" does not work.

Tuesday, January 6, 2015

Caching: Creating a wrapper around MS EntLib Caching


These are the layers through which we have sequential calls:
Client > ServiceImplementation > Manager > Provider > DataSource

A provider may call a datasource directly. Providers can also call Managers to get requested info.

Example:
* EmployeeInformationProvider requires AsianEmployees. Hence it calls EmployeeManager.GetAsianEmployees().
* EmployeeManager.GetAsianEmployees() in turn first tries to get cached asian employees else it  will get from the datasource. Here's the code:
//Inside EmployeeManager.cs  
 public List<Employee> GetAsianEmployees()  
 {  
  return CacheProvider.CachedAsianEmployees();  
 }  
 //Inside CacheProvider.cs  
 public static CachedAsianEmployees()  
 {  
  List<Employee> employees = CacheUtility.RetrieveItem<List<Employee>>("AsianEmployeesPolicy", "AsianEmployees");  
 }
...where
AsianEmployeesPolicy = policy name
AsianEmployees = key name  

Now the CacheUtility class:
public static T RetrieveItem<T>(string policy, string keyname)  
 {  
   T res = default(T);  
      //create a tag named '<policy name="AsianEmployeesPolicy">' in config file.  
      //inside that place a provider tag which has the filename and assembly. It will have description and expiry time subtags  
   //read policy tag from config file  
   //CachingPolicy is a class with properties such as Name, ProviderInfo.  
   CachingPolicy p = CachingPolicyUtility.GetPolicy(policy);  
   if (p != null)  
   {  
     //inner implementation is upto you. Basically what this code does is initiate an activator.getinstance of the full file name with assembly that  
      //we had provided in the policy tag in our config.  
      //that provider file has certain methods like RetrieveItem which we need to invoke  
      //providers can be SlidingExpirationCacheProvider, StaticExpirationCacheProvider or SqlDependencyCacheProvider all having base type CachingProvider  
      CachingProvider provider = (CachingProvider)ProviderLoader.LoadProvider(p.ProviderInfo, typeof(CachingProvider));  
      res = (T)provider.RetrieveItem(keyname);  
   }   
   return res;  
 }  

Lets see an implementation of SlidingExpCacheProvider
Inherit some base class with operations such as StoreItem, RetrieveItem, ExpiryTime property in SlidingExpCacheProvider like SlidingExpCacheProvider: BaseCacheProvider

public class SlidingExpCacheProvider: BaseCacheProvider  
 {  
 void Init()  
 {  
 //get expiry time etc..in some private variable to use in GetExpTime property here ..  
 //also set a default time if exp time was not provided...  
 }  
 //override as necessary or stick to default implementation  
 public override object RetrieveItem(string key)  
 {  
 //CacheManager is from MS.EntLib.Caching  
   CacheManager cacheManager = CacheFactory.GetCacheManager();  
   return cacheManager[key];  
 }  
 public override void StoreItem(string key, object item)  
 {  
   double time = Convert.ToDouble(_exptime, CultureInfo.InvariantCulture);  
   //CacheManager is from MS.EntLib.Caching  
   CacheManager cacheManager = CacheFactory.GetCacheManager();  
   cacheManager.Add(key, item, CacheItemPriority.Normal, null, new SlidingTime(TimeSpan.FromMinutes(time)));  
 }  
 }

StaticExpCacheProvider is very similar to SlidingExpCacheProvider with the following differences:
*//Add item to cache 
cacheManager.Add(key, item, CacheItemPriority.Normal, null, new AbsoluteTime(DateTime.Now.AddSeconds(time)));
* Sliding exp: Cached element will expire after specified expiry time elasped after last access.
* Static: Element expires after the specified exp time. 

Pointers on using Moles for unit testing


Scenario 1

TestContext tContext = (TestContext)TestContextUtility.GetData(Constants.TestContextKey);

TestContextUtility is a class which returns an object when GetData property is accessed (it also expects a string parameter). You want to mock this using moles.

Solution:

TestContext ctx = new TestContext();  
MTestContextUtility.GetDataString = (s) => { return ctx; };  

...where MTestContextUtility is generated by Moles, s is the expected string parameter variable (no need to declare this anywhere) and the method body returns TestContext object.

Scenario 2
ValResult res = CommonValidation.CreateValResult(settings, tContext.Info, true);
CreateValResult method returns a ValResult object. It accepts 3 parameters, the 3rd parameters being boolean. You want to return a mock ValResult and bypass the logic in CreateValResult

Solution:
MCommonValidation.CreateValResultSettingsInfoBoolean = (d, u, p) =>  
 {  
   return  
      new ValResult  
      {  
        ErrorMessage = "this is an error",  
        ErrorNumber = "123"  
      };  
 };  


...where MCommonValidation is generated by Moles, d, u, p are variables and method returns a mock ValResult object. You can return this object based on input conditions too.

Scenario 3
When you need to mock a private method:

public class EmployeeProvider  
 {  
 public CreateEmployeeContext  
 {  
  dbemp = ..//get from database  
  //then parse  
  var parsedEmployee = ParseEmployee(dbemp);  
 }  
 }  


EmployeeProvider class provides an employee through public method CreateEmployeeContext  

//private method which parses db employee to employee entity  
 private Employee ParseEmployee(DBEmployee emp)  
 {  
  Employee e = new Employee();  
  e.Name = emp.Name;  
 }  


ParseEmployee is the private method which we wish to mock

Solution:
MEmployeeProvider.AllInstances.ParseEmployeeDBEmployee = (a,b) => { return new Employee{ Name="test" };};  


...where a is DBEmployee and b is Employee (return type)