Inspired by Mohamed Mahmoud’s blog posting How to: Create Interfaces with Static Methods via IL? I wrote another sick example on IL (Intermediate Language) to show you how different is the world behind compilers. Tonight I have enough of exceptions, I want to throw some strings! Let’s do it!
Throwing exception in IL
As a first thing take a look at the following code written in IL. In short this code defines class with two methods. Run() is entry point and it is run automatically when compiled assembly is executed from command line. ThrowSomething() is method that throws exception. This exception is caught and program terminates without any errors. I borrowed this code from Vijay Mukhi’s IL book, Chapter 10 “Exception Handling”.
.assembly StringMess {}
.class private auto ansi Program extends [mscorlib]System.Object
{
.method public hidebysig static void Run() il managed
{
.entrypoint
.locals (class [mscorlib]System.Exception V_0)
.try
{
call void Program::ThrowSomething()
ldstr "Bye"
call void [mscorlib]System.Console::WriteLine
(class System.String)
leave.s IL_001e
}
catch [mscorlib]System.Exception
{
stloc.0
ldstr "Exception was thrown!"
call void [mscorlib]System.Console::WriteLine
(class System.String)
leave.s IL_001e
}
IL_001e: ldstr "Finish"
call void [mscorlib]System.Console::WriteLine
(class System.String)
ret
}
.method public hidebysig static void ThrowSomething()
il managed
{
newobj instance void [mscorlib]System.Exception::.ctor()
throw
}
}
Everybody who is familiar with C# should be able to understand this code at least in some parts. Now let’s see what is the output of this method. As image on right shows it is nothing special. We threw exception, it was handled and program terminated normally. Just like we expected.
Let’s throw some strings now
Now let’s modify this code so it should do something we expect to end up with error. I add one more catch clause. This additional catch catches String. To test it I will do exactly what this catch expects – I will throw out the String. Here is the code.
.assembly StringMess {}
.class private auto ansi Program extends [mscorlib]System.Object
{
.method public hidebysig static void Run() il managed
{
.entrypoint
.locals (class [mscorlib]System.Exception V_0)
.try
{
call void Program::ThrowSomething()
ldstr "Bye"
call void [mscorlib]System.Console::WriteLine
(class System.String)
leave.s IL_001e
}
catch [mscorlib]System.Exception
{
stloc.0
ldstr "Exception was thrown!"
call void [mscorlib]System.Console::WriteLine
(class System.String)
leave.s IL_001e
}
//
// CATCH STRING
//
catch System.String
{
stloc.0
ldstr "String was thrown"
call void [mscorlib]System.Console::WriteLine
(class System.String)
leave.s IL_001e
}
IL_001e: ldstr "Finish"
call void [mscorlib]System.Console::WriteLine
(class System.String)
ret
}
.method public hidebysig static void ThrowSomething()
il managed
{
//newobj instance void [mscorlib]System.Exception::.ctor()
//
// THROW STRING
//
ldsfld string [mscorlib]System.String::Empty
throw
}
}
We can expect that this code doesn’t compile, but it does. As a next thing we may expect that running this code some runtime error occurs, but no, there is no runtime error. We can expect that exception handling lands in catch for Exception… we can expect many things but the result is here.
I bet at least half of readers expected something else but yes, we just threw string and we also caught it. But why C# and VB.NET give us errors when we try to compile code like this? Well, it is a compiler level limitation. It is not related to CLR as we just saw.
Playing with Visual Studio
Let’s play now with Visual Studio. I created console application, compiled previous example as DLL and referenced it from my console application. I want to know what happens when string is thrown and caught. Does it affect compiler somehow?
using System;
namespace ConsoleExamples
{
class Program
{
static void Main(string[] args)
{
StringMess.Program.Run();
Console.ReadLine();
Console.ReadLine();
}
}
}
Well, it does not. Let’s try to call ThrowSomething() method now. Maybe something interesting happens.
using System;
namespace ConsoleExamples
{
class Program
{
static void Main(string[] args)
{
StringMess.Program.ThrowSomething();
Console.ReadLine();
}
}
}
Okay, now something happens. Our application is not able to handle the situation and it throws RuntimeWrappedException.
RuntimeWrappedException is located under System.Runtime.CompilerServices namespace and as documentation sais it is here to maintain compatibility between languages. The common language runtime (CLR) wraps objects that do not derive from Exception in a RuntimeWrappedException object. This is why we got exception and not completely crashed application.
TIP! If you want to find out more about IL there is very good book I can suggest: Expert .NET 2.0 IL Assembler by Serge Lidin. I have read this book and also the idea of this posting is taken from this book. If you are interested in my other postings about IL and compiling results then please take a look at Behind the Compiler category.
Okay, it’s couple of minutes over midnight here and it is time to throw some real strings, I guess. Good night!
I wrote some object to object mapping code and introduced it in some of my previous postings about performance. As I received 22x performance raise when trying out different mapping methods and it is now time to make my code nice. In this posting I will show you how I organized my code to classes. Yes, you can use my classes in your work if you like. :)
To get fast overview of my mapping journey so far I suggest you to read the following postings from this blog:
In this posting I will create base class for my O/O-mappers. Also I will provide three implementations of O/O-mapper. There will be reflection based, dynamic code based and IL-instructions based implementations.
NB! Although implementations given here work pretty nice they are very general and therefore not maximally optimal. I will provide faster implementations in my next posting about object to object mapper.
Creating mapper base
I wrote simple base class that provides base type and some common functionality to mapper implementations. Common functionality comes in two methods: GetMapKey() and GetMatchingProperties(). First one of them creates unique string key for two mapped types. Second one queries source and target types and decides what properties are matching. These methods are protected because there is no reason for external code to call them. If you write your own implementations you can override these methods is you like.
public class PropertyMap
{
public PropertyInfo SourceProperty { get; set; }
public PropertyInfo TargetProperty { get; set; }
}
public abstract class ObjectCopyBase
{
public abstract void MapTypes(Type source, Type target);
public abstract void Copy(object source, object target);
protected virtual IList<PropertyMap> GetMatchingProperties
(Type sourceType, Type targetType)
{
var sourceProperties = sourceType.GetProperties();
var targetProperties = targetType.GetProperties();
var properties = (from s in sourceProperties
from t in targetProperties
where s.Name == t.Name &&
s.CanRead &&
t.CanWrite &&
s.PropertyType == t.PropertyType
select new PropertyMap
{
SourceProperty = s,
TargetProperty = t
}).ToList();
return properties;
}
protected virtual string GetMapKey(Type sourceType,
Type targetType)
{
var keyName = "Copy_";
keyName += sourceType.FullName.Replace(".", "_");
keyName += "_";
keyName += targetType.FullName.Replace(".", "_");
return keyName;
}
}
Properties query given here is primitive one. My own query is far more complex and has many more conditions. I don’t want to drive your attention away from main topic and that’s why I am using simple implementation of query here. Querying result is property map for two given types. Every property of source type that fits is matched to property of target type.
ObjectCopyReflection – reflection based implementation
My first implementation was based on reflection. It made heavy use of it and was not as optimal as I wanted. Of course, it has also bright side – it is simplest one to read and understand. Just open Google if you are not familiar with reflection and it takes you couple of minutes to understand how this implementation works.
public class ObjectCopyReflection : ObjectCopyBase
{
private readonly Dictionary<string, PropertyMap[]> _maps =
new Dictionary<string, PropertyMap[]>();
public override void MapTypes(Type source, Type target)
{
if (source == null || target == null)
return;
var key = GetMapKey(source, target);
if (_maps.ContainsKey(key))
return;
var props = GetMatchingProperties(source, target);
_maps.Add(key, props.ToArray());
}
public override void Copy(object source, object target)
{
if (source == null || target == null)
return;
var sourceType = source.GetType();
var targetType = target.GetType();
var key = GetMapKey(sourceType, targetType);
if (!_maps.ContainsKey(key))
MapTypes(sourceType, targetType);
var propMap = _maps[key];
for (var i = 0; i < propMap.Length; i++)
{
var prop = propMap[i];
var sourceValue = prop.SourceProperty.GetValue(source,
null);
prop.TargetProperty.SetValue(target, sourceValue,
null);
}
}
}
If you look at Copy() method you can see that this method is pretty safe – it checks if mapping is for types already there and if it is not it creates it. This method was not perfect one because in my test environment it took about 0.0238 ms to copy matching properties from one object to another. Using this class I got the following result: 0,0240 ms.
ObjectCopyDynamicCode – dynamically compiled C#
Next implementation was remarkably faster. I used dynamically generated C# code and it gave me 0,0055 ms as result. Implementation for dynamically compiled C# mapper is here.
public class ObjectCopyDynamicCode : ObjectCopyBase
{
private readonly Dictionary<string, Type> _comp =
new Dictionary<string, Type>();
public override void MapTypes(Type source, Type target)
{
if (source == null || target == null)
return;
var key = GetMapKey(source, target);
if (_comp.ContainsKey(key))
return;
var builder = new StringBuilder();
builder.Append("namespace Copy {\r\n");
builder.Append(" public class ");
builder.Append(key);
builder.Append(" {\r\n");
builder.Append(" public static void CopyProps(");
builder.Append(source.FullName);
builder.Append(" source, ");
builder.Append(target.FullName);
builder.Append(" target) {\r\n");
var map = GetMatchingProperties(source, target);
foreach (var item in map)
{
builder.Append(" target.");
builder.Append(item.TargetProperty.Name);
builder.Append(" = ");
builder.Append("source.");
builder.Append(item.SourceProperty.Name);
builder.Append(";\r\n");
}
builder.Append(" }\r\n }\r\n}");
// Write out method body
Debug.WriteLine(builder.ToString());
var myCodeProvider = new CSharpCodeProvider();
var myCodeCompiler = myCodeProvider.CreateCompiler();
var myCompilerParameters = new CompilerParameters();
myCompilerParameters.ReferencedAssemblies.Add(
typeof(LinqReflectionPerf).Assembly.Location);
myCompilerParameters.GenerateInMemory = true;
var results = myCodeCompiler.CompileAssemblyFromSource
(myCompilerParameters, builder.ToString());
// Compiler output
foreach (var line in results.Output)
Debug.WriteLine(line);
var copierType = results.CompiledAssembly.GetType(
"Copy." + key);
_comp.Add(key, copierType);
}
public override void Copy(object source, object target)
{
if (source == null || target == null)
return;
var sourceType = source.GetType();
var targetType = target.GetType();
var key = GetMapKey(sourceType, targetType);
if (!_comp.ContainsKey(key))
MapTypes(sourceType, targetType);
var flags = BindingFlags.Public | BindingFlags.Static |
BindingFlags.InvokeMethod;
var args = new[] { source, target };
_comp[key].InvokeMember("CopyProps", flags, null, null,
args);
}
}
This implementation is way better than previous one. It takes 0,0058 ms per copying operation. The code is not so simple to read and understand but we got better performance.
ObjectCopyLcg – dynamically generated IL-code
Our last implementation is based on LCG (Lightweight Code Generation) and this code has best performance as you saw from the chart given in LCG posting. Here is the code of LCG implementation of object copy class.
public class ObjectCopyLcg : ObjectCopyBase
{
private readonly Dictionary<string, DynamicMethod> _del =
new Dictionary<string, DynamicMethod>();
public override void MapTypes(Type source, Type target)
{
if (source == null || target == null)
return;
var key = GetMapKey(source, target);
if (_del.ContainsKey(key))
return;
var args = new[] { source, target };
var mod = typeof(Program).Module;
var dm = new DynamicMethod(key, null, args, mod);
var il = dm.GetILGenerator();
var maps = GetMatchingProperties(source, target);
foreach (var map in maps)
{
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Ldarg_0);
il.EmitCall(OpCodes.Callvirt,
map.SourceProperty.GetGetMethod(), null);
il.EmitCall(OpCodes.Callvirt,
map.TargetProperty.GetSetMethod(), null);
}
il.Emit(OpCodes.Ret);
_del.Add(key, dm);
}
public override void Copy(object source, object target)
{
var sourceType = source.GetType();
var targetType = target.GetType();
var key = GetMapKey(sourceType, targetType);
var del = _del[key];
var args = new[] { source, target };
del.Invoke(null, args);
}
}
Now let’s see how well this implementation performs. The result is a little bit unexpected: 0,0084 ms. Okay, there is a little gotcha but let it be your homework if you have nothing better to do.
Test method
Here is my simple test method that measures how much time each implementation takes with given to objects. After measuring it writes results to console window. You can use this code to make testing easier.
public static void TestMappers(object source, object target)
{
var mappers = new ObjectCopyBase[]
{
new ObjectCopyReflection(),
new ObjectCopyDynamicCode(),
new ObjectCopyLcg()
};
var sourceType = source.GetType();
var targetType = target.GetType();
foreach (var mapper in mappers)
{
mapper.MapTypes(sourceType, targetType);
var stopper = new Stopwatch();
stopper.Start();
for (var i = 0; i < 100000; i++)
{
mapper.Copy(source, target);
}
stopper.Stop();
var time = stopper.ElapsedMilliseconds / (double)100000;
Console.WriteLine(mapper.GetType().Name + ": " + time);
}
}
Summary
In this posting I showed you how I organized my previously written dirty code to classes and achieved better readability and maintainability of code. Abstract base class serves also very well – I am able to cast different mapper instances to base type and therefore it is easier for me to measure their performance and to use them with IoC containers like Unity.
In the next posting about object to object mapper I will show you how to modify these classes to gain better performance.
In my previous posting about ASP.NET MVC performance I showed you how to combine resources like scripts, style sheets and images. In this posting I will show you how to minimize resources so we don’t waste the bandwidth we got.
Optimizing scripts and style sheets
Scripts and style sheets can be optimized by removing unnecessary characters from files. Usually these smaller versions are called minimized scripts and style sheets. For smaller resources you have no remarkable effects but for larger resources you may win in tens or even hundreds of kilobytes of file sizes. The process of decreasing resource size this way is called minifying.
jQuery and other popular JavaScript libraries come in two versions usually: original scripts and minified scripts. To minify custom scripts you can use custom tools like:
Feel free to use these tools to minify your own scripts.
In our previous version we decreased the number of requests that browser has to do when downloading our page. We used Combres to combine scripts and styles to packages that are downloaded only once as separate file for scripts and the other for styles. Now let’s replace scripts with their minified versions. Our script block looks like this now:
<script type="text/javascript" src="/Scripts/jquery-1.3.2.min.js">
</script>
<script type="text/javascript" src="/Scripts/jquery-ui-1.7.2.custom.min.js">
</script>
<script type="text/javascript"src="/Scripts/fullcalendar.min.js">
</script>
Let’s see now how much better our situation is now.
| Metric | Before | Now | Difference |
| No. of requests | 9 | 9 | 0 |
| Size of output | 448.8 KB | 340.1 KB | 108.7 KB |
| Time to load | 1.30 sec | 1.12 sec | 0.18 sec |
Well, size of output is now 108.7KB smaller than before. For 100 requests we save about 10.87MB of traffic. Not bad at all.
Optimizing images
You can also optimize images. By example, some of your PNG images can be way smaller when they are saved as JPG or GIF. Same way you can save other formats to PNG to get smaller files. If you win 1KB of size then it makes 1MB less traffic for 1000 requests.
As I am not designer I am not very familiar with all choices you have. But here are some tutorials you may find interesting:
If you are using designs by professional web designer you usually should not be afraid that you are the one who has to optimize images. But if it goes like it generally goes in the world then you should know at least some tricks.
Conclusion
Minifying scripts and styles and optimizing images may give us way smaller output compared to original scripts and images. Of course, there are more ways how to get output smaller and how to get less requests. In the next posting I will show you how to get better results than ones we got here.
I wrote a small postings series about how to optimize ASP.NET MVC applications. This posting is small introduction to series and it also introduces first two optimization steps: resources and images combining.
Totally non-optimal page
As this posting is also introduction to this little series I give you short overview about what is non-optimal page. Main characteristics of non-optimal page are:
- too heavy mark-up (contains a lot of constructs that can be avoided by using style sheets),
- non-minimized resources like scripts and style sheets,
- non-combined resources,
- repeatedly used images are served as separate images,
- views are too heavy (by example, view contain repeated JavaScript),
- no use of cache,
- no use of output compression.
These are all small points if you look at them separately but they work as Chinese torture – no one water drop kills you but the effect of their cooperation is fatal.
In this small series I will introduce you some ASP.NET MVC optimization methods you can use on your applications. In all postings we will look how much one or another optimization method raise performance or how much it decreases size of output and how many bytes of output can be used from cache.
Initial state
Our initial state is pretty sad. We have simple calendar view like show on the following screenshot.
Currently it takes 13 requests to load, output is 448.8 KB at size and it takes on my local machine about 1.3 sec to load. What we want to do is to minimize values of all these characteristics as much as possible.
Combining resources
If your MVC application uses some certain collection of scripts almost for every page then you may include this scripts on master page. Same stays true for style sheets. You can use MVC Script Combiner to make these scripts and style sheets to be downloaded as one file. This way you can minimize the number of requests made to server.
Take a look at the following script block (yes, I don’t use minimized versions of scripts in this posting).
<link href="/Content/Site.css" rel="stylesheet" type="text/css" />
<link href="/Content/jquery-ui-1.7.2.custom.css" rel="stylesheet" type="text/css" />
<link href="/Content/fullcalendar.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="/Scripts/jquery-1.3.2.js"></script>
<script type="text/javascript" src="/Scripts/jquery-ui-1.7.2.custom.min.js"></script>
<script type="text/javascript" src="/Scripts/fullcalendar.js"></script>
Now I take some code from my posting ASP.NET MVC: How to combine scripts and other resources. Resource combiner is named now as Combres and you can find a good article about it from Code Project: Combres - WebForm & MVC Client-side Resource Combine Library.
We can combine all these scripts to one file and all our style sheets to another. They are text files and adding them one next to another causes no problems as long as they contain same content (scripts or style definitions). Previously referenced examples help you to apply script combining to your application. I suggest you to do it because we will use Combres also in my next MVC optimization posts.
Optimization gave us some first results: we have no 9 requests instead of 13. Combined scripts are cached so we don’t have any additional overhead in server-side.
Combining images
It is also possible to combine images (let’s say icons) to one image and show correct part of resulting image where specific icon is needed.
First image on right shows jQueryUI icon map. All icons are on same image and showing specific image as icon is achieved by using style sheets. Style sheet uses this image as background and positions it so that only image that is required is show.
Second image on right shows highlighted Next button in jQueryUI DatePicker component. This is the same icon you can see on the first image.
Here is the computed style of the container of this image:
background-image:
url(ui-icons_ef8c08_256x240.png);
display: block;
height: 16px;
left: 50%;
margin-left: -8px;
margin-top: -8px;
overflow-x: hidden;
overflow-y: hidden;
position: absolute;
text-indent: -99999px;
top: 50%;
width: 16px;
There are 173 icons on this one image. To download them all separately it takes about 173 requests to server. Now we win by 172 requests. When we have 100 visitors visiting our web page almost at same time then we win by 17200 requests to web server. I think it is very good result as requests are pretty expensive objects to handle in server.
You can find very good tutorial about this topic from WebSiteOptimization.com: CSS Sprites: How Yahoo.com and AOL.com Improve Web Performance.
Conclusion
In this posting we used resource combining and image combining. As we have images already combined this optimization has no effect to end result. Image combining was discovered just to give you some idea about how much you can save performance when applying it. Script and style sheets combining gave as first small results – we saved 4 requests to web server. In next postings we will go further and apply more optimizations.
Today I gave last performance boost to my property values copying mechanism. I would like to thank my readers Ron and David to remind me Lightweight Code Generation (LCG) and pointing me out aussie bloke blog entry Generic copy object using Lightweight Code Generation. In this posting I will show you last performance boost and put down a summary about my experiment this far.
To get better idea about what I have done this far read my blog postings Using LINQ and reflection to find matching properties of objects and Performance: Using dynamic code to copy property values of two objects.
Copying matching properties – Lightweight Code Generation (LCG)
The last performance boost was achieved by using LCG. I created static dictionary to cache generic delegates that invoke dynamically generated methods that perform actual copying. These methods are generated using Intermediate Language (IL) opcodes. Here is the code.
delegate void CopyPublicPropertiesDelegate<T,TU>
(T source, TU target);
static Dictionary<string, object> _del =
new Dictionary<string, object>();
static void GenerateCopyDelegate<T, TU>()
{
var className = GetClassName(typeof(T), typeof(TU));
var args = new[] {typeof(T), typeof(TU)};
var mod = typeof(Program).Module;
var dm = new DynamicMethod(className, null, args, mod);
var il = dm.GetILGenerator();
var maps = _maps[className];
foreach (var map in maps)
{
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Ldarg_0);
il.EmitCall(OpCodes.Callvirt,
map.SourceProperty.GetGetMethod(), null);
il.EmitCall(OpCodes.Callvirt,
map.TargetProperty.GetSetMethod(), null);
}
il.Emit(OpCodes.Ret);
var del = (CopyPublicPropertiesDelegate<T,TU>)dm.CreateDelegate(typeof(CopyPublicPropertiesDelegate<T,TU>));
_del.Add(className, del);
}
static void CopyUsingLcg<T, TU>(T source, TU target)
{
var sourceType = source.GetType();
var targetType = target.GetType();
var className = GetClassName(sourceType, targetType);
var del = (CopyPublicPropertiesDelegate<T, TU>)
_del[className];
del.Invoke(source, target);
}
The best result in my last posting was 0,0055 milliseconds (it was measured as average over 100.000 copy operations). LCG gives even better result: 0,0018 milliseconds! It is 3 times better than previous optimization.
Summary
Well… after four tries my results are as follows. Third column shows how many times performance grew compared to previous optimization. Fourth column show how much performance grew compared to first and unoptimized version.
Why I compare results to first one that is completely dumb and non-optimized version? Well… don’t forget that out there are people in hurry (by example, soldiers in death march projects). And there are also beginners who are not aware of these more complex optimization methods. These two cases are major dangers where performance problems are naturally coded. You can see here how much you can do for performance when using more complex optimization methods. I think performance raise ~22.4 times is not unnoticeable small thing.
Conclusion
Can we go any further from here? Yes, we can. The code you have seen so far sits in static class that is compiled to command line application. As a next thing I want to make this code reusable for different applications. I have some ideas but I have to think what is best solution in my scenario. But you will hear about this topic soon. :)
I found very good jQuery component called FullCalendar. My special favorites are agenda views because they make this calendar really useful in business applications. In this posting I will show you how to use FullCalendar with ASP.NET MVC.
Update: source code of this project is available at CodePlex. Please visit MVC Time Planner page for further information and downloads.
Prerequisites
You need the following JavaScript components in your MVC project:
Download these components and include them to your ASP.NET MVC project. If you have problems then take a look at the image on right – you can what files I included and where they are located. Click on the image to see it at full size.
I included jQueryUI styles for one good reason – I am not designer but ol’ school MS Paint gangsta and I will be never able to make such a nice designs as pros. I think I am not the only one. :)
Including scripts and styles
As a next thing let’s include script and styles we need to make calendar work. Because my sample application offers currently no more functionality I included these scripts to my master page.
<link href="<%= Url.Content("~/Content/jquery-ui-1.7.2.custom.css") %>" rel="stylesheet" type="text/css" />
<link href="<%= Url.Content("~/Content/fullcalendar.css") %>" rel="stylesheet" type="text/css" />
<script type="text/javascript"
src="<%= Url.Content("~/Scripts/jquery-1.3.2.min.js") %>">
</script>
<script type="text/javascript"
src="<%= Url.Content("~/Scripts/jquery-ui-1.7.2.custom.min.js") %>">
</script>
<script type="text/javascript"
src="<%= Url.Content("~/Scripts/fullcalendar.min.js") %>">
</script>
Url.Content method creates correct URL-s and it is way better than MS strategy (href like ..\..\Content\Site.css).
Defining FullCalendar
FullCalendar is typical jQuery component. It needs a container with unique id to be defined in HTML. By example:
<div id="calendar"></div>
Now let’s use jQuery to make calendar look like calendar. Now paste the following script to page header between <script> and </script> tags.
$(document).ready(function() {
$('#calendar').fullCalendar({
theme: true,
header: {
left: '',
center: '',
right: ''
},
defaultView: 'agendaDay',
editable: false,
events: "/Calendar/GetEvents/"
});
});
Now you should see calendar like this when you run your application and move to the page where you added FullCalendar.
Reading events from server
If you look at calendar definition of calendar you can see that there is attribute called events (currently it has value "Calendar/GetEvents/"). FullCalendar uses this URL to get data about event sin selected view. Let’s take a look request to this URL in FireBug.
We can see that this request contains three parts: start and end time of current view and one additional parameter that avoids browsers caching the response. Also we can see that start and end times are given as timestamps from Epoch.
Let’s see the controller action that returns events for us.
public JsonResult GetEvents(double start, double end)
{
var userName = Session["UserName"] as string;
if(string.IsNullOrEmpty(userName))
{
return null;
}
var fromDate = ConvertFromUnixTimestamp(start);
var toDate = ConvertFromUnixTimestamp(end);
var rep = Resolver.Resolve<IEventRepository>();
var events = rep.ListEventsForUser(userName,fromDate,toDate);
var eventList = from e in events
select new {
id = e.Id,
title = e.Title,
start = e.FromDate.ToString("s"),
end = e.ToDate.ToString("s"),
allDay = false
};
var rows = eventList.ToArray();
return Json(rows,JsonRequestBehavior.AllowGet);
}
ConvertFromUnixTimestamp method is borrowed from CodeClimber blog posting Convert a Unix timestamp to a .NET DateTime. So, let’s say thanks to Simone Chiaretta.
private static DateTime ConvertFromUnixTimestamp(double timestamp)
{
var origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
return origin.AddSeconds(timestamp);
}
If there were no problems and we inserted some events to database then we should see something like this. Pretty nice?
As a quick update you can follow my previous posting about FullCalendar Linking jQueryUI DatePicker and FullCalendar and link you calendar to jQueryUI DatePicker. The result is here.

That’s it for now. Happy coding! :)
Last year I wrote short posting about how to use LINQ to find matching properties of two objects. In this posting I will show you how to copy values from one object to another and how to boost up performance so you can use this strategy also on in servers under heavy load.
As this is lengthy posting I will give you right now some idea what we are going to do here:
- Stating the problem – when we need to copy property values
- Detecting matching properties of two objects using reflection and LINQ
- Copying matching properties (no optimizations)
- Copying matching properties (lightweight optimizations)
- Copying matching properties (heavily optimized)
- Comparing the results
NB! Test results are calculated arithmetic averages of 100.000 copy operations and unit of measurement is millisecond.
Problem
In some application we have business objects and DTO-s that have matching attributes or properties that we need to copy from one object to another. There can be many reasons why we cannot instantiate new objects and do updates to database based on new object. By example, if you use NHibernate as O/R mapper and you have ASP.NET MVC web application then you have to copy values from business objects to DTO-s when user saves exitsing or inserts new object. That’s because NHibernate monitors object and makes some magic with it. The other reason is even simpler – DTO-s generated for data transfer from view to controller cannot build up business objects automatically (we have manager ID field on form but how to load manager?).
There are also another scenarios when we need to copy values of properties from one object to another, by example web services that use DTO-s to map to and from business objects.
NB! We can write code that maps from type to type but we can also automate this task. By example, you can use AutoMapper like shown in Shiju Varghese’s blog posting View Model pattern and AutoMapper in ASP.NET MVC Applications. You can find also other tools if you make some searching in internet.
In this posting I will not use any tools but I show you how to write effective code that does such mappings. If you are planning systems that go to public then it is recommended to use some good external libraries for that.
Detecting matching properties
As a first thing we have to detect matching properties of two objects. We can use the following method for this. In this example I am copying only value-types and strings. Of course, you can modify this code to fit your needs.
public static IList<PropertyMap> GetMatchingProperties(Type sourceType, Type targetType)
{
var sourceProperties = sourceType.GetProperties();
var targetProperties = targetType.GetProperties();
var properties = (from s in sourceProperties
from t in targetProperties
where s.Name == t.Name &&
s.CanRead &&
t.CanWrite &&
s.PropertyType.IsPublic &&
t.PropertyType.IsPublic
s.PropertyType == t.PropertyType &&
(
(s.PropertyType.IsValueType &&
t.PropertyType.IsValueType
) ||
(s.PropertyType == typeof(string) &&
t.PropertyType == typeof(string)
)
)
select new PropertyMap
{
SourceProperty = s,
TargetProperty = t
}).ToList();
return properties;
}
PropertyMap is the class that contains matching properties.
public class PropertyMap
{
public PropertyInfo SourceProperty { get; set; }
public PropertyInfo TargetProperty { get; set; }
}
In the LINQ query above we make sure that we don’t read write-only properties and we don’t write values to read-only properties. Also we exclude private properties so we don’t mess up something.
Copying matching properties – non-optimized version
Our first version of properties copying code is straight-forward and we don’t use any optimizations. We just want to see so called zero-results to get some base metric for optimizations. So, here is the code that does exactly what we need.
public static void CopyProperties(object source, object target)
{
var sourceType = source.GetType();
var targetType = target.GetType();
var propMap = GetMatchingProperties(sourceType, targetType);
for(var i=0; i<propMap.Count; i++)
{
var prop = propMap[i];
var sourceValue = prop.SourceProperty.GetValue(source,
null);
prop.TargetProperty.SetValue(target, sourceValue, null);
}
}
This method gave 0,0403 milliseconds per copy operation.
Copying matching properties – caching property map
Now let’s take a look at our hey-it-works! version of code we just wrote. There is one repeated step we can avoid – detecting matching properties. We don’t need to run it more than once if we cache the results. After adding this optimization we get the following code.
private static Dictionary<string, PropertyMap[]> _maps =
new Dictionary<string, PropertyMap[]>();
public static void AddPropertyMap<T, TU>()
{
var props = GetMatchingProperties(typeof (T), typeof (TU));
var className = GetClassName(typeof(T), typeof(TU));
_maps.Add(className, props.ToArray());
}
public static void CopyMatchingCachedProperties(object source,
object target)
{
var className = GetClassName(source.GetType(),
target.GetType());
var propMap = _maps[className];
for (var i = 0; i < propMap.Length; i++)
{
var prop = propMap[i];
var sourceValue = prop.SourceProperty.GetValue(source,
null);
prop.TargetProperty.SetValue(target, sourceValue, null);
}
}
public static string GetClassName(Type sourceType,
Type targetType)
{
var className = "Copy_";
className += sourceType.FullName.Replace(".", "_");
className += "_";
className += targetType.FullName.Replace(".", "_");
return className;
}
This method gives us way better performance: 0,0247 milliseconds. It is about 1.6 times better than unoptimized result.
Copying matching properties – generating dynamic code
Now let’s remember all those ghost stories about reflection and performance. Reflection is powerful tool but it comes with its own cost. As our first optimization showed us we 2x gained performance boost when we applied caching of property maps.
Now let’s replace also copying code with something else. We can use dynamically generated and compiled code that copies values from one property to another line by line. Same stuff that we otherwise should write manually. We will create class per types, compile it and cache it. If we need to copy property values from one object to another second time and object types are same then we can run static method from cache without any additional actions.
private static readonly Dictionary<string, Type> Comp = _
new Dictionary<string, Type>();
public static void CopyWithDom<T, TU>(T source, TU target)
{
var className = GetClassName(typeof (T), typeof (TU));
var flags = BindingFlags.Public | BindingFlags.Static |
BindingFlags.InvokeMethod;
var args = new object[] {source, target};
Comp[className].InvokeMember("CopyProps", flags, null,
null, args);
}
public static void GenerateCopyClass<T, TU>()
{
var sourceType = typeof(T);
var targetType = typeof (TU);
var className = GetClassName(typeof (T), typeof (TU));
if (Comp.ContainsKey(className))
return;
var builder = new StringBuilder();
builder.Append("namespace Copy {\r\n");
builder.Append(" public class ");
builder.Append(className);
builder.Append(" {\r\n");
builder.Append(" public static void CopyProps(");
builder.Append(sourceType.FullName);
builder.Append(" source, ");
builder.Append(targetType.FullName);
builder.Append(" target) {\r\n");
var map = GetMatchingProperties(sourceType, targetType);
foreach (var item in map)
{
builder.Append(" target.");
builder.Append(item.TargetProperty.Name);
builder.Append(" = ");
builder.Append("source.");
builder.Append(item.SourceProperty.Name);
builder.Append(";\r\n");
}
builder.Append(" }\r\n }\r\n}");
// Write out method body
Debug.WriteLine(builder.ToString());
var myCodeProvider = new CSharpCodeProvider();
var myCodeCompiler = myCodeProvider.CreateCompiler();
var myCompilerParameters = new CompilerParameters();
myCompilerParameters.ReferencedAssemblies.Add(
typeof (LinqReflectionPerf).Assembly.Location
);
myCompilerParameters.GenerateInMemory = true;
var results = myCodeCompiler.CompileAssemblyFromSource
(myCompilerParameters, builder.ToString());
// Compiler output
foreach (var line in results.Output)
Debug.WriteLine(line);
var copierType = results.CompiledAssembly.GetType(
"Copy." + className);
Comp.Add(className, copierType);
}
And now we have real killer result: 0,0055 milliseconds! This is ~4.5 times faster than caching property map and still using reflection to copy values and ~7.3 times faster than our first method. We wrote more code but we got way better performance than before.
Comparing results
As we have now about 1000 words let’s take a picture that explains more. Here is our results drawn out as bar chart.
We can see that unoptimized code is horror when compared to dynamic code. The result on chart tells us clearly that our last optimization gave us very good results.
Conclusion
Although reflection can be very expensive thing to use it is like electricity – it kills fools and helps smart ones. Through this example we optimized code step by step avoiding repeating things we already done. In the last optimization we were static and dynamic at same time – we created dynamically code that statically assigns values from one object to another and we used reflection to call this method.
As you can see from this example the ability to generate and compile source code on the fly can be very useful thing. We raised the speed of our copy method about 7.5 times using dynamically generated code. By the way, the win in performance is even greater when objects have more than 4-5 properties to copy.
In one of my sample projects I wrote simple calendar solution. Users can select dates from calendar and see what events they have on selected days. I used jQueryUI DatePicker and FullCalendar components. In this posting I will show you how to link them together.
Update: source code of this project is available at CodePlex. Please visit MVC Time Planner page for further information and downloads.
To get better idea what I was doing take a look at the following screenshot. jQueryUI DatePicker is the small calendar on left. FullCalendar is larger one that is opened in day view. When user selects date from DatePicker then FullCalendar loads events for given date.
The trick here is very simple. Here is how I initialize DatePicker.
$(document).ready(function() {
$('#datepicker').datepicker({
inline: true,
onSelect: function(dateText, inst) {
var d = new Date(dateText);
$('#calendar').fullCalendar('gotoDate', d);
}
});
}
The ID of FullCalendar is calendar. If user picks something from DatePicker then DatePicker calls gotoDate method of FullCalendar. FullCalendar selects given date and makes request to server to get events for given date.