<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Gal Segal&#039;s Blog</title>
	<atom:link href="http://gal-segal.com/feed" rel="self" type="application/rss+xml" />
	<link>http://gal-segal.com</link>
	<description>Thoughts of a programmer with a soul</description>
	<lastBuildDate>Sat, 13 Apr 2013 13:31:06 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=4.2.35</generator>
	<item>
		<title>GoodBye WordPress, Hello Jekyll</title>
		<link>http://gal-segal.com/uncategorized/goodbye-wordpress-hello-jekyll</link>
		<comments>http://gal-segal.com/uncategorized/goodbye-wordpress-hello-jekyll#comments</comments>
		<pubDate>Sat, 13 Apr 2013 09:04:58 +0000</pubDate>
		<dc:creator><![CDATA[Gal Segal]]></dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://gal-segal.com/?p=526</guid>
		<description><![CDATA[I decided to move my blog from WordPress to Jekyll. My new blog is here: http://gal-segal.net.]]></description>
				<content:encoded><![CDATA[<p>I decided to move my blog from WordPress to <a href="http://jekyllbootstrap.com/">Jekyll</a>. My new blog is here: <a href="http://gal-segal.net">http://gal-segal.net</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://gal-segal.com/uncategorized/goodbye-wordpress-hello-jekyll/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Unit Testing Log4Net Wrapper</title>
		<link>http://gal-segal.com/c-sharp/unit-testing-log4net-wrapper</link>
		<comments>http://gal-segal.com/c-sharp/unit-testing-log4net-wrapper#comments</comments>
		<pubDate>Mon, 10 Dec 2012 05:31:49 +0000</pubDate>
		<dc:creator><![CDATA[Gal Segal]]></dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[c#]]></category>

		<guid isPermaLink="false">http://gal-segal.com/?p=499</guid>
		<description><![CDATA[Log4Net is an industry standard for logging. Almost every developer uses it in some point in his/hers professional life. I am no exception, and I needed to write a LogManager wrapper and unit test it.]]></description>
				<content:encoded><![CDATA[<p><a title="Log4Net" href="http://logging.apache.org/log4net/" target="_blank">Log4Net</a> is an industry standard for logging. Almost every developer uses it in some point in his/hers professional life. I am no exception, and I needed to write a LogManager wrapper and unit test it.</p>
<p>The purpose of the unit test is to check if the logger logs a message or not, depending on the level of the threshold configured. It should also write exception messages when given.  The idea is to use Log4Net <a title="MemoryAppender" href="http://logging.apache.org/log4net/release/sdk/log4net.Appender.MemoryAppender.html" target="_blank">MemoryAppender</a> and test the output.</p>
<p>Here is the code (I am using <a title="Shouldly" href="http://shouldly.github.com/" target="_blank">Shouldy</a> for assertion), use it at will:</p>
<pre class="brush: csharp; title: ; notranslate">
public interface ILogManager
{
 void Debug(string message, Exception ex = null);
 void Info(string message, Exception ex = null);
 void Warn(string message, Exception ex = null);
 void Error(string message, Exception ex = null);
 void Fatal(string message, Exception ex = null);
}

public class LogManager : ILogManager
{
 private readonly ILog _logger;
 private bool _isDebugEnabled;
 private bool _isInfoEnabled;
 private bool _isWarnEnabled;
 private bool _isErrorEnabled;
 private bool _isFatalEnabled;

public LogManager()
 {
 _logger = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
 XmlConfigurator.Configure();
 SetLoggingLevelConstants();
 }

public LogManager(ILog logger)
 {
 _logger = logger;
 SetLoggingLevelConstants();
 }

public void Debug(string message, Exception ex = null)
 {
 Log(_isDebugEnabled, _logger.Debug, message, ex);
 }

public void Info(string message, Exception ex = null)
 {
 Log(_isInfoEnabled, _logger.Info, message, ex);
 }

public void Warn(string message, Exception ex = null)
 {
 Log(_isWarnEnabled, _logger.Warn, message, ex);
 }

public void Error(string message, Exception ex = null)
 {
 Log(_isErrorEnabled, _logger.Error, message, ex);
 }

public void Fatal(string message, Exception ex = null)
 {
 Log(_isFatalEnabled, _logger.Fatal, message, ex);
 }

private void SetLoggingLevelConstants()
 {
 _isDebugEnabled = _logger.IsDebugEnabled;
 _isInfoEnabled = _logger.IsInfoEnabled;
 _isWarnEnabled = _logger.IsWarnEnabled;
 _isErrorEnabled = _logger.IsErrorEnabled;
 _isFatalEnabled = _logger.IsFatalEnabled;
 }

private static void Log(bool enabled, Action&lt;string, Exception&gt; logAction, string message, Exception exception = null)
 {
 if (!enabled)
 return;
 logAction(message, exception);
 }
}

[TestClass]
public class LogManagerShould
{
 private MemoryAppender _appender;
 private const string LOG_MESSAGE = &quot;test message&quot;;
 private readonly Exception _exception = new Exception(&quot;test exception&quot;);

[TestMethod]
 public void LogDebugMessagesWhenDebugEnabled()
 {
 //arrange
 var logManager = GetLogManager(Level.Debug);

//act
 logManager.Debug(LOG_MESSAGE);

//assert
 GetLogMessage().ShouldBe(LOG_MESSAGE);
 }

[TestMethod]
 public void LogDebugMessagesWithExceptionWhenDebugEnabled()
 {
 //arrange
 var logManager = GetLogManager(Level.Debug);

//act
 logManager.Debug(LOG_MESSAGE, _exception);

//assert
 GetLogMessage().ShouldBe(LOG_MESSAGE);
 GetLogException().ShouldBe(GetLogExceptionMessage());
 }

[TestMethod]
 public void NotLogDebugMessagesWhenDebugDisabled()
 {
 //arrange
 var logManager = GetLogManager(Level.Info);

//act
 logManager.Debug(LOG_MESSAGE);

//assert
 GetLogMessage().ShouldBe(null);
 }

[TestMethod]
 public void LogInfoMessagesWhenInfoEnabled()
 {
 //arrange
 var logManager = GetLogManager(Level.Info);

//act
 logManager.Info(LOG_MESSAGE);

//assert
 GetLogMessage().ShouldBe(LOG_MESSAGE);
 }

[TestMethod]
 public void LogInfoMessagesWithExceptionWhenInfoEnabled()
 {
 //arrange
 var logManager = GetLogManager(Level.Info);

//act
 logManager.Info(LOG_MESSAGE, _exception);

//assert
 GetLogMessage().ShouldBe(LOG_MESSAGE);
 GetLogException().ShouldBe(GetLogExceptionMessage());
 }

[TestMethod]
 public void NotLogInfoMessagesWhenInfoDisabled()
 {
 //arrange
 var logManager = GetLogManager(Level.Warn);

//act
 logManager.Info(LOG_MESSAGE);

//assert
 GetLogMessage().ShouldBe(null);
 }

[TestMethod]
 public void LogWarnMessagesWhenWarnEnabled()
 {
 //arrange
 var logManager = GetLogManager(Level.Warn);

//act
 logManager.Warn(LOG_MESSAGE);

//assert
 GetLogMessage().ShouldBe(LOG_MESSAGE);
 }

[TestMethod]
 public void LogWarnMessagesWithExceptionWhenWarnEnabled()
 {
 //arrange
 var logManager = GetLogManager(Level.Warn);

//act
 logManager.Warn(LOG_MESSAGE, _exception);

//assert
 GetLogMessage().ShouldBe(LOG_MESSAGE);
 GetLogException().ShouldBe(GetLogExceptionMessage());
 }

[TestMethod]
 public void NotLogWarnMessagesWhenWarnDisabled()
 {
 //arrange
 var logManager = GetLogManager(Level.Error);

//act
 logManager.Warn(LOG_MESSAGE);

//assert
 GetLogMessage().ShouldBe(null);
 }

[TestMethod]
 public void LogErrorMessagesWhenErrorEnabled()
 {
 //arrange
 var logManager = GetLogManager(Level.Error);

//act
 logManager.Error(LOG_MESSAGE);

//assert
 GetLogMessage().ShouldBe(LOG_MESSAGE);
 }

[TestMethod]
 public void LogErrorMessagesWithExceptionWhenErrorEnabled()
 {
 //arrange
 var logManager = GetLogManager(Level.Error);

//act
 logManager.Error(LOG_MESSAGE, _exception);

//assert
 GetLogMessage().ShouldBe(LOG_MESSAGE);
 GetLogException().ShouldBe(GetLogExceptionMessage());
 }

[TestMethod]
 public void NotLogErrorMessagesWhenErrorDisabled()
 {
 //arrange
 var logManager = GetLogManager(Level.Fatal);

//act
 logManager.Error(LOG_MESSAGE);

//assert
 GetLogMessage().ShouldBe(null);
 }

[TestMethod]
 public void LogFatalMessagesWhenFatalEnabled()
 {
 //arrange
 var logManager = GetLogManager(Level.Fatal);

//act
 logManager.Fatal(LOG_MESSAGE);

//assert
 GetLogMessage().ShouldBe(LOG_MESSAGE);
 }

[TestMethod]
 public void LogFatalMessagesWithExceptionWhenFatalEnabled()
 {
 //arrange
 var logManager = GetLogManager(Level.Fatal);

//act
 logManager.Fatal(LOG_MESSAGE, _exception);

//assert
 GetLogMessage().ShouldBe(LOG_MESSAGE);
 GetLogException().ShouldBe(GetLogExceptionMessage());
 }

[TestMethod]
 public void NotLogFatalMessagesWhenOff()
 {
 //arrange
 var logManager = GetLogManager(Level.Off);

//act
 logManager.Fatal(LOG_MESSAGE);

//assert
 GetLogMessage().ShouldBe(null);
 }

private ILogManager GetLogManager(Level level)
 {
 _appender = new MemoryAppender
 {
 Name = &quot;Unit Testing Appender&quot;,
 Layout = new log4net.Layout.PatternLayout(&quot;%message&quot;),
 Threshold = level
 };
 _appender.ActivateOptions();

var root = ((Hierarchy)log4net.LogManager.GetRepository()).Root;
 root.AddAppender(_appender);
 root.Repository.Configured = true;

var rootLogger = log4net.LogManager.GetLogger(&quot;root&quot;);
 return new LogManager(rootLogger);
 }

private string GetLogMessage()
 {
 if (_appender.GetEvents().Length == 0)
 return null;
 var logEvent = _appender.GetEvents()[0];
 return logEvent.MessageObject.ToString();
 }

private string GetLogException()
 {
 if (_appender.GetEvents().Length == 0)
 return null;
 var logEvent = _appender.GetEvents()[0];
 return logEvent.ExceptionObject.ToString();
 }

private string GetLogExceptionMessage()
 {
 return string.Format(&quot;{0}: {1}&quot;, _exception.GetType().FullName, _exception.Message);
 }
}
</pre>
<p>Happy coding!</p>
]]></content:encoded>
			<wfw:commentRss>http://gal-segal.com/c-sharp/unit-testing-log4net-wrapper/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Simple Process Manager</title>
		<link>http://gal-segal.com/c-sharp/simple-process-manager</link>
		<comments>http://gal-segal.com/c-sharp/simple-process-manager#comments</comments>
		<pubDate>Tue, 31 Jan 2012 08:00:46 +0000</pubDate>
		<dc:creator><![CDATA[Gal Segal]]></dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[c#]]></category>

		<guid isPermaLink="false">http://gal-segal.com/?p=458</guid>
		<description><![CDATA[It is a common matter to have an operation in the server that requires few steps. Sometimes it is necessary that all the steps will complete successfully, and if one fails, a rollback should be made. SQL has the transaction term to support this kind of situation, and I'm about to show how it can be done in code.]]></description>
				<content:encoded><![CDATA[<p>It is a common matter to have an operation in the server that requires few steps. Sometimes it is necessary that all the steps will complete successfully, and if one fails, a rollback should be made. SQL has the transaction term to support this kind of situation, and I&#8217;m about to show how it can be done in code.</p>
<p>My role of thumb for this kind of infrastructure is that the code should be easy to use, flexible enough for many different cases, and relays on a default behavior that can be overridden when needed.</p>
<p>Now lets think about a process of this kind:</p>
<h3>The Single Step</h3>
<ol>
<li>A process is created from small steps, each one is responsible for a single task.</li>
<li>Each step should get the necessary input data and manipulate it.</li>
<li>Each step should know how to execute its task. (Daa..)</li>
<li>Each task should have the knowledge  how to rollback this task.</li>
<li>Each step should be able to make several retry attempts for the execution and rollback.</li>
<li>Each step should report if the action was successful or failed.</li>
</ol>
<div></div>
<div>The base class for the step has the default behavior, which means:</div>
<div>
<ul>
<li><strong>Execute</strong> &#8211; run the task</li>
<li><strong>Retry</strong> &#8211; do &#8220;Execute&#8221; again</li>
<li><strong>Rollback</strong> &#8211; do nothing</li>
<li><strong>Retry</strong> <strong>Rollback  </strong>&#8211; do Rollback again</li>
</ul>
<div></div>
<div>I used an enum for reporting the state of the action:</div>
<div>
<pre class="brush: csharp; title: ; notranslate">
public enum eStatus
{
 Pending,
 Success,
 Error
}
</pre>
</div>
<div>It looks like this:</div>
<div>
<pre class="brush: csharp; title: ; notranslate">
public abstract class BaseStep
{
 public virtual int ExecuteAttempts { get { return 1; } }
 public virtual int RollbackAttempts { get { return 1; } }

 public abstract eStatus Execute();
 public virtual eStatus Retry()
 {
  return Execute();
 }
 public virtual eStatus Rollback()
 {
  return eStatus.Success;
 }
 public virtual eStatus RetryRollback()
 {
  return Rollback();
 }
}
</pre>
</div>
<h3>The Process Manager</h3>
<p>The manager is responsible for creating the steps in the right order and execute each one. It is also responsible for coordinating the retry attempts and rollbacks. It implements an interface with one method:</p>
<pre class="brush: csharp; title: ; notranslate">
public interface IProcessManager
{
 eStatus Process();
}
</pre>
<p>and a base class that encapsulates the default behavior:</p>
<pre class="brush: csharp; title: ; notranslate">
public abstract class BaseProcessManager : IProcessManager
{
	private eStatus _currentStatus;
	private int _currentStep;
	private Func&lt;eStatus&gt; _action;
	protected List&lt;BaseStep&gt; _steps;

	protected BaseProcessManager()
	{
		_currentStatus = eStatus.Pending;
		_steps = new List&lt;BaseStep&gt;();
		Setup();
	}

	protected abstract void Setup();

	public virtual eStatus Process()
	{
		do
		{
			_action = _steps[_currentStep].Execute;
			Run();
			_action = _steps[_currentStep].Retry;
			Retry(_steps[_currentStep].ExecuteAttempts);

			_currentStep++;

		} while (_currentStatus != eStatus.Error &amp;&amp; _currentStep &lt; _steps.Count);

		if (_currentStatus == eStatus.Success)
			return eStatus.Success;

		do
		{
			_currentStep--;

			_action = _steps[_currentStep].Rollback;
			Run();
			_action = _steps[_currentStep].RetryRollback;
			Retry(_steps[_currentStep].RollbackAttempts);

		} while (_currentStep &gt; 0);

		return eStatus.Error;
	}

	private void Run()
	{
		_currentStatus = eStatus.Pending;
		_currentStatus = _action.Invoke();
	}

	private void Retry(int numberOfAttempts)
	{
		int attempt = 1;
		while (_currentStatus == eStatus.Error &amp;&amp; attempt &lt; numberOfAttempts)
		{
			_currentStatus = _action.Invoke();
			attempt++;
		}
	}
}
</pre>
<p>Now what is left for a developer to do is:</p>
<ol>
<li>Implement The BaseProcessManager, and override the Setup() method, where he should create the steps.</li>
<li>Create steps that implement the BaseStep abstract class, with the step logic.</li>
</ol>
<p>Thats it!I added a small app demonstrating this ides &#8211; <a href="http://gal-segal.com/wp-content/uploads/2012/01/TestProcessManager.zip">grab it here</a>.Special thanks to <a href="http://www.liorhakim.com/" target="_blank">Lior Hakim</a> and Omry Hay!</div>
]]></content:encoded>
			<wfw:commentRss>http://gal-segal.com/c-sharp/simple-process-manager/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Why Inheritance Doesn&#8217;t Scale</title>
		<link>http://gal-segal.com/c-sharp/why-inheritance-doesnt-scale</link>
		<comments>http://gal-segal.com/c-sharp/why-inheritance-doesnt-scale#comments</comments>
		<pubDate>Thu, 26 Jan 2012 12:53:23 +0000</pubDate>
		<dc:creator><![CDATA[Gal Segal]]></dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[c#]]></category>

		<guid isPermaLink="false">http://gal-segal.com/?p=419</guid>
		<description><![CDATA[OO Programmer tend to use inheritance as a way of code reuse, a best practice and for better maintainability. I am no exception. But there are times where inheritance can become your worst enemy, and instead of making your life easier, complicate stuff to the point you are lost.]]></description>
				<content:encoded><![CDATA[<p>OO Programmer tend to use inheritance as a way of code reuse, a best practice and for better maintainability. I am no exception. But there are times where inheritance can become your worst enemy, and instead of making your life easier, complicate stuff to the point you are lost.</p>
<p>That was a bit dramatic&#8230; but I will try to demonstrate my point, but first, a small declaration: inheritance is a good way for keeping your code nice and tidy, but if you use it the wrong way, you get a headache.</p>
<p>Lets say we run a bakery. Currently we are creating only 3 products: bread, rolls and cakes.  Each product is created in 3 stages: make dough, bake and wrap. It is pretty straightforwardness to build the object hierarchy for the bakery:</p>
<ul>
<li>Create an interface for the product (IProduct)</li>
<li>Implement 3 products (bread, roll, cake)</li>
<li>Create a base class for the Factories (ProductFactory)</li>
<li>Each product factory uses a<strong> <a href="http://www.dofactory.com/Patterns/PatternTemplate.aspx#_self1" target="_blank">template method</a></strong> for running the process (create dough, bake, wrap)</li>
<li>Implement 3 factories, one for each product</li>
</ul>
<p>Plain and simple. Now we can create a collection of factories, tell them to process and collect the products.</p>
<p style="text-align: center;"><a href="http://gal-segal.com/wp-content/uploads/2012/01/InheritancePhaseI.png"><img class="aligncenter size-full wp-image-447" title="Inheritance Phase I" src="http://gal-segal.com/wp-content/uploads/2012/01/InheritancePhaseI.png" alt="" width="500" height="467" /></a></p>
<p>Suddenly we discover that there are 2 types of dough: sweet and salty. We think: &#8220;hey, why not create 2 abstract factories, one for sweet and one for salty&#8221;. That&#8217;s a good idea, and you fill you showed the world your supreme c# kong fu with the <strong><a href="http://www.dofactory.com/Patterns/PatternAbstract.aspx" target="_blank">Abstract Factory</a></strong> pattern. Yes, you did it again! (and apparently, this is a good design decision).</p>
<p>Now your code structure looks like this:</p>
<p><a href="http://gal-segal.com/wp-content/uploads/2012/01/InheritancePhaseII.png"><img class="size-full wp-image-433 aligncenter" title="Inheritance Phase II" src="http://gal-segal.com/wp-content/uploads/2012/01/InheritancePhaseII.png" alt="" width="500" height="444" /></a></p>
<p>Your bakery grows, and so is your code.Now you are supporting 20 products, each of them has its own factory, and you are repeating this process of uniting similar factories to more abstract classes that overrides a part of the process.</p>
<p>Now lets fast forward to a more ambitious bakery, one that produce 100,000 different products. The inheritance tree is so big and complex, and so is maintainability: almost any change is breaking something, each new product you add is just a big pain: you don&#8217;t remember which factory to use, you do your best, but the odds are against you..</p>
<p>Why does it happens? its is not because inheritance is evil. Actually, inheritance is good, and it will allow us to find the solution, but you are using it the wrong way. The problem is that each factory is tide to these 3 actions. Take 2 factories where 2 actions are the same and one is different &#8211; the classic inheritance will call for another base class that implements the 2 methods, and the 2 classes will implement the third. It is time for a different approach, more <strong><a href="http://en.wikipedia.org/wiki/Single_responsibility_principle" target="_blank">single responsibility principle</a> </strong>one:</p>
<p>Assume each stage is a class of its own, managing only one granular action, for example &#8220;Bake()&#8221;: We will have the interface <strong>IBake, </strong>and we will derive classes from it, implementing different baking actions. The same goes with &#8220;make dough&#8221; and &#8220;wrap&#8221;. Now, each factory will instantiate the relevant actions, creating all its parts (instantiating dough maker, baker and wrapper) and call them:</p>
<p style="text-align: center;"><a href="http://gal-segal.com/wp-content/uploads/2012/01/InheritancePhaseIII.png"><img class="aligncenter size-full wp-image-446" title="Inheritance Phase III" src="http://gal-segal.com/wp-content/uploads/2012/01/InheritancePhaseIII.png" alt="" width="500" height="767" /></a></p>
<p>What are we gaining here? We gain the ability to create new factories with new combinations of the basic actions. We can also create new dough makers/bakers/wrappers without breaking the existing code. In other words, we are implementing the <strong><a href="http://en.wikipedia.org/wiki/Open/closed_principle" target="_blank">open/closed principle</a>, </strong>meaning &#8220;<em>software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification&#8221;. </em>Now scaling is more reasonable.</p>
<p>I added some code that demonstrates this concept, <a href="http://gal-segal.com/wp-content/uploads/2012/01/InheritanceLimitsExample.zip"><strong>you can grab it here</strong></a>.</p>
<p>Happy coding!</p>
]]></content:encoded>
			<wfw:commentRss>http://gal-segal.com/c-sharp/why-inheritance-doesnt-scale/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>WCF Client Proxy Creation Process</title>
		<link>http://gal-segal.com/c-sharp/wcf-client-proxy-creation-process</link>
		<comments>http://gal-segal.com/c-sharp/wcf-client-proxy-creation-process#comments</comments>
		<pubDate>Wed, 14 Dec 2011 09:52:51 +0000</pubDate>
		<dc:creator><![CDATA[Gal Segal]]></dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[c#]]></category>

		<guid isPermaLink="false">http://gal-segal.com/?p=398</guid>
		<description><![CDATA[WCF enables us to consume a service in 2 ways: adding a service reference or by creating the proxy yourself. Both methods do the same thing - create a proxy class and and using it with the channel factory. Both cases are good, and its a matter of preference which one you use. I tend to use the second one - I prefer creating my proxy and add reference to the service dlls in the consuming app.]]></description>
				<content:encoded><![CDATA[<p>WCF enables us to consume a service in 2 ways: adding a service reference or by creating the proxy yourself. Both methods do the same thing &#8211; create a proxy class and and using it with the channel factory. Both cases are good, and its a matter of preference which one you use. I tend to use the second one &#8211; I prefer creating my proxy and add reference to the service dlls in the consuming app.</p>
<p>In this post I want to show you how to do it correctly. Generally this is a simple process, but when working in high performance environments, we want to be as efficient as possible with creation and consumption of the service from the client application. The basic idea is that creating the channel factory takes time, but WCF will cache this object in the MRU (see <a href="http://blogs.msdn.com/b/wenlong/archive/2007/10/27/performance-improvement-of-wcf-client-proxy-creation-and-best-practices.aspx" target="_blank">here </a> for more details) and the next invocations will be faster.</p>
<p>A good infrastructure should expose a simple interface, and hide all the &#8220;dirty&#8221; processes, living the programmer a light and simple access. This is what to &#8220;ProxyHelper&#8221; class does in this process.</p>
<p>First, we need a service:</p>
<pre class="brush: csharp; title: ; notranslate">
[ServiceContract]
public interface ITestService
{
 [OperationContract]
 string DoWork();
}

public class TestService : ITestService
{
 public string DoWork()
 {
   return &quot;Hello&quot;;
 }
}
</pre>
<p>Than we create the proxy for this service, by implementing ClientBase&lt;T&gt; abstract class and the service contract:</p>
<pre class="brush: csharp; title: ; notranslate">
public class TestServiceProxy : ClientBase&lt;ITestService&gt;, ITestService
{
#region Ctor

public TestServiceProxy()
{

}

public TestServiceProxy(string endpointConfigurationName)
 : base(endpointConfigurationName)
{

}

public TestServiceProxy(string endpointConfigurationName, string remoteAddress)
 : base(endpointConfigurationName, remoteAddress)
{

}

public TestServiceProxy(string endpointConfigurationName, EndpointAddress remoteAddress)
 : base(endpointConfigurationName, remoteAddress)
{

}

public TestServiceProxy(Binding binding, EndpointAddress remoteAddress) :
 base(binding, remoteAddress)
{

}

#endregion

#region Methods

public string DoWork()
{
   return base.Channel.DoWork();
}

#endregion
}
</pre>
<p>In the consuming application we add reference to the service contract and proxy dll.<br />
Now, in order to create the proxy instance efficiently and safely, we need to implement a few things:</p>
<ol>
<li>Wrap the proxy instance in a &#8220;using&#8221; statement</li>
<li>Catch all exception types and abort the operation.</li>
</ol>
<p>This can be done nicely with a proxy helper that will do all the work for us:</p>
<pre class="brush: csharp; title: ; notranslate">
public static class ProxyHelper
{
 public static void InvokeProxyMethod&lt;TProxy&gt;(Action&lt;TProxy&gt; action)
 where TProxy : class, IDisposable, ICommunicationObject
 {
   InvokeMethod&lt;TProxy&gt;(action);
 }

public static void InvokeProxyMethod&lt;TProxy&gt;(string endpointConfigurationName, Action&lt;TProxy&gt; action)
 where TProxy : class, IDisposable, ICommunicationObject
 {
   InvokeMethod&lt;TProxy&gt;(action, endpointConfigurationName);
 }

public static void InvokeProxyMethod&lt;TProxy&gt;(string endpointConfigurationName, string address, Action&lt;TProxy&gt; action)
 where TProxy : class, IDisposable, ICommunicationObject
 {
   InvokeMethod&lt;TProxy&gt;(action, endpointConfigurationName, address);
 }

public static void InvokeProxyMethod&lt;TProxy&gt;(Binding binding, EndpointAddress address, Action&lt;TProxy&gt; action)
 where TProxy : class, IDisposable, ICommunicationObject
 {
   InvokeMethod&lt;TProxy&gt;(action, binding, address);
 }

private static void InvokeMethod&lt;TProxy&gt;(Action&lt;TProxy&gt; action, params object[] args)
 where TProxy : class, IDisposable, ICommunicationObject
 {
 using (var proxy = Resolve&lt;TProxy&gt;(args))
 {
   bool success = false;
   proxy.Open();
   try
   {
     action(proxy);
     success = true;
   }
   catch (CommunicationException ex)
   {
     throw new Exception(string.Format(&quot;CommunicationException - Failed to invoke '{0}' proxy&quot;, proxy.GetType().Name), ex);
   }
   catch (TimeoutException ex)
   {
     throw new Exception(string.Format(&quot;TimeoutException - Failed to invoke '{0}' proxy&quot;, proxy.GetType().Name), ex);
   }
   catch (Exception ex)
   {
     throw new Exception(string.Format(&quot;GeneralException - Failed to invoke '{0}' proxy&quot;, proxy.GetType().Name), ex);
   }
   finally
   {
     if (!success)
     {
       proxy.Abort();
     }
   }
  }
 }

private static T Resolve&lt;T&gt;(params object[] args)
{
   Type resolverType = typeof(T);
   if (resolverType == null)
   {
     throw new Exception(string.Format(&quot;type '{0}' does not exits&quot;, resolverType));
   }
   try
   {
     return (T)Activator.CreateInstance(resolverType, args);
   }
   catch (Exception ex)
   {
     throw new Exception(string.Format(&quot;could not create an instance of type '{0}'&quot;, resolverType), ex);
   }
 }
}
</pre>
<p>The helper class creates an instance of the proxy, utilizing all proxy&#8217;s constructors, and enables the consuming class to define an action to be performed on the proxy. It wraps the proxy method invocation with the needed &#8220;try catch&#8221; options.<br />
A simple usage for this helper is as follows: (this example uses the Binding and EndpointAddress constructor of the ClientBase&lt;T&gt; class, but you can use any other option)</p>
<pre class="brush: csharp; title: ; notranslate">
public class TestServiceConsumer
{
  public string DoWork()
  {
    Binding binding = new WSHttpBinding();
    EndpointAddress address = new EndpointAddress(&quot;http://192.168.11.78:800/InnerOAuthService.svc&quot;);
    string response = string.Empty;
    ProxyHelper.InvokeProxyMethod&lt;TestServiceProxy&gt;(binding, address, (proxy) =&gt;
    {
      response = proxy.DoWork();
     });
    return response;
   }
 }
</pre>
]]></content:encoded>
			<wfw:commentRss>http://gal-segal.com/c-sharp/wcf-client-proxy-creation-process/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Thread Safe High Performance Capped Queue</title>
		<link>http://gal-segal.com/c-sharp/thread-safe-high-performance-capped-queue</link>
		<comments>http://gal-segal.com/c-sharp/thread-safe-high-performance-capped-queue#comments</comments>
		<pubDate>Mon, 24 Oct 2011 10:44:07 +0000</pubDate>
		<dc:creator><![CDATA[Gal Segal]]></dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[c#]]></category>

		<guid isPermaLink="false">http://gal-segal.com/?p=385</guid>
		<description><![CDATA[Lately I was busy creating a new infrastructure for our logging system. I work on OpenBook - a website that gets a lot of traffic and involves with many different business processes. I started logging errors, info data and more with the excellent log4net to files, but has the logs got bigger and longer it became almost impossible  to track it. We also use several IIS servers behind a load - balancer, and the result is a lot of logs on many different servers.

I wanted to create an infrastructure that will be able to have the lowest footprint on the production server, but still be able to log a lot of message to some storage (SQL server, NoSQL server, files..).]]></description>
				<content:encoded><![CDATA[<p><span style="text-decoration: underline;"><strong>UPDATE &#8211; 27/2/2012</strong></span></p>
<p>I updated the code again to reflect Otto&#8217;s comment. The main concern was that 2 threads will enter simultaneously to the &#8220;publishing&#8221; code. The need for an atomic check if the the queue is now publishing can be done using Interlocked. Refer to Otto&#8217;s comments for context. Thanks again, Otto!</p>
<p><span style="text-decoration: underline;"><strong>UPDATE &#8211; 26/2/2012</strong></span></p>
<p>I updated the code to be a little more safe &#8211; there was a problem with a private member &#8220;_onPublishExecuted&#8221; being called twice(see in comments). Thanks Otto!<br />
Lately I was busy creating a new infrastructure for our logging system. I work on <a href="http://openbook.etoro.com" target="_blank">OpenBook</a> &#8211; a website that gets a lot of traffic and involves with many different business processes. I started logging errors, info data and more with the excellent <a href="http://logging.apache.org/log4net/" target="_blank">log4net</a> to files, but has the logs got bigger and longer it became almost impossible  to track it. We also use several IIS servers behind a load &#8211; balancer, and the result is a lot of logs on many different servers.</p>
<p>I wanted to create an infrastructure that will be able to have the lowest footprint on the production server, but still be able to log a lot of message to some storage (SQL server, NoSQL server, files..).</p>
<p>The main idea is this:</p>
<ol>
<li>Create a singletone/static queue that will collect all messages</li>
<li>Once it has X messages or after X seconds &#8211; it flushes all messages to another data store.</li>
</ol>
<p>Since we are dealing with high performance systems, I couldn&#8217;t afford any locks in this mechanism: I saw that the &#8220;flush&#8221; action locks the queue and all threads that try to insert new messages are frozen. I tried using the &#8220;ReaderWriterLockSlim&#8221; (see my post <a href="http://gal-segal.com/c-sharp/readerwriterlockslim-extension-method" target="_blank">here</a>) but it didn&#8217;t match &#8211; there are far more writes than reads in this process.</p>
<p>I headed over to the new<a href="http://msdn.microsoft.com/en-us/library/dd267265.aspx" target="_blank"> ConcurrentQueue&lt;T&gt;</a> object. This object implements almost a thread-safe lock-free mechanism. It was perfect for me. All I had to do was add the limitations for number of messages or timeout and this was pretty easy.</p>
<p>So this is it:</p>
<pre class="brush: csharp; title: ; notranslate">
public abstract class CappedQueue&lt;T&gt; : ConcurrentQueue&lt;T&gt; where T : class
{
	protected int _capLimit;
	protected int _timeLimit;
	protected System.Timers.Timer _timer;
	protected int _onPublishExecuted;
	protected ReaderWriterLockSlim _locker;

	protected CappedQueue()
	{
		var config = (CappedQueueConfigSection)ConfigurationManager.GetSection(&quot;cappedQueue&quot;);
		Init(config.CapLimit, config.TimeLimitInSeconds);
	}

	protected CappedQueue(int capLimit, int timeLimit)
	{
		Init(capLimit, timeLimit);
	}

	public event Action&lt;List&lt;T&gt;&gt; OnPublish = delegate { };

	public virtual new void Enqueue(T item)
	{
		base.Enqueue(item);
		if (Count &gt;= _capLimit)
		{
			Log4NetLogger.Log(eLogLevel.Debug, string.Format(&quot;Cap Limit: {0}&quot;, _capLimit));
			Publish();
		}
	}

	private void Init(int capLimit, int timeLimit)
	{
		_capLimit = capLimit;
		_timeLimit = timeLimit;
		_locker = new ReaderWriterLockSlim();
		InitTimer();
	}

	protected virtual void InitTimer()
	{
		_timer = new System.Timers.Timer();
		_timer.AutoReset = false;
		_timer.Interval = _timeLimit * 1000;
		_timer.Elapsed += new ElapsedEventHandler((s, e) =&gt;
		{
			Log4NetLogger.Log(eLogLevel.Debug, string.Format(&quot;Time Limit: {0}&quot;, _timeLimit));
			Publish();
		});
		_timer.Start();
	}

	protected virtual void Publish()
	{
		Task task = new Task(() =&gt;
		{
			List&lt;T&gt; itemsToLog = new List&lt;T&gt;();
			try
			{
				if (IsPublishing())
					return;

				StartPublishing();

				Log4NetLogger.Log(eLogLevel.Debug, string.Format(&quot;Start Dequeue {0} items&quot;, Count));
				T item;
				while (TryDequeue(out item))
				{
					itemsToLog.Add(item);
				}
			}
			catch (ThreadAbortException tex)
			{
				Log4NetLogger.Log(eLogLevel.Error, &quot;Dequeue items failed&quot;, tex);
			}
			catch (Exception ex)
			{
				Log4NetLogger.Log(eLogLevel.Error, &quot;Dequeue items failed&quot;, ex);
			}
			finally
			{
				Log4NetLogger.Log(eLogLevel.Debug, string.Format(&quot;Dequeued {0} items&quot;, itemsToLog.Count));
				OnPublish(itemsToLog);
				CompletePublishing();
			}
		});
		task.Start();
	}

	private bool IsPublishing()
	{
		return (Interlocked.CompareExchange(ref _onPublishExecuted, 1, 0) &gt; 0);
	}

	private void StartPublishing()
	{
		_timer.Stop();
	}

	private void CompletePublishing()
	{
		_timer.Start();
		Interlocked.Decrement(ref _onPublishExecuted);
	}
}
</pre>
<p>The CappedQueue gets 2 parametes in its constructor &#8211; one for the amount of objects and one for the interval (in seconds).<br />
It also expose a delegate of type Action that is fired asynchronously when one of the limits had been reached.</p>
<p>2 other things to notice:</p>
<ol>
<li>When the &#8220;Publish&#8221;  is fired, it runs a task asynchronously to avoid the locking.</li>
<li>All message in the queue are transferred to a new collection for further actions, and the main queue is free again.</li>
</ol>
<p>Happy coding :)</p>
]]></content:encoded>
			<wfw:commentRss>http://gal-segal.com/c-sharp/thread-safe-high-performance-capped-queue/feed</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>ReaderWriterLockSlim Extension Method</title>
		<link>http://gal-segal.com/c-sharp/readerwriterlockslim-extension-method</link>
		<comments>http://gal-segal.com/c-sharp/readerwriterlockslim-extension-method#comments</comments>
		<pubDate>Thu, 06 Oct 2011 13:23:37 +0000</pubDate>
		<dc:creator><![CDATA[Gal Segal]]></dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[c#]]></category>

		<guid isPermaLink="false">http://gal-segal.com/?p=376</guid>
		<description><![CDATA[ReaderWriterLockSlim was introduced in .net 3.5 as a better and more stable locker that allows multiple reads and single write capabilities on a synced resource. Using it is fairly a simple task: for reader you wrap your resource with "EnterReadLock()" and "ExitReadLock()", similar approach for writing. But problem lurk around the corner when it is not used correctly...]]></description>
				<content:encoded><![CDATA[<p><a href="http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim.aspx">ReaderWriterLockSlim</a> was introduced in .net 3.5 as a better and more stable locker that allows multiple reads and single write capabilities on a synced resource. Using it is fairly a simple task: for reader you wrap your resource with &#8220;EnterReadLock()&#8221; and &#8220;ExitReadLock()&#8221;, similar approach for writing.</p>
<p>One thing that is very important to remember is that you have to make sure the lock (either read or write) should be released after the action completes. The most obvious way is something like this:</p>
<pre class="brush: csharp; title: ; notranslate">
var locker = new ReaderWriterLockSlim();
try
{
	locker.EnterReadLock();
}
finally
{
	locker.ExitWriteLock();
}
</pre>
<p>The problem is to enforce all programmers to do it every time they use the locker. There are some debates about a better syntax for doing so <a href="http://stackoverflow.com/questions/805412/readerwriterlockslim-extension-method-performance">here</a>, <a href="http://stackoverflow.com/questions/5188475/is-readerwriterlockslim-the-right-coice">here</a> and <a href="http://stackoverflow.com/questions/6758858/simplifying-readerwriterlockslim-syntax">here</a>. Basically we can solve it by wrapping the locking operation in another object that implements the  <strong>IDisposable</strong> interface and in the Dispose() method release the lock. The problem here is that there are some cases where The Dispose() method will not be called, as explained <a href="http://www.bluebytesoftware.com/blog/PermaLink,guid,d9ff204a-a8a5-400e-bcbc-dedb90a7d11a.aspx">here</a>.</p>
<p>A better, and more safe approach is something like this:  think of a read operation as a &#8220;getter&#8221; function that returns an object, and the write as a &#8220;setter&#8221; that receives an object, than wrap it up with extension method:</p>
<pre class="brush: csharp; title: ; notranslate">
public static class ReadWriteLock
{
	public static T AcquireReadLock&lt;T&gt;(this ReaderWriterLockSlim locker, Func&lt;T&gt; action)
	{
		try
		{
			locker.EnterReadLock();
			return action();
		}
		finally
		{
			locker.ExitReadLock();
		}
	}

	public static void AcquireWriteLock(this ReaderWriterLockSlim locker, Action action)
	{
		try
		{
			locker.EnterWriteLock();
			action();
		}
		finally
		{
			locker.ExitWriteLock();
		}
	}
}
</pre>
<p>and usage:</p>
<pre class="brush: csharp; title: ; notranslate">
var originalCollection = new List&lt;string&gt;{&quot;apple&quot;,&quot;orange&quot;};

//read
var replicatedData = locker.AcquireReadLock&lt;List&lt;string&gt;&gt;(() =&gt; originalCollection);

//write
locker.AcquireWriteLock(() =&gt; originalCollection.Add(&quot;banana&quot;));
</pre>
<p>Happy coding :)</p>
]]></content:encoded>
			<wfw:commentRss>http://gal-segal.com/c-sharp/readerwriterlockslim-extension-method/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>MVC Routing Legacy URLs</title>
		<link>http://gal-segal.com/c-sharp/mvc-routing-legacy-urls</link>
		<comments>http://gal-segal.com/c-sharp/mvc-routing-legacy-urls#comments</comments>
		<pubDate>Wed, 21 Sep 2011 06:23:06 +0000</pubDate>
		<dc:creator><![CDATA[Gal Segal]]></dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[mvc3]]></category>

		<guid isPermaLink="false">http://gal-segal.com/?p=363</guid>
		<description><![CDATA[When moving a web application from WebForms to MVC framework I found sometimes ".aspx" and ".ashx" URLs from the old website sniking into my new clean and carved URLs. This issue can be addressed specifically by targeting the relevant "aspx" URLs and redirecting to a desired place, but it can get a bit messy. I found a more generic way of doing so by creating a new "Legacy Route" that will redirect all legacy requests to the new home page]]></description>
				<content:encoded><![CDATA[<p>When moving a web application from WebForms to MVC framework I found sometimes &#8220;.aspx&#8221; and &#8220;.ashx&#8221; URLs from the old website sniking into my new clean and carved URLs. This issue can be addressed specifically by targeting the relevant &#8220;aspx&#8221; URLs and redirecting to a desired place, but it can get a bit messy. I found a more generic way of doing so by creating a new &#8220;Legacy Route&#8221; that will redirect all legacy requests to the new home page:</p>
<pre class="brush: csharp; title: ; notranslate">
public class LegacyURLRoute : RouteBase
{
	public override RouteData GetRouteData(HttpContextBase httpContext)
	{
		var url = httpContext.Request.Url.AbsolutePath;
		if (url.Contains(&quot;.aspx&quot;) || url.Contains(&quot;.ashx&quot;))
		{
			var response = httpContext.Response;
			response.Status = &quot;301 Moved Permanently&quot;;
			response.RedirectLocation = &quot;/&quot;;
			response.End();
		}
		return null;
	}

	public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
	{
		return null;
	}
}
</pre>
<p>I tend to place this route at the end of the route table to avoid the unnecessary checks:</p>
<pre class="brush: csharp; title: ; notranslate">

RouteTable.Routes.Add(new LegacyURLRoute());

</pre>
]]></content:encoded>
			<wfw:commentRss>http://gal-segal.com/c-sharp/mvc-routing-legacy-urls/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>MVC Output Cache With Cache Profiles</title>
		<link>http://gal-segal.com/c-sharp/mvc-output-cache-with-cache-profiles</link>
		<comments>http://gal-segal.com/c-sharp/mvc-output-cache-with-cache-profiles#comments</comments>
		<pubDate>Wed, 14 Sep 2011 21:05:40 +0000</pubDate>
		<dc:creator><![CDATA[Gal Segal]]></dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[mvc3]]></category>

		<guid isPermaLink="false">http://gal-segal.com/?p=348</guid>
		<description><![CDATA[MVC and Output Cache are a good match, and since MVC3 this match is even better. But there are some occasions where this match is not good enough. I recently discovered an unwelcome behavior when dealing with ajax and had to come up with a solution.]]></description>
				<content:encoded><![CDATA[<p>MVC and Output Cache are a good match, and since MVC3 this match is even better. But there are some occasions where this match is not good enough. I recently discovered an unwelcome behavior when dealing with ajax and had to come up with a solution.</p>
<p>My team is working on a big website &#8211; <a href="http://openbook.etoro.com/?utm_campaign=English&amp;utm_medium=Affiliate&amp;utm_source=27318&amp;utm_content=2523&amp;utm_serial=BlogOpenBook#/main/" target="_blank">OpenBook</a>, which involve a lot of ajax calls (we are using jQuery as our basic JavaScript lib).  We also used Output cache on our ajax actions and all went pretty smooth, until, for some reasons, we had to disable caching of ajax calls on the client. What we discovered is that out Output Cache was also disabled &#8211; and this behavior I wanted to prevent.</p>
<p>The way jQuery disables browser caching is by adding &#8220;_=[TIMESTAMP]&#8221; on each call&#8217;s query string, so every new call as a distinct URL. By doing so it disabled Output Cache on the server as well. Why?</p>
<p>The reason for this is that Output Cache is a very early in the life cycle of the request-response model, before the routing and controller creation. Lets say we have a controller called &#8220;TaskController&#8221; and an action called &#8220;Edit&#8221; that receives &#8220;ID&#8221; as parameter. When requesting the URL &#8220;/task/edit/1&#8243; the MVC framework will assign ID with the value &#8220;1&#8221;. Any other parameters will not be used. If jQuery adds &#8220;_=[TIMESTAMP]&#8221; to the request, our action will not know about it, but Output Cache will and if you use &#8220;VaryByParam&#8221; it will not cache anything, since one of the parameters as changed.</p>
<p>Output Cache takes all the request&#8217;s parameters and creates a string that is uses as a key identifier for the response output.It caches the response with this key, and once this key is being requested again, it will pull the relevant resource from the cache and return it immediately. This is a good thing because the request will not pass through the MVC cycle and the request will not hit a controller or action.</p>
<p>I wanted to come up with a solution that will ignore the &#8220;_&#8221; parameter. I also wanted to keep using the cache profiles configuration on the web.config. The result is a mix and match of some code I found <a href="http://blog.maartenballiauw.be/post/2008/06/26/Creating-an-ASPNET-MVC-OutputCache-ActionFilterAttribute.aspx" target="_blank">here</a> and <a href="http://blog.stevensanderson.com/2008/10/15/partial-output-caching-in-aspnet-mvc/" target="_blank">here</a> with my additions.</p>
<h2>The Code</h2>
<pre class="brush: csharp; title: ; notranslate">
public class ActionOutputCacheAttribute : ActionFilterAttribute
{
	private static readonly OutputCacheSection _cacheConfig = (OutputCacheSection)ConfigurationManager.GetSection(&quot;system.web/caching/outputCache&quot;);
	private static readonly OutputCacheSettingsSection _cacheConfigSettings = (OutputCacheSettingsSection)ConfigurationManager.GetSection(&quot;system.web/caching/outputCacheSettings&quot;);
	private OutputCacheProfile _cacheProfile;
	private string _cacheKey;

	public ActionOutputCacheAttribute(string cacheProfileName)
	{
		if (string.IsNullOrWhiteSpace(cacheProfileName))
		{
			throw new ArgumentException(&quot;Cache profile is required&quot;);
		}

		_cacheProfile = _cacheConfigSettings.OutputCacheProfiles[cacheProfileName];

		if (_cacheProfile == null)
		{
			throw new ArgumentException(string.Format(&quot;Caching profile '{0}' was not found&quot;, _cacheProfile));
		}
	}

	public override void OnActionExecuting(ActionExecutingContext filterContext)
	{
		if (_cacheConfig.EnableOutputCache &amp;&amp; CacheOnServer())
		{
			_cacheKey = GenerateKey(filterContext);
			if (filterContext.HttpContext.Cache[_cacheKey] != null)
			{
				filterContext.Result = (ActionResult)filterContext.HttpContext.Cache[_cacheKey];
			}
		}

		base.OnActionExecuting(filterContext);
	}

	public override void OnActionExecuted(ActionExecutedContext filterContext)
	{
		if (_cacheConfig.EnableOutputCache &amp;&amp; CacheOnServer())
		{
			filterContext.HttpContext.Cache.Add(
				_cacheKey,
				filterContext.Result,
				null,
				DateTime.Now.AddSeconds(_cacheProfile.Duration),
				Cache.NoSlidingExpiration,
				CacheItemPriority.Normal,
				null
				);
		}
		base.OnActionExecuted(filterContext);
	}

	public override void OnResultExecuted(ResultExecutedContext filterContext)
	{
		if (_cacheConfig.EnableOutputCache &amp;&amp; CacheOnClient())
		{
			HttpCachePolicyBase cache = filterContext.HttpContext.Response.Cache;
			TimeSpan cacheDuration = TimeSpan.FromSeconds(_cacheProfile.Duration);

			cache.SetCacheability(HttpCacheability.Public);
			cache.SetExpires(DateTime.Now.Add(cacheDuration));
			cache.SetMaxAge(cacheDuration);
			cache.AppendCacheExtension(&quot;must-revalidate, proxy-revalidate&quot;);
		}
		base.OnResultExecuted(filterContext);
	}

	private string GenerateKey(ControllerContext filterContext)
	{
		StringBuilder cacheKey = new StringBuilder();

		cacheKey.Append(filterContext.Controller.GetType().FullName);
		if (filterContext.RouteData.Values.ContainsKey(&quot;action&quot;))
		{
			cacheKey.Append(&quot;_&quot;);
			cacheKey.Append(filterContext.RouteData.Values[&quot;action&quot;].ToString());
		}

		if (!string.IsNullOrEmpty(_cacheProfile.VaryByParam))
		{
			var varyByParamCollection = _cacheProfile.VaryByParam.Split(';');
			foreach (KeyValuePair&lt;string, object&gt; pair in filterContext.RouteData.Values)
			{
				if (_cacheProfile.VaryByParam == &quot;*&quot; || varyByParamCollection.Contains(pair.Key))
				{
					cacheKey.Append(&quot;_&quot;);
					cacheKey.Append(pair.Key);
					cacheKey.Append(&quot;=&quot;);
					cacheKey.Append(pair.Value.ToString());
				}
			}
		}
		if (!string.IsNullOrEmpty(_cacheProfile.VaryByHeader))
		{
			var varyByHeaderCollection = _cacheProfile.VaryByHeader.Split(';');
			foreach (var header in varyByHeaderCollection)
			{
				cacheKey.AppendFormat(&quot;_{0}={1}&quot;, header, filterContext.HttpContext.Request.Headers[header]);
			}
		}

		return cacheKey.ToString();
	}

	private bool CacheOnClient()
	{
		return _cacheProfile.Location == OutputCacheLocation.Client ||
			   _cacheProfile.Location == OutputCacheLocation.ServerAndClient ||
			   _cacheProfile.Location == OutputCacheLocation.Any ||
			   (int)_cacheProfile.Location == -1;
	}

	private bool CacheOnServer()
	{
		return _cacheProfile.Location == OutputCacheLocation.Server ||
			   _cacheProfile.Location == OutputCacheLocation.ServerAndClient ||
			   _cacheProfile.Location == OutputCacheLocation.Any ||
			   (int)_cacheProfile.Location == -1;
	}
}
</pre>
<h2>Usage</h2>
<h3>The Action:</h3>
<pre class="brush: csharp; title: ; notranslate">
[ActionOutputCache(&quot;SomeAction&quot;)]
public ActionResult SomeAction(int id)
{
	///do something...
	return View();
}
</pre>
<h3>and configuration:</h3>
<pre class="brush: xml; title: ; notranslate">
&lt;caching&gt;
      &lt;outputCache enableOutputCache = &quot;true&quot; /&gt;
      &lt;outputCacheSettings&gt;
          &lt;outputCacheProfiles&gt;
	      &lt;add name=&quot;SomeAction&quot; duration=&quot;60&quot; varyByParam=&quot;*&quot; varyByHeader=&quot;Accept-Language&quot; location=&quot;ServerAndClient&quot;/&gt;
          &lt;/outputCacheProfiles&gt;
      &lt;/outputCacheSettings&gt;
&lt;/caching&gt;
</pre>
<p>Happy Coding :)</p>
]]></content:encoded>
			<wfw:commentRss>http://gal-segal.com/c-sharp/mvc-output-cache-with-cache-profiles/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Object Mapper Extension Method</title>
		<link>http://gal-segal.com/c-sharp/object-mapper-extension-method</link>
		<comments>http://gal-segal.com/c-sharp/object-mapper-extension-method#comments</comments>
		<pubDate>Tue, 30 Aug 2011 07:30:02 +0000</pubDate>
		<dc:creator><![CDATA[Gal Segal]]></dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[utilities]]></category>

		<guid isPermaLink="false">http://gal-segal.com/?p=334</guid>
		<description><![CDATA[Many times I need a small piece of code that will help me map one object to another. I see it a lot when dealing with view models : taking a business object and modeling it to serve the needs of the presentation layer.
So I came up with a simple extension method:]]></description>
				<content:encoded><![CDATA[<p>Many times I need a small piece of code that will help me map one object to another. I see it a lot when dealing with view models : taking a business object and modeling it to serve the needs of the presentation layer.</p>
<p>There are many solutions to this problem:</p>
<ol>
<li>Target objects with a constructor that take the source object as parameter</li>
<li>A factory method that does it.</li>
<li>Just a simple piece of code that does the mapping.</li>
</ol>
<p>When dealing with large applications where this process occurs many times, I think a generic procedure should take place. I also keep in mind the need to keep these object ready for serialization. So I came up with a simple extension method:</p>
<pre class="brush: csharp; title: ; notranslate">
public static TTarget MapTo&lt;TSource, TTarget&gt;(this TSource source, Func&lt;TSource, TTarget&gt; mapper)
   where TSource : class
   where TTarget : class
{
   return mapper.Invoke(source);
}
</pre>
<p>and usage:</p>
<pre class="brush: csharp; title: ; notranslate">
public class Source
{
    public string SourceName { get; set; }
}

public class Target
{
    public string TargetName { get; set; }
}
Source source = new Source()
{
    SourceName = &quot;source&quot;
};

Target target = source.MapTo(x =&gt;
{
new Target() { TargetName = x.SourceName };
});
</pre>
]]></content:encoded>
			<wfw:commentRss>http://gal-segal.com/c-sharp/object-mapper-extension-method/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
