Value Injector – How to Use

One of the main tasks that you may face during development is how to translate from one object to another that is very similar in term of properties and attributes. There are many ready to use code to be downloaded from Internet and use.

I tried Value Injector DLL; it was good enough for my needs and it satisfy my needs in very good way. you can download the Value Injector DLL from this link.

The overall performance of this component was very good and it didn’t hit the performance of the system that I’m working on.

The Basic usage of this component is as follow.

using Omu.ValueInjecter;
public class DemoClass { 
 public void MethodInjector(mySourceClass source)
  {
   MyClass destination = new MyClass();
   destination.InjectFrom(source);
   //inject using your own injector calss.
   destination.InjectFrom < MyInjection > (source);
  }
}

The good thing about ValueInjector is that you can build your own Injector class and use it; that is needed if the current implementation for ValueInjector is not satisfying your needs.

for more information about value injector, please visit this link

Creating Required Literal for MVC with Razor rendering engine

In web applications, It is became a standard to have a symbol indicating if the field is required or not. This symbol maight be a star, icon or any verbiage that a client ma requested to have. It is a good practice to have the logic that render this symbol in one place and have all of your views using it. You can do that easily in standard ASPX pages, and it is the same on MVC using Razer rendering engine (cshtml/vbhtml). For MVC you need to create a custom HTML helper that do the job for you, and using it in your views cross the board. Below is a sample HTML helper method

 

public static MvcHtmlString RequiredFieldIcon(this HtmlHelper helper)
{
TagBuilder tag = new TagBuilder(“span”);
tag.AddCssClass(“color-color-text”);
tag.Attributes.Add(“title”, “Field is required”);
tag.SetInnerText(“>> “);
return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
}

In above method, the symbol is as simple as ‘>>’ in red color; using CSS class for that. it might be more complicated UI control and you can customize it based on your requirement. You can use this method just as if it is one of the out of the box HTML helpers that shipped with MVC; you just need to make sure you are including the namespace of the class that hosting this HTML helper method.

@Html.RequiredFieldIcon()

Using Google Calculator for Money Exchange

While working in one of the projects, one of the main requirements was to do money exchange from a specific currency to another. When I was looking into this functionality, I thought that is going to be a hard thing to be implemented as it is touching a critical area related to money. in fact, Thanks to Google calculator.. implementing such a functionality was a very easy job and it took from me like 1 hour to be done… Google Calculator has a very easy to be consumed APIs. below code explaining how could I consume Google Calculators to get the up to date exchange rate between 2 different currencies.

   /// <summary>
/// Currency Exchange Service that is responsible
/// </summary>
public class CurrencyExchangeService
{private static string GoogleCalculatorApiUrl
{
get
{
return “http://www.google.com/ig/calculator?hl=en&q={0} {1} to {2}”;
}
}

/// <summary>
/// Do currency Exchange between currencies.
/// </summary>
/// <param name=”fromCurrencyCode”>Source Currency Code</param>
/// <param name=”toCurrencyCode”></param>
/// <param name=”amountToConvert”></param>
/// <param name=”roundedDecimalPoints”></param>
/// <returns></returns>
public static decimal ConvertCurrency(string fromCurrencyCode, string toCurrencyCode, decimal amountToConvert = 1, int roundedDecimalPoints = 4)
{
if (fromCurrencyCode == null)
throw new ArgumentNullException(“fromCurrencyCode”);
else if (toCurrencyCode == null)
throw new ArgumentNullException(“toCurrencyCode”);
else if (amountToConvert < 0)
throw new ArgumentOutOfRangeException(“amountToConvert”);

if (string.Compare(fromCurrencyCode, toCurrencyCode, true) == 0)
return amountToConvert;
else if (amountToConvert == 0)
return 0;

var request = HttpWebRequest.Create(string.Format(GoogleCalculatorApiUrl, amountToConvert, fromCurrencyCode, toCurrencyCode));
request.Timeout = 5000;
using (var response = request.GetResponse())
{
using (var stream = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(“iso-8859-1”)))
{
Match match;
if ((match = Regex.Match(
stream.ReadLine(),
@”{lhs: “”(?<From>[0-9.\s]+)(.*?)””,rhs: “”(?<To>[0-9.\s]+)(.*?)””,error: “”(?<Error>(.*?))””,icc: (true|false)}”,
RegexOptions.Singleline | RegexOptions.IgnoreCase)
).Success)
{
//Parse response from Google Calculator.
var result = new
{
From = Regex.Replace(match.Groups[“From”].Value, “[^0-9.]”, string.Empty),
To = Regex.Replace(match.Groups[“To”].Value, “[^0-9.]”, string.Empty),
Error = match.Groups[“Error”].Value
};

if (string.IsNullOrEmpty(result.Error))
{
return Math.Round(Convert.ToDecimal(result.To, CultureInfo.InvariantCulture), roundedDecimalPoints);
}

throw new Exception(string.Format(“Converter error: {0}.”, result.Error));
}

throw new Exception(“Response format error.”);
}
}
}
}

How to Install OneNote Printer to Simulate Printing Process

One of the components that I worked on recently is printing components and I got into a need to test how things going when I print out to the printer. It was a costly thing to keep printing out into a hard copy papers. one of the ultimate solutions for this is to simulate the printing process. so I start using OneNote printer (which is installed automatically once you install MS OneNote product). it was brilliant idea to use it and it worked just perfectly.

For some reasons the OneNote printer got deleted from my machine, and I got into a need to use it again; I look up for help and I found this article that helped me on reinstalling the printer again http://speedstug.com/node/85… This solved the issue that I faced.

Visual Studio Achievements Extension

I believe Visual Studio Achievement extension is a very nice plugin to have it on Visual Studio. It is running in the background while you are doing your daily tasks to analyzes your actions and according to the progress you are going to get an achievement badge(s).

Most often developer hard work and efforts will not be noticeable, till he/she achieved a huge thing in short time or discover a hidden bug within a very short period. But having VS achievement in place, this is will not the case again. The tool will analyze actions on Visual Studio and unlocked the deserved achievement to the developer according to actions. These unlocked achievements will be posted to Channel 9 profile for the developer (thus having profile on Channel 9 is a prerequisite ).

Once you have an achievement granted, a popup will appear on the right-bottom corner of your screen with your achievement badge and you can check your achievement on your channel 9 profile at any time.

This extension is live now and you can install it from extension manager at your Visual Studio 2010. after installing it, you will be asked to restart your Visual Studio, after the first run, you will be asked to login with your Channel 9 profile.

I believe this extension represent a new way for developers to highlight their skills in a common way. The same rules applied on everybody…

It should not be the judge on developer experience but I think it is very good extension that will create a very good atmosphere between developers for a fair competition

Sync Data Between SQL Server and SQL Azure

couple of weeks ago I had discussion with a friend of mine about cloud technologies form Microsoft. After we finished that discussion I start thinking of what scenarios that we maybe come over while developing a real enterprise application on cloud. One scenario came into mind about that; What if I get into a need to synchronize data between SQL Azure on the cloud and SQL server on-premises? is this will be an easy thing to be accomplished? Sudhesh through the below video illustrate how to setup data sync between a SQL Azure and SQL Server databases.

Java Script Curly Braces place

I got annoyed while writing some Java Script inside Visual studio, because Visual Studio keep placing the curly braces at the same line as the control statement which what is called K&R style. as I am coming form C# background I would like to have the braces at the new line just like how the C# code got formatted; this style called Allman style. I never thought that might has any effect of how the Java Script interpreter might interpret the code and thus affect the end result.

so I decided to do a research why Visual Studio formatting Java Script in K&R style rather than Allman style. I got into a very nice article by Dave Ward that explained to me why is that by an example. The article explained in details how it would matter the position for the curly braces in certain cases because of the nature of Java Script interpreter. Please follow this link to read the article

TransformXml Task Failed Unexpectedly Error Message While Publishing Web Project in Visual Studio 2010

 

TransformXml task failed unexpectedly

one of the strange issues that I faced yesterday while trying to publish one of the web projects that I am working on. although the project compilation was working fine and when I run the project locally on my PC it was working fine without any issue.

After investigating for this issue I found the cause of this issue because the Web.config file was containing a special character inside it. so what I did is encode the special character then try to publish it again and things worked for me fine.

I had a very large Web.config file so looking for the special characters was not an easy job. I wrote a regular expression on Visual Studio that helped me on accomplished this job. so I would recommend to use regular expression to search Web.config instead of looking for the special characters inside the web.config file.

Performance Troubleshooting (ANTS tool)

it happened once that a client raise an issue regarding to poor performance at certain area on an application that I was working on. That area was working perfectly on my environment, but at their environment it was not like that. I could not duplicate their environment locally because of security restrictions rules we have. Tracing code and do debugging was not helpful. Thus I decided to look into a tool that will help me on this mission.

I found a very nice tool that help me very much on tracing and figuring out the bottleneck on my application, that tool is called ANTS from Red-Gate. I strongly recommend to try this tool.

The good thing about this tool is that it is integrated inside the visual studio which making your life much easier when you want to start troubleshoot the performance issue. another thing that making it great is when you launch it from the visual studio, the result will be some sort of tree diagram for your code according to the resources utilization. Part of that diagram is the ability to see the code snap that you concerning about. also part of this output is an attribute that is showing you how many a certain method got called, you will find this very helpful because it will make you pay attention to methods that is getting called more than the expected numbers.

Red Gate providing this tool as a free trial to let you try it and make sure it is fitting to your business. you can check more about it by clicking here

Parallelism in .Net 4.0

One of the major enhancements that Microsoft has accomplished is enhancing the parallelism in many .Net class library. that is making things much faster and using the hardware in more effective way. in .Net 3.5 and earlier versions of .Net framework, wee have to using Threads to accomplish the same job. Actually .Net 4.0 is using Threads but that is internally at the .Net class library and it will be hidden from your code which is making your life much easier.

The new Parallelism feature of ..Net framework categorized into one of the folllowings:

1) Task Parallel:

including parallel implementaion for FOREACH and FOR loops letting you define the concurrent, Async tasks without working directlying into threads thing,

2) Parallel LINQ (PLINQ):

Significantly improves the performance of LINQ.

3) Data Structure for Parallel Programming:

including a high performance collection of classes with lock-free and at the same time it is thread safe including lightweight objects.

4) Tools to facilitate the Parallel Programming:

like debugger windows for tasks and parallel stacks.