VS2012 – Performance Test Issue – Quick Tip


Last week I was trying to run some performance analysis in a web project using VS2012 features.

The wizard is pretty nice and it is very easy to configure..

But trying to start the performance tracking an issue occurred:

error

It is a strange error and has nothing to do with the solution’s code I was trying to test, except for one thing: The web.config file.

For some reason VS2012 need a unique .config file. It means if you have some specific config files to address specific concerns like: connection strings, service bindings, unity, etc, you will need to put it all in the web.config file to make it run.

Enjoy it!! =))

Posted in .NET Framework, Uncategorized | Tagged , , , | 2 Comments

VS2012 – Code Analysis CA0059 Error


Last week I was trying to run the Code Analysis tool on Visual Studio 2012 and for my surprise I got the CA0059 error on my screen:

fig1

Searching on MSDN website there isn´t any useful information about the error and because of it I decided to write this post.

In my case, the issue occurs because before the VS2012, the VM already have versions of VS2008 and VS2010 installed on it. These previous versions of Visual Studio created an environment variable called FxCodDir and it was pointing to previous versions of Visual Studio not the newest one: VS2102.

fig2

The solution is pretty simple: just delete the environment variable FxCodDir and it´s done, you are able to run code analysis on VS2012.

Posted in .NET Framework | Tagged , , , | Leave a comment

End Up With Caching Boring Code


boring2The situation is always the same: You are building a new feature that retrieve some data, make some calculus or whatever, and you think that is appropriated to cache the results for some while, and here is the cache aside pattern been written over and over again:

           if (!CachingContext.Current.Contains("YourKey"))
            {
                var result = GetAnyResult();

                 CachingContext.Current.Add("YourKey", result, ExpirationType.Absolute, 10);

                 return result;
            }
            else
            {
                return CachingContext.Current.GetData("YourKey");
            }

The pattern is nice, some developers when working with multi-thread applications like to use the statement “lock” in combination with this pattern to avoid concurrency issues, but the truth is: this structure of code is replicated in every method that needs to cache something.

One tip to avoid writing this boring code structure is to combine the caching aside pattern, with Func and anonymous methods.

Here is an example about how to code the Cache Aside Pattern in a unique method:

public TResult ManageCache<TResult>(Func<TResult> txCode, string cacheKey, ExpirationType expirationType, double minutes)
 {
        TResult result;

        if (!CachingContext.Current.Contains(cacheKey))
        {
            result = txCode();

            CachingContext.Current.Add(cacheKey, result, expirationType, minutes);
         }
         else
         {
            result = (TResult)CachingContext.Current.GetData(cacheKey);
         }

         return result;
}

And How should you call it:

 var result = CachingContext.Current.ManageCache(() =>
                {
                    return GetAnyResult();
                },
                                "YourKey",
                                ExpirationType.Absolute,
                                10);

It´s pretty simple and you still use the cache aside pattern, but don’t need to repeat the boring code structure every time you want to use it.

Posted in .NET Framework, Computer Science | Tagged , , , , , | Leave a comment

Useful Tip – Tracing with Logging App Block


tracking

Sometimes it is useful and necessary to keep track of the activity that is going under the scenes in your application. One of the most common necessities is to have a detailed log about how much time a specific method spent to execute.

This is not a hard thing to code, but those who are already working with enterprise library can take advantage over an out of the box feature provided by it.

Here is a sample code. It´s nice and simple:

using (var tracer = new Microsoft.Practices.EnterpriseLibrary.Logging.Tracer() )
{
      //Put your code here
}

This is how it works: the timer starts when the Tracer object is instantiated and the timer stops when the object is disposed.

But, that´s not enough, we have to log the information and make it available for the people who are interested in the information. To address that, it is possible to take advantage over all of the Logging App block features available in the enterprise library.

Here is an example about how to configure it:

<loggingConfiguration name="Logging Application Block" tracingEnabled="true" defaultCategory="General" logWarningsWhenNoCategoriesMatch="false">
  <listeners>
    <add databaseInstanceName="BAM" writeLogStoredProcName="WriteLog" addCategoryStoredProcName="AddCategory" formatter="Text Formatter" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Database.Configuration.FormattedDatabaseTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging.Database, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" traceOutputOptions="None" filter="All" type="Microsoft.Practices.EnterpriseLibrary.Logging.Database.FormattedDatabaseTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging.Database, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="Database BAM Trace Listener" />
  </listeners>
  <formatters>
    <add template="Timestamp: {timestamp}
Message: {message}
Category: {category}
Priority: {priority}
EventId: {eventid}
Severity: {severity}
Title:{title}
Machine: {machine}
Application Domain: {appDomain}
Process Id: {processId}
Process Name: {processName}
Win32 Thread Id: {win32ThreadId}
Thread Name: {threadName}
Extended Properties: {dictionary({key} - {value}
)}" type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="Text Formatter" />
  </formatters>
  <categorySources>
    <add name="Trace" switchValue="ActivityTracing">
      <listeners>
        <add name="Database BAM Trace Listener" />
      </listeners>
    </add>
  </categorySources>
</loggingConfiguration>
<connectionStrings>
<add name="BAM" connectionString="xxx" providerName="xxx"/>
</connectionStrings>

Writing the log to the database and increasing the logging capabilities in our solution we were able to create a Business Activity Monitoring (BAM) in our enterprise WCF service bus.
After that we just created a report to show the information to IT Staff.

Posted in .NET Framework, Computer Science | Tagged , , , , ,

Lean Software Development


About 2 years ago I started working in a new project and encouraged by the agile movement that was/is around at that time the team decided to learn and apply the disciplines and practices related with the Lean Software Development.

My colleague Ben-Hur, one of the best PMs that I ever worked with, shared with team the 7 core principles about Lean Software Development:

1. Eliminate waste
2. Amplify learning
3. Decide as late as possible
4. Deliver as fast as possible
5. Empower the team
6. Build integrity in
7. See the whole

If you would like a more deeply explanation about each concept I recommend Wikipedia.

By compiling all the theory and the concepts behind the Lean Software Development in this 7 principles it was easy to share with new team players the core concepts that the team was following.

This project were one of the most enjoyable that I ever worked mainly because the fabulous team and of course the mindset that Lean Software Development gave to us.

Posted in Uncategorized | Tagged , | 4 Comments

Commerce Server Staging – Hot Fix


Once you develop an e-commerce web site using Microsoft Commerce Server it´s very common to utilize the Commerce Server Staging. This engine is basically responsible for transporting Commerce Server data through different environments

Until now, everything is fine, but when you schedule the Commerce Server Staging to run very frequently, I mean with intervals of short periods of time, for instance 10 or 15 minutes, you will probably receive this exception in your event viewer log: Error occurred with the database StagingLog.mdb. Error is: System.Data.OleDb.OleDbException: System resource exceeded.

This error is related with the storage that Commerce Server Staging decides to save your own logs: Microsoft Access. We all know that Microsoft Access it´s not a reliable data source and to fix this issue Microsoft released a hot fix. It´s basically uses a Microsoft SQL CE engine instead of Microsoft Access.

Don´t forget to pay attention on the requirement of the hot fix that is the Microsoft SQL CE. My fellow and colleague, Roberto Galvão, already installed this hot fix in some environments and shared with me some steps to successfully install the hot fix in a 64bit platform. Thanks Roberto.

Steps:
1. Install SQL Server CE (x86)
2. Install SQL Server CE (x64)
3. Install Commerce Server Staging Fix
4. Restart the Servers.
5. Change the user of Commerce Server Staging Service (The hot fix changed the previous configs, so you should change it back again).
6. Restart Commerce Server Staging Service.
7. Execute Commerce Server Staging Projects.

Regards.

Posted in Uncategorized | Tagged , , , | Leave a comment

WCF + Unity App. Block


The Inversion of Control  (IoC) and Dependency Injection (DI) Pattern are very common nowadays and it represent an excellent approach to assemble projects into a cohesive application. Martin Fowler describes those patterns in this article

Enterprise Library gives us an IoC Container within Unity App. Block. This App. Block makes our lives easier when we’re about to use the IoC and DI patterns and some Creational Patterns as well.

But how do integrate WCF with Unity App. Block? The main issue is that WCF is responsible for instantiate the concrete service classes. So what we have to do is to modify this behavior, using some extensibility points of WCF and delegate to Unity App. Block the responsibility of instantiate the concrete service classes. Doing that, we’re able to enjoy all the benefits of the IoC Container and DI, even using WCF.

Remember that in this post I’m using Unity App. Block as our IoC Container but the strategy applies to any IoC container you like.

So, let’s go to hands on experience:

Creating Your Instance Provider based on Unity App. Block

WCF gives us the possibility of extend the way we create concrete service classes instances. In order to do that we should inherit from System.ServiceModel.Dispatcher.IInstanceProvider and override the GetInstance method. In this method we should use the Unity App. Block Container to manage the instances creation as follow:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Practices.Unity;

namespace Sample.WCF.Extensions.Unity
{
    /// <summary>
    /// Creates the service instance using Unity App.block
    /// </summary>
    public class UnityInstanceProvider : System.ServiceModel.Dispatcher.IInstanceProvider
    {
        /// <summary>
        /// Unity Container
        /// </summary>
        public IUnityContainer UnityContainer { get; set; }

        /// <summary>
        /// Service Type to Instantiate
        /// </summary>
        public Type ServiceType { get; set; }

        public UnityInstanceProvider() :this(null){}

        public UnityInstanceProvider(Type serviceType)
        {
            this.ServiceType = serviceType;
            this.UnityContainer = new UnityContainer();
        }

        #region IInstanceProvider Members

        public object GetInstance(System.ServiceModel.InstanceContext instanceContext, System.ServiceModel.Channels.Message message)
        {
            //Check if the container is available
            if (this.UnityContainer != null)
            {
                /*
                 * Creates the service instance using Unity App. Block (DI and IoC)
                 * */
                return this.UnityContainer.Resolve(this.ServiceType);
            }

            return instanceContext;
        }

        public object GetInstance(System.ServiceModel.InstanceContext instanceContext)
        {
            return this.GetInstance(instanceContext, null);
        }

        public void ReleaseInstance(System.ServiceModel.InstanceContext instanceContext, object instance)
        {
        }

        #endregion
    }
}

Creating a Service Behavior

In order to use the Custom Instance Provider that we’ve created we should build a Custom Service Behavior and override the ApplyDispatchBehavior method.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Practices.Unity;
using System.ServiceModel.Dispatcher;
using Microsoft.Practices.Unity.Configuration;
using System.Configuration;

namespace Sample.WCF.Extensions.Unity
{
    public class UnityServiceBehavior : System.ServiceModel.Description.IServiceBehavior
    {
        /// <summary>
        /// The Instance Provider Reference
        /// </summary>
        private UnityInstanceProvider InstanceProvider { get; set; }

        private void ConfigureUnityContainer(IUnityContainer unityContainer)
        {
            //Loads the Unity Section Handler and its configuration
            UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");

            //Configures the container
            section.Containers.Default.Configure(unityContainer);
        }

        public UnityServiceBehavior()
        {
            //Creates the UnityInstanceProvider
            this.InstanceProvider = new UnityInstanceProvider();

            this.InstanceProvider.UnityContainer = new UnityContainer();

            this.ConfigureUnityContainer(this.InstanceProvider.UnityContainer);

        }

        #region IServiceBehavior Members

        public void AddBindingParameters(System.ServiceModel.Description.ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<System.ServiceModel.Description.ServiceEndpoint> endpoints, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
        {

        }

        public void ApplyDispatchBehavior(System.ServiceModel.Description.ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
        {
            foreach (ChannelDispatcherBase cdb in serviceHostBase.ChannelDispatchers)
            {
                ChannelDispatcher cd = cdb as ChannelDispatcher;

                if (cd != null)
                {
                    foreach (EndpointDispatcher ed in cd.Endpoints)
                    {
                        //Indicates to instance provider the Service Type
                        this.InstanceProvider.ServiceType = serviceDescription.ServiceType;

                        //Sets the UnityInstanceProvider Foreach EndpointDispatcher
                        ed.DispatchRuntime.InstanceProvider = this.InstanceProvider;
                    }
                }
            }
        }

        public void Validate(System.ServiceModel.Description.ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
        {
        }

        #endregion
    }
}

Configuring The Unity App. Block Section

The Unity App. Block works in two different ways. You can configure the IoC Container using a config file, our hard coding the IoC Container behavior. I often use the first approach (config file).

To configure the Unity App. Block we should declare a Section in the web.config file:

<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration, Version=1.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />

After, we have to point this section to an external file (that really configures the IoC Container).


<unity configSource="YourConfigFile.config">

</unity>

To see how to configure the Unity App. Block Container check out this link: http://msdn.microsoft.com/en-us/library/ff647427.aspx

Two different approaches to configure a Custom Service Behavior

There are two different approaches to insert the custom service behavior that we’ve created.

1. BehaviorExtensionElement Approach

In this approach we should indicate foreach Service we have that we would like to integrate it with Unity App. Block. In order to do that we have to create BehaviorExtensionElement and configure it in the web.config file:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Practices.Unity;

namespace Sample.WCF.Extensions.Unity
{
    public class UnityBehaviorExtensionElement : System.ServiceModel.Configuration.BehaviorExtensionElement
    {
        public UnityBehaviorExtensionElement()
        {
        }

        public override Type BehaviorType
        {
            //Returns the type of UnityServiceBehavior
            get { return typeof(UnityServiceBehavior); }
        }

        protected override object CreateBehavior()
        {
            return new UnityServiceBehavior();
        }
    }
}

Registering it in the web.config file:

  <extensions>
      <behaviorExtensions>
        <add name="UnityWCF" type="Sample.WCF.Extensions.Unity.UnityBehaviorExtensionElement, Sample.WCF.Extensions, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
      </behaviorExtensions>
    </extensions>
	<behaviors>
			<serviceBehaviors>
				<behavior name="Sample.WCF.Extensions.SampleServiceBehavior">
                                        <UnityWCF />
					<serviceMetadata httpGetEnabled="true"/>
					<serviceDebug includeExceptionDetailInFaults="false"/>
				</behavior>
                          </serviceBehaviors>
        </behaviors>

2. Service Host Factory Approach

In this approach we use a custom Service Host Factory and inject the Custom Service Behavior and its Custom Instance Provider foreach service without needing to indicate that in the web.config file:

The first Step is to create a Custom Service Host Factory and a Custom Service Host:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Practices.Unity.Configuration;
using System.Configuration;

namespace Sample.WCF.Extensions.Unity
{
    public class UnityServiceHostFactory : System.ServiceModel.Activation.ServiceHostFactory
    {
        protected override System.ServiceModel.ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
        {
            //Creates the unity service host
            UnityServiceHost unityServiceHost = new UnityServiceHost(serviceType, baseAddresses);

            return unityServiceHost;
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using System.Configuration;

namespace Sample.WCF.Extensions.Unity
{
    public class UnityServiceHost : System.ServiceModel.ServiceHost
    {
        public UnityServiceHost() : base()
        {
        }

        public UnityServiceHost(Type serviceType, params Uri[] baseAddresses) : base(serviceType, baseAddresses)
        {
        }

        protected override void OnOpening()
        {
            //Verifies if the UnityServiceBehavior is already attached
            if (this.Description.Behaviors.Find<UnityServiceBehavior>() == null)
            {
                //Attach the UnityServiceBehavior
                this.Description.Behaviors.Add(new UnityServiceBehavior());
            }

            base.OnOpening();
        }
    }
}

After that we need to chance the service Factory in your .svc file:


<%@ ServiceHost Debug="true" Service="Sample.WCF.Extensions.SampleService" CodeBehind="SampleService.svc.cs" Factory="Sample.WCF.Extensions.Unity.UnityServiceHostFactory, Sample.WCF.Extensions" %>

Remember that in this post I’m using Unity App. Block as our IoC Container but the strategy applies to any IoC container you like, ok?

[]´s

Posted in .NET Framework, Computer Science | Tagged , , , , , , , | 2 Comments