How to use Unity with Web API

Web Api controller are instantied by Asp.Net MVC framework and by default, the parameter less constructor is called. If you want to instantiate your class with your IoC, like Microsoft Unity, you will have to customize the instantiation of those Web Api Controller. The customized instanciator is called a Dependency Resolver and can be configured in the Global.asax.

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);

        UnityConfiguration.Initialize();
        MapperConfiguration.Initialize(UnityConfiguration.Container.Resolve<IMapperFactory>());
        UnityConfiguration.Container.Resolve<IDatabaseContext>().InitializeDatabase();
        GlobalConfiguration.Configuration.DependencyResolver = new IoCContainer(UnityConfiguration.Container);
    }
}

The first thing to do is to modify the Application_Start of your WebApi project. You need to execute the configuration of all your interface with Unity. In the example above, this is done by calling UnityConfiguration.Initialize() which Resolve every interface to a concrete class.

The second thing to do is to set to the GlobalConfiguration a DependencyResolver to a IocContainer that we will create to use Unity container.

internal class ScopeContainer : IDependencyScope
{
	protected readonly IUnityContainer _container;

	public ScopeContainer(IUnityContainer container)
	{
		if (container == null)
		{
			throw new ArgumentNullException("container");
		}
		this._container = container;
	}

        public object GetService(Type serviceType)
        {

            if (!_container.IsRegistered(serviceType))
            {
                if (serviceType.IsAbstract || serviceType.IsInterface)
                {
                    return null;
                }
            }
            return _container.Resolve(serviceType);
        }

	public IEnumerable<object> GetServices(Type serviceType)
	{
		return _container.IsRegistered(serviceType) ? _container.ResolveAll(serviceType) : new List<object>();
	}

	public void Dispose()
	{
		_container.Dispose();
	}
}

internal class IoCContainer : ScopeContainer, IDependencyResolver
{
	public IoCContainer(IUnityContainer container):base(container)
	{
	}

	public IDependencyScope BeginScope()
	{
		var child = _container.CreateChildContainer();
		return new ScopeContainer(child);
	}
}

The GetService is made in a way that it doesn’t require you to register every controllers with Unity but only registered type will go through Unity.

From here, every Web Api controllers will be instanced by passing by the ScopeContainer , which will check every parameters’ type and resolve the type with Unity.

The Web Api will create a new instance of Unity and dispose of it at every http request.

How to use Paypal’s payment for your website and associate the payment to one of your user with PHP

It’s rare that I wrote something in PHP but since I have worked with Paypal with PHP in 2009, it will be simpler for me to show you how it works with this language. The same process can be apply for your .Net website. In fact, most steps are within Paypal website and interact with plain Html.

Paypal offers many ways to use their system for transaction. By memory, at least since 2009 x.com has become the reference website for Paypal. By then, they have developed rich API and documentation. Nevertheless, the IPN method, the one that I’ll show you is simple and works since many years. From what I know, it’s been over 6 years that this method is working (and could be more).

Coding the button to send the Paypal’s request

First of all, you need to have a Paypal account and create a Merchant account. You can get one for free, no need to have the “Premium Merchant” account. The Paypal account is required to receive the fund and the merchant account to be able to charge your customer. Second, you need to create a button that will redirect your user to Paypal with an amount to pay. You need to go to “Merchant Services” and create your button.

buyNowButton

The method I am showing you has the limitation of having few hardcoded values like the price charged. You won’t be able to change the amount directly via the Html Form. When creating the button, you’ll have to set a fixed price. If you have, let say, three differents account, you may want to have 3 buttons generated with 3 hard coded amount. However, you can charge your customer which should be your main goal. Once the button is created, save the generated Html by Paypal to your webpage. Second, the button needs to be inside a form. This form will send the request to Paypal where the user will enter his Paypal’s credential and to complete the order. Once the order is done, Paypal will send you back a message indicating that the transaction is a success or not. From here, you need to tell to Paypal what is the web page it needs to call. You have to go to “My Account” and then “Profile”. You will see “Instant Payment Notification”, click on it and write your “callback” webpage.

ipnconfig

Third, you need to associate the user to the transaction because you want that in the call back to save into your database that you have a new transactions executed for a specific user. This can be done by adding hidden fields to the form where the Paypal’s button has been inserted. In fact, you can go to the IPN Guide or the online documentation and see all possibles parameters (hidden fields) that can be sent to Paypal with a button. I use the “custom” field where I concatenate multiple information like the user id, the goods id, etc.

<input type="hidden" name="custom" value="<?php echo(urlencode(base64_encode($usagerCourant->getIdUsager()."+1")));?>">
<input type="hidden" name="lc" value="fr"/>

Has you can see in the example above, I am encoding the user id and I concatenate the item id. When Paypal will call back my webpage, I’ll be able to get from the http header the field custom and decode the field to get back both information. You can also see that I am using the hidden field name “lc”. This field tells Paypal to display itself in French. This can be useful if you have multiple languages to support.

Last thing concerning the button and the form: you need to send the request somewhere. You have two places where you can send the transction. The first is the real web site where real money is involved. The second is called “SandBox” where is a place to mess around. Everything inside the sandbox is fake, and won’t be charged. You can do you test with the sandbox environment without having to refund real transaction. The two url are:

      https://www.paypal.com/cgi-bin/webscr
      https://www.sandbox.paypal.com/cgi-bin/webscr

Creating the IPN’s callback

From here, you need to write the call back page. This is where all the hard work is required.

The call back page is harder because the testing process is longuer even with Paypal callback. You’ll also need to use to debug log file because you do not have any direct feedback of what is going on.

The first step is to send back to Paypal every parameters with the additionnal command called “cmd” and indicating that you are validating that is a real request from Paypal. This is a secure protection that assure that the request is not forged by a malicious user. Since Paypal should have create the request, this one will validate that all parameters that he just sent are valid.

So, your code should look like this one :

$req = 'cmd=_notify-validate';
foreach ($_POST as $key => $value) {
	$value = urlencode(stripslashes($value));
	$req .= "&$key=$value";
}

Then, we need to send the request. I use a socket connection to send a Http request. Many other ways could be used of course.

	$header = "POST /cgi-bin/webscr HTTP/1.0\r\n";
	$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
	$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
	
	if($isDebugging)
		$fp = fsockopen('www.sandbox.paypal.com', 80, $errno, $errstr, 30);
	else
		$fp = fsockopen('ssl://www.paypal.com', 443, $errno, $errstr, 30);

Before sending back the request to Paypal, I personalty insert some information to my database concerning the transaction id, the item name, the user who bought the item/service the real name of the user and real email, etc. As you can see, I am not yet sending the request but preparing the socket to open an url (that change depending if I am testing or not). Since we are using at different place different url, I suggest that you have a mechanism to switch between dev/debug mode and prod/real mode. For more information concerning which url to use, please refer yourself to this documentation.

The next step is to send the request and wait the response.

fputs ($fp, $header . $req);
while (!feof($fp)) 
{
	$res = fgets ($fp, 1024);
	if (strcmp ($res, "VERIFIED") == 0) 
	{
	//...
//...
}
fclose ($fp);

If the answer is the string “VERIFIED” then everything is fine. From here, I do some other validation concerning if the price is right with the product/service bought and I can grand the user of his goods. For me, it’s simply adding his id to a junction table with special privileges with an expiration date.

Paypal IPN service is fast and your user can be granted of what he bought immediately when you receive the request from the post back. This is a huge advantage because no manual intervention is required and the user can access everything right after he sent you the money.

Testing with the sandbox

You can create fake customer with Paypal’s Sandbox. Go to : https://developer.paypal.com. Once you have your developer account, which doesn’t require you more than having a valid Paypal’s account, you’ll be able to create fake customer with fake email. This will allow you to use these fake Paypal account to do fake payment in the sandbox. It will also let you do fake refund. This is ideal to practice and to test your button, your post back page and how save into your database information about a transaction.

paypalsandbox

To test with the sandbox you absolytely need to create the button from the fake merchant account you have created in the sandbox. So once you have created a merchant account, log to https://www.sandbox.paypal.com/ and recreate the button.

Watch out about fraud

Paypal is well know to protect the buyer more than the seller. Once, I have live a situation that he user pay and within the 30 days of refund, the user requested a refund. Even more, the user called his credit card company which created a fee of few dollar on me. In that case, if you provide premium service, it will be very hard to prove that you really provided this service. Trust me, Paypal won’t fight for you. This is really sad because if you have downloadable content, and the user download everything and then request for refund, you will lose. The best way to organize your premium service is something that require to user to access only from your website and never more then few months (ideally recurrent payment every month).

Here is a great source for Paypal and PHP.

https://www.x.com/developers/paypal/documentation-tools/ipn/integration-guide/IPNIntro
http://demos.ipn-easy.com/Howto/TestEnvironment.aspx

Asp.Net MVC Html Helper to create link with an image

You can use the default Html Helper to have a text url. This is most of the time sufficient but when came the scenario that you want an image to be a link, you are alone. You can create every time a link that will contain an image. But, with Asp.Net MVC, one nicest way to do it would be with an Html Extension. The main reason is that you won’t have to repeat the code every time.

So, if we take the ActionLink html helper we would use it this way.

@Html.ActionLink("Text to display", "ActionNameHere", "ControllerNameHere", new { id = 123 }, new{@class="myClass"})

As you can see, this overload take the text to display, the action name to redirect to and the controller which belong the action. Then, we have the route value which in this example send an id to the action and finally an html attribute which let you configure the link accordingly to some html attributes you desire.

htmlhelperimageurl

What we want to do it almost the same but adding an image.

public MvcHtmlString ActionImage(this HtmlHelper htmlHelper, 
                                 string controller, 
                                 string action, 
                                 object routeValues, 
                                 string imagePath, 
                                 string alternateText = "", 
                                 object htmlAttributes = null)
{

	var anchorBuilder = new TagBuilder("a");
	var url = new UrlHelper(HtmlHelper.ViewContext.RequestContext);

	anchorBuilder.MergeAttribute("href",url.Action(action,controller,routeValues));
	
	var imgBuilder = new TagBuilder("img");
	imgBuilder.MergeAttribute("src", url.Content(imagePath));
	imgBuilder.MergeAttribute("alt", alternateText);

	var attributes = (IDictionary<string, object>) HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
	imgBuilder.MergeAttributes(attributes);
	string imgHtml = imgBuilder.ToString(TagRenderMode.SelfClosing);

	anchorBuilder.InnerHtml = imgHtml;
	return MvcHtmlString.Create(anchorBuilder.ToString());
}

The first parameter let you extend the HtmlHelper. This will let you use your new method with the @Html keyword.
The 4 next parameters is the required parameters. THe first one is the controller, then the action, the route value and the image path. Finally, we can specify if desired an alternated text and additional html attributes.

The first part will create the link. It uses the RequestContext and the UrlHelper to create the link. In fact, it will build from the controller, the action and the route values an url well formed from the routing schema of your Asp.Net MVC website.

The last part build the image and add it into the link. Finally, we merge the attribute we passed to the image. We could also do the same to have html attribute for the link.

Here is how to html helper can be used.

@Html.ActionImage("Workout", "Delete", new { id = @workout.Id }, "/images/bluetrash.png", "Delete", new { id="deletebutton"})

How to update specific field of your entity with a generic method and Entity Framework

If you are using Entity Framework with a repository layer which has the basic method like Get, Update, Insert (or Add) and Delete you are already in a good position. But what if you want to update a single property without having to load the whole entity from the database? If you have only the primary key (id) of your entity and the value of the property you want to update, you may want to simply update the field with a where clause with the id. In SQL, we would create the following query.

update [dbo].[WorkoutSessions]
set [Name] = 'New Name', 
    [Order] = 1
where ([Id] = 123)

With Entity Framework, you could create single method like “UpdateNameAndOrder” but this would end to having a lot of update method if you require to have partial update among many properties. A better approach would be to specify which properties we want to update.

public int Update(T entity, Expression<Func<T, object>>[] properties)
{
	DatabaseContext.Entry(entity).State = EntityState.Unchanged;
	foreach (var property in properties)
	{
		var propertyName = ExpressionHelper.GetExpressionText(property);
		DatabaseContext.Entry(entity).Property(propertyName).IsModified = true;
	}
	return DatabaseContext.SaveChangesWithoutValidation();
}

The code above is in the BaseRepository class of the project described in the “Enterprise project“. As you can see, it takes as its second parameter an expression of a function. This will let use this method by specifying in a Lambda expression witch property to update.

    ...Update(Model, d=>d.Name);
//or
    ...Update(Model, d=>d.Name, d=>d.SecondProperty, d=>d.AndSoOn);

As you can see, the Update method first line change the state to Unchanged. We could have using Attach of the IDbSet but since in the Enterprise project we have special sets a way to simply go directly to the DbSet of the current database context is to go directly to the Entry. Next, we loop all properties chosen. Inside the loop, we are using a System.Web.Mvc namespace. We could have using the code of GetExpressionText without having to use this namespace. Here is the code if you do not want a reference to this dll.

    /// <summary>
    /// Gets the model name from a lambda expression.
    /// </summary>
    /// 
    /// <returns>
    /// The model name.
    /// </returns>
    /// <param name="expression">The expression.</param>
    public static string GetExpressionText(LambdaExpression expression)
    {
      Stack<string> stack = new Stack<string>();
      Expression expression1 = expression.Body;
      while (expression1 != null)
      {
        if (expression1.NodeType == ExpressionType.Call)
        {
          MethodCallExpression methodCallExpression = (MethodCallExpression) expression1;
          if (ExpressionHelper.IsSingleArgumentIndexer((Expression) methodCallExpression))
          {
            stack.Push(ExpressionHelper.GetIndexerInvocation(Enumerable.Single<Expression>((IEnumerable<Expression>) methodCallExpression.Arguments), Enumerable.ToArray<ParameterExpression>((IEnumerable<ParameterExpression>) expression.Parameters)));
            expression1 = methodCallExpression.Object;
          }
          else
            break;
        }
        else if (expression1.NodeType == ExpressionType.ArrayIndex)
        {
          BinaryExpression binaryExpression = (BinaryExpression) expression1;
          stack.Push(ExpressionHelper.GetIndexerInvocation(binaryExpression.Right, Enumerable.ToArray<ParameterExpression>((IEnumerable<ParameterExpression>) expression.Parameters)));
          expression1 = binaryExpression.Left;
        }
        else if (expression1.NodeType == ExpressionType.MemberAccess)
        {
          MemberExpression memberExpression = (MemberExpression) expression1;
          stack.Push("." + memberExpression.Member.Name);
          expression1 = memberExpression.Expression;
        }
        else if (expression1.NodeType == ExpressionType.Parameter)
        {
          stack.Push(string.Empty);
          expression1 = (Expression) null;
        }
        else
          break;
      }
      if (stack.Count > 0 && string.Equals(stack.Peek(), ".model", StringComparison.OrdinalIgnoreCase))
        stack.Pop();
      if (stack.Count <= 0)
        return string.Empty;
      return Enumerable.Aggregate<string>((IEnumerable<string>) stack, (Func<string, string, string>) ((left, right) => left + right)).TrimStart(new char[1]
      {
        '.'
      });
    }

What it does is it takes from the lambda the name of the property selected.

The last thing the update method is doing it’s saving without executing the validation on the entity. This is required since not the whole entity is loaded. Some property required might not be loaded which would result into validation exception. To be honest, an improvement would be to execute the validation for the updated property, but for the sake of simplicity, we will stay this smaller.

To conclude, it’s possible to update an entity in a generic way without having to preload this object or to update all its properties.

SQL Tracing without having Sql Server Tools

It’s always a good idea to be able to see what’s happening behind when you are using ORM, like Entity Framework. If you have the possibility to have the full blow Sql Server with tools, than you have the Sql Profiler that can tell you every queries executed. Unfortunately, if you are using the Sql Express Edition, you won’t have the Sql Profiler available.

However, you still can get thoses queries outputted into a log file with the Sql Express edition. First of all, be sure to stop the SQL Express Service. This can be done by going into the Services.msc

sqlexpressservice

Or you can use the command prompt with the command “net stop” with the parameter of the service which should be “MSSQL$SqlExpress”. Of course, this must be done with the administrator privileges which can be

sqlexpressservicecmd

To enable the service to run again but this time with the log we need to start the Sql Service with the flag “/T4032”.

net start MSSQL$SQLEXPRESS /T4032

The last thing to do is open the Sql Server Management Studio and to execute the following command.

dbcc traceon(3605, -1)

From here, you just need to consult the log file. With Sql Server 2012 Express edition on a Windows 7 OS, you will find the log file here:

C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS\MSSQL\Log

How to use log every call of your WCF service’s methods

If you want to log information like which method has been called with which parameters on every methods of your WCF service, you shouldn’t set the log every time on each method. Two approaches is possible to create something clean.

The first option is to create an attribute and when this one is present will log. The second is to automatically log every call. I’ll show you the second approach since it’s seem more logic to log every methods. If you are curious about how to do it with an attribute, I’ll post in few times the code to apply security with WCF with attribute which will show you how to do it.

This article shows you how to log every calls of WCF’s methods. It will use Unity as IOC. So, this article show you how to use an IOC (Unity) with WCF also.

The first step is to modify your service definition. This can be done by editing the .scv (not the .svc.cs).

<%@ ServiceHost Language="C#" 
Debug="true" 
Service="MyNameSpace.MyServices.MyService" 
CodeBehind="MyService.svc.cs" 
Factory="MyNameSpace.MyServices.Common.MyServiceHostFactory " %>

The important modification is the Factory attribute. This one is required to be able to use Unity. This act as the global.asax.cs. By this, I mean, it’s called when the service is initialized and not at every calls. Behind this factory, you own class is instanced and you are able to return your own ServiceHost class. This is a door to initialize Unity (IoC), AutoMapper and many others utilities class that need to be instanced once.

public class MyServiceHostFactory : ServiceHostFactory
{
	protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
	{
		var serviceHost = new MyServiceHost(serviceType, baseAddresses);
		//ConfigureUnity(serviceHost.Container);
		//ConfigureAutoMapper();
		return serviceHost;
	}
}

The MyServiceHostFactory creates a MyServiceHost and configure the inversion of control container. It also initialize the Automapper configuration. The MyServiceHost inherit from ServiceHost, which let you add the implementation of the IoC container and handle behaviors. To be able to log on every service’s method, a new behavior need to be defined.

public class MyServiceHost : ServiceHost
{
	public UnityContainer Container { get; set; }
	
	public MyServiceHost()
	{
		Container = new UnityContainer();
	}

	public MyServiceHost(Type serviceType, params Uri[] baseAddresses): base(serviceType, baseAddresses)
	{
		Container = new UnityContainer();
	}

	protected override void OnOpening()
	{
		base.OnOpening();

		if (this.Description.Behaviors.Find<MyServiceBehavior>() == null)
		{
			this.Description.Behaviors.Add(new MyServiceBehavior(Container));
		}
	}
}

The MyServiceHost initializes the container and add a single behavior which handle the logging feature.

public class MyServiceBehavior : IServiceBehavior
{
	public UnityInstanceProvider InstanceProvider { get; set; }

	public MyServiceBehavior()
	{
		InstanceProvider = new UnityInstanceProvider();
	}

	public MyServiceBehavior(UnityContainer unity)
	{
		InstanceProvider = new UnityInstanceProvider {Container = unity};
	}

	public void AddBindingParameters(ServiceDescription serviceDescription, 
									ServiceHostBase serviceHostBase, 
									Collection<ServiceEndpoint> endpoints,
									BindingParameterCollection bindingParameters)
	{	
	}

	public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
	{
                InstanceProvider.ServiceType = serviceDescription.ServiceType;
		foreach (ChannelDispatcherBase cdb in serviceHostBase.ChannelDispatchers)
		{
			var cd = cdb as ChannelDispatcher;
			if (cd != null)
			{
				foreach (EndpointDispatcher ed in cd.Endpoints)
				{
					ed.DispatchRuntime.InstanceProvider = InstanceProvider;
				}
			}
		}

		var log = InstanceProvider.Container.Resolve<ILog>();
		IOperationBehavior behavior = new LoggingOperationBehavior(log);
		foreach (ServiceEndpoint endpoint in serviceDescription.Endpoints)
		{
			foreach (OperationDescription operation in endpoint.Contract.Operations)
			{
				if (!operation.Behaviors.Any(d => d is LoggingOperationBehavior))
				{
					operation.Behaviors.Add(behavior);
				}
			}
		}
	}

	public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
	{ 
	}
}

This is where we attach for all endpoints, all operations (methods) the behavior to be executed. This is where we add the logging behavior. The first foreach is required for Unity to be the provider while the second foreach is there to add the logging behavior.

public class UnityInstanceProvider : IInstanceProvider
    {
        public IUnityContainer Container { set; get; }
        public Type ServiceType { set; get; }


        public UnityInstanceProvider()
            : this(null)
        {
        }

        public UnityInstanceProvider(Type type)
        {
            ServiceType = type;
            Container = new UnityContainer();
        }

        public object GetInstance(InstanceContext instanceContext, Message message)
        {
            return Container.Resolve(ServiceType);
        }

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

        public void ReleaseInstance(InstanceContext instanceContext, object instance)
        {

            var myInstance = instance as IDisposable;

            if (myInstance != null)
            {
                myInstance.Dispose();
            }
        }
    }
public class LoggingOperationBehavior : IOperationBehavior
{
	private readonly ILog _myLog;

	public LoggingOperationBehavior(ILog myLog)
	{
		_myLog = myLog;
	}

	public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
	{
		dispatchOperation.Invoker = new LoggingOperationInvoker(_myLog, dispatchOperation.Invoker, dispatchOperation);
	}
	
	public void Validate(OperationDescription operationDescription)
	{
	}
	
	public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)
	{
	}

	public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters)
	{
	}
}

At this point, we need to invoke the log. We need to specify an invoker that will be executed. This is why, we need to create a logging invoker which take the log that come from Unity.

public class LoggingOperationInvoker : IOperationInvoker
{
	private readonly IOperationInvoker _baseInvoker;
	private readonly string _operationName;
        private readonly string _controllerName;
	private readonly ILog _myLog;

	public LoggingOperationInvoker(ILog myLog, IOperationInvoker baseInvoker, DispatchOperation operation)
	{
		_myLog = myLog;
		_baseInvoker = baseInvoker;
		_operationName = operation.Name;
                _controllerName = operation.Parent.Type==null?"[None]":operation.Parent.Type.FullName;
	}
	
	public object Invoke(object instance, object[] inputs, out object[] outputs)
	{
		_myLog.Log("Method " + _operationName + " of class " + _controllerName + " called");
		try
		{
			return _baseInvoker.Invoke(instance, inputs, out outputs);
		}
		catch (Exception ex)
		{
			_myLog.Log(ex);
			throw;
		}
	}

	public object[] AllocateInputs() {return _baseInvoker.AllocateInputs();	}

	public IAsyncResult InvokeBegin(object instance, object[] inputs, AsyncCallback callback, object state)
	{
		_myLog.Log("Method " + _operationName + " of class " + _controllerName + " called");
		return _baseInvoker.InvokeBegin(instance, inputs, callback, state);
	}

	public object InvokeEnd(object instance, out object[] outputs, IAsyncResult result)	{return _baseInvoker.InvokeEnd(instance, out outputs, result);	}

	public bool IsSynchronous { get {return _baseInvoker.IsSynchronous;	}	}
}

This is where the log is really written. It uses the interface to log which came from Unity from the Factory. The log is written when the method is invoked.

How to shake (or vide) a html element

When your user does an error, it might be interesting to select the control and to make it shakes few seconds just to get the user attention. It’s not something you should do for every validation but some time, you may cross a situation where the user might be more confuse about which controls or elements he needs to take care of. Therefore, a way to do it is to shake the element on the screen and highlight this one.

The code in this post is not into the form of JQuery plugin but it should be. It’s more indented to be educational. The first part of the code show you that you need to call the method “Vibrate” that takes the element to shake as parameter.

var vibrateIndex = 0;
var selector;
//Animate the selector with the animation function
function Vibrate(item) {
    selector = $(item);
    var interval = 10;
    var duration = 500;
    vibrateIndex = setInterval(Vibe, interval);
    setTimeout(StopVibration, duration);
}

The second part is doing the animation of shaking the control. In fact, we are randomly moving the left and top position of the control and setting this one relative. This is important. Otherwise, the control won’t move. It also set the border to red.

//Animation
function Vibe() {
    var shake = 3;
    $(selector).stop(true, false)
        .css({
            position: 'relative',
            left: Math.round(Math.random() * shake) + 'px',
            top: Math.round(Math.random() * shake)  +'px',
            borderColor: 'red'
        });
    
};

The last part is executed when the animation is over. This is called by the setTimout method previously set with a duration.

//Remove all CSS applied to the selector
function StopVibration() {
    clearInterval(vibrateIndex);
    $(selector).stop(true, false)
                .css({ position: 'static',
                        left: '0px', 
                        top: '0px',
                        borderColor: ''});
};

This could be improved by having everything inside a JQuery plugin which would be cleaner. The problem with the code above is that we use global variable to remember to control that is implicated into the animation and the interval reference is also global.

You can see a working example here.

Plugin

Here is the JQuery Plugin version : http://jsfiddle.net/kEVd3/3/

(function($){ 
    $.fn.vibrate = function(options) {
        options = $.extend({}, $.fn.vibrate.defaultOptions, options);     
        var control = $(this);
        var vibrateIndex = 0;
        var selector;
        
        vibrateIndex = setInterval(vibe, options.interval);
        setTimeout(stopVibration, options.duration);
        function vibe() {
            var shake = 3;
            $(control).stop(true, false)
                .css({
                    position: 'relative',
                    left: Math.round(Math.random() * shake) + 'px',
                    top: Math.round(Math.random() * shake)  +'px',
                    borderColor: 'red'
                });
            
        };

        function stopVibration() {
            clearInterval(vibrateIndex);
            $(control).stop(true, false)
                        .css({ position: 'static',
                                left: '0px', 
                                top: '0px',
                                borderColor: ''});
        };
        return this;
   } 
    
    $.fn.vibrate.defaultOptions = {
         interval : 10
       , duration : 500
    }
})(jQuery);

Here is an example of how to use it :

   $('#btnShake').click(function(){
       $('input[type=text]').vibrate();
                        });

You can also specify option like the duration:

   $('input[type=text]').vibrate({duration:3000});

I’ll do a post concerning how to create a JQuery plugin soon to explain in detail how and why the plugin has been created this way. For the moment, you can refer to this Microsoft’s tutorial which is very fine.

How to display a list by category with Linq and Grouping

If you are using Asp.Net MVC, you could have a set of entities which are going to be mapped from your model to your view model. Here is a sample of a situation where we have an exercise that is related to a muscle. It’s a 1 to n relationship where the exercise are linked to a single muscle, but the muscle could be trained by many exercises.

MuscleAndExercise

As you can see, the mapping between the view model and the model is simple, the side of the exercise, where only one instance of muscle could be attached, is merged into the view model of the exercise. This one is called ExerciseViewModel in the following class diagram.

ExerciseViewModel

So, if you want to display a list of exercise you can get the whole list by getting from your database context the list of exercise. Here is the partial view that get a list of ExerciseViewModel and dress a list of all exercises inside an Html list.

@model IEnumerable<ViewModels.ExerciseViewModel>
<ul class="exercises-container-source">
@foreach (var exercise in Model)
{      
	<li data-exercise-id="@exercise.Id">
		<span class="exerciseName">@exercise.Name</span>
	</li>
}    
</ul>

Let say that now you want to display exercises by their muscle group. This is not a problem from the class point of view because the ExerciseViewModel contain directly the MuscleId and MuscleName.

The “old school” way to do it would be to sort the collection by the exercise name, then to loop through the collection and every time the muscle group change, to write the muscle name.

@model IEnumerable<ViewModels.ExerciseViewModel>
<ul class="exercises-container-source">
int lastId = -1;
@foreach (var exercise in Model.OrderBy(d=>d.MuscleId))
{      
	if(lastId != exerciseMuscleId)
	{
		if(lastId != -1)
		{
			</ul>
		}
		<h3>@exercise.MuscleName</h3>
		<ul class="exercises-container-source">
		lastId = exerciseMuscleId;
	}
	<li data-exercise-id="@exercise.Id">
		<span class="exerciseName">@exercise.Name</span>
	</li>
}    
</ul>

This kind of code is not particularly great and invokes some logic to understand it correctly. First, we have to handle the last muscle id into a variable and change its value depending of a comparison. Second, we have to handle the creation of the Html tag “UL” because header tag (h3) cannot be inserted between “UL” tag. This mean that we need to open and close the “UL” tag every time we have an exercise.

With Linq and Grouping we can simplify by a lot this whole process. The main advantage of the next methodology is that without modifying any backend classes the view page will be cleaner and easier to understand.

@model IEnumerable<ViewModels.ExerciseViewModel>   
@foreach (var exerciseGroup in Model.GroupBy(d => new { Id = d.MuscleId, Name = d.MuscleName }))
{
    <h3>@exerciseGroup.Key.Name</h3>
    <ul class="exercises-container-source">
    @foreach (var exercise in exerciseGroup)
    {
        <li data-exercise-id="@exercise.Id">
            <span class="exerciseName">@exercise.Name</span>
        </li>
    }
    </ul>
}

Here you go. No more integer to know that last exercise, no anymore weird handling of the “UL”. It’s very clear so the maintainability of the code is easier. As you can see, we first group every exercise by MuscleId and MuscleName. We need to have both because we want to show the name. As you can see, we also display the name which is part of the key. With Visual Studio 2010 and 2012, your anonymous type will be handled by Microsoft Intellisense and you will see that your Key’s property have the Id and the Name properties. After displaying the muscle name, you just need to loop through the collection of exercise and display the exercise name.

I hope that you will be able to use the Linq Grouping functionality in you application more often because it can help greatly simple task to be cleaner.

Linq Aggregate to concatenate string with a comma

If you have an array that you want to flatten into a string with a comma between each entry, you could use Linq with a one liner delegate to reach this goal.

string flatten = inputs.Aggregate((current, next) => 
                                 string.Format("{0}, {1}", current, next))

This is quite powerful as you can see, you do not have to do validation to know if you have reach the last entry to not add a trailing comma. Without Linq and the aggregate function, you would have to loop and to verify this condition.

string flatten = string.Empty;
for(int i = 0 ; i < inputs.Length ; i++)
{
   if(i!=(i.Length-1))
   {
       flatten += str + ", ";
   }
   else
   {
       flatten += str;
   }
}

I don’t know for you, but I found more easy to read the Aggregate method than the second snippet of code.