Creating Word documents in .Net using Docentric Toolki


As any other developer who has been involved in writing business applications, I have used different frameworks (and tricks) to generate word reports. It’s usually a roller coaster ride as most of the components and frameworks try to use various inbuilt features from Word (usually Mail Merge) to accomplish that.

This article is focused on generating or creating the mail merge word documents using Docentric Toolkit.

In their own words,

Docentric Toolkit is a Word document generation, mail-merge and reporting toolkit for .NET designed to drastically reduce the time and effort required to create and maintain documents and reports in Word.

And based on their website, the high level design of the product is as shown below:

Let’s try it first hands

Generate Document using .Net Object

As I said before, I have used various components before to implement the word report generation. To be honest it has never been a satisfactory experience.

For the purpose of demonstration in this article, I would be using the xml data source as the input for report generation using the Docentric Took Kit. And as I wanted a real world example of data and not something which I would define, I decided to use the Book Catalog Xml data source based on this MSDN link.

Let’s do some ground work before we dig deep into the Docentric demonstration. Based on the xml data structure, I wanted to create a .NET class that would hold and represent the XML data. Big deal, you can always use the XSD.exe to generate XML schema or common language runtime classes from XDR, XML, and XSD files, or from classes in a runtime assembly. But what I was not aware of was a new feature in Visual Studio 2012 (and of course Visual Studio 2013) and when using .Net 4.5 project. Now, you can use simple use Edit -> Paste Special -> Paste XML as Classes. Quite handy as a feature and lets you as a developer focus on more important thing which you want to accomplish and does the most obvious things itself.

So now we have a class library named Catalog.dll which wraps up the data structure for our input Book Catalog xml.

The installation of Docentric Toolkit not only gives you access to the assemblies which you can use in your code to generate word reports but also provides an Add-In for Microsoft Word which can be used to generate the template documents for your reports. In my opinion, the Add-In is one of the unique features of Docentric Toolkit which differentiates it from other similar mail merge solutions available in market.

Data Source Explorer

The starting point while designing a template for your report is the Data Source Explorer. The various data sources supported by the toolkit are:

  • .Net Objects
  • Xml Data Source
  • DTS Object

DTS is their own type system and was introduced in order to make the template design user experience even better for non-technical users. However, the first two types are quite generic as well and can be used by someone who is not writing real code in his day-to-day work. For this example, I will be using .NET Object kind of a data source which is probably used the most.

The next step is to select a Schema for the report you are going to generate and I am going to use the class catalogBook from the assembly Catalog.dll which we created earlier using the xml data source.

Schema Info and Member Tree

Once the Schema has been selected, Docentric Toolkit automatically provides you with a graphical representation of all available members defined by the schema.

Basic Design and Elements Explorer

For the first demonstration, I want to generate a report with the information of a singe book record and that’s the reason I have specified in the template itself what kind of behavior I want from the template. You can change this by selecting the value of .Net Type Usage to be either Single Object or Collection.

Next step is to graphically design your word template and add the field tagging elements for each property that we want to write on the generated document. The Field element is the most basic tagging element used as a placeholder for values on a report template. It is a bind able element which means that when it is placed on a template, it can also be bound to data. The Field element will simply be replaced with the value it is bound to when the report engine will process it.

Every field selected and specified is represented in the Elements Explorer (see image below). The Field elements also provide you with additional features such as formatting a string to a number, date time etc.
The Formatted objects are shown with a different representation with an adjacent circle (see next to price),


Get more with less code

I am a big supporter of writing less lines of code and achieving more with fewer lines of code. The motive behind this argument is simple. The bigger your code base becomes, the bigger gets your technical debt and effort to maintain it throughout its life cycle.

Let’s start by creating a simple Console Application to demonstrate the report generation. All you need to begin is add reference to the following three Docentric Libraries in your project.

The following code is the most basic repeatable piece of code which you can use to achieve most of the functionality when generating reports using Docentric Toolkit.

private static void GenerateReport(string templateDocument, object input)
            string reportDocumentFileName = String.Format("GenerateReport_{0}.docx", Guid.NewGuid());

            using (Stream reportDocumentStream = File.Create(reportDocumentFileName))
                using (Stream reportTemplateStream = File.OpenRead(templateDocument))
                    DocumentGenerator dg = new DocumentGenerator(input);

                    DocumentGenerationResult result = dg.GenerateDocument(reportTemplateStream, reportDocumentStream);

                    if (result.HasErrors)
                        foreach (Docentric.Word.Error error in result.Errors) Console.Out.WriteLine(error.Message);


XmlSerializer reader = new XmlSerializer(typeof(catalog));
System.IO.StreamReader file = new System.IO.StreamReader(dataXml);
catalog catalogOverview = new catalog();
catalogOverview = (catalog)reader.Deserialize(file);

//Generate simple report fields

With just handful lines of code and most of the configuration in the Word itself we can easily generate a report connecting to a .Net Schema and data coming in the form of an Xml file.

Generate Document directly using Xml Schema

We quickly saw the Data Source possibility in the Docentric Toolkit and the support directly for Xml objects. What does it exactly mean?

In simple terms, further less code. You can simply specify an XSD or even an a sample XML file to import the schema for a data source to Docentric Toolkit Add-In. It will generate a schema based on the data available as it would have done with the .Net Object.

Once you selected the xml file which we used to generate the .Net class, we see a very similar schema of objects as it was represented by .Net Object. This means, you can actually get rid of the additional step of generating the .Net library for your xml data source.

However, in this example we will generate a table with a collection of records from the xml file. The collection will use the List feature which basically wraps around the field elements to create a repeatable control in the template. The List element is much different to the Field element. It doesn’t act as a placeholder, but rather as a “repeater”. The List element’s behavior is very simple. All it does is “repeating” its wrapped content for each data item in the collection it is bound to, where the wrapped content acts as a content template for each collection item. A template content is not limited to be a table row, it can be anything. Those familiar with the “Repeater” control in Asp.Net or WPF/Silverlight’s “Items Control” will notice that similar concepts have also been employed for the List element.


The data context gets changed to the current collection item for the List element’s child elements. For example, if the List element is bound to the collection, then its nested Field elements Data Context will be of type Customer. This is reasonable, since the Field element is part of the List element’s template content, which gets repeated for each item in the collection. Most data bindable elements nested inside a List element will mostly have their Binding Source set to the Current Data Context value.

With even fewer lines of code which we wrote earlier and just changing a few arguments to the same function we can generate the results as shown below. And not only generation, we can control certain other behaviors such as sorting etc. within the template itself. If you notice in the figure above, the table is sorted based on the Title of a book and it is completely configured in the template without any special treatment in the code.

//Generate report with table structured data
XElement data = XElement.Load(dataXml);
GenerateReport(templateDocumentTable, data);


One of the most common requirement in any serious business application is a generation of reports based on the data used.

Docentric Toolkit is no doubt a nice mail merge framework to stream line the document and report generation process in any application. As I indicated earlier in the article as well, the best feature in my opinion is the simplicity of the toolkit and the burden it removes from the developer for the repetitive work he has to do. With the template feature, the business users themselves can define the document, fields, lists, groups etc. and of course we developer can enhance the work done by them to make sure the correct data is enriched into the reports.

Having said that, I would personally like to see more from this toolkit to even go to an extent where you don’t need any code written for report generation. And your template can just accept the data source from various formats like Xml, OData or JSON feed.

Download Demo Project

Retrieve disk space of remote computers using PowerShell

The more I use PowerShell, the more I like it. I expect if you are reading this blog right now then you are already aware of What PowerShell is.

For those who are new to this topic, Windows PowerShell is Microsoft’s task automation and configuration management framework, consisting of a command-line shell and associated scripting language built on .NET Framework. Although many consider it as an extension of good old command prompt (CMD), its much more extendable scripting language. It’s simply cool because as a developer you can actually write all those small toys you were writing as console applications or executable, isn’t required any more. One can have interaction with all your .Net libraries using PowerShell itself. In fact, you can use COM too using p/Invoke.

Anyway without dragging the topic in PowerShell details, this tip/note-to-self is about how to get disk (free) space of a remote computer using PowerShell.

I wanted to know the total disk space and the available free space of number of servers. You can always use the RDP to log-in and check the details but I wanted to avoid that step and have the insights remotely.

If you are looking for something similar, the following one line PowerShell is a good place to start:

Get-WmiObject Win32_LogicalDisk -ComputerName $ServerName -Filter "DeviceID='C:'" | Select-Object Size,FreeSpace

WMI remains the primary automation technology for system administration, so system administrators will likely rely heavily on Get-WmiObject to help them with their routine management tasks. And there’s an added bonus, too: unlike most cmdlets, Get-WmiObject can be run against remote computers. That means you really can use Windows PowerShell as a management tool.

So, now I was able to get the total Size and FreeSpace of the drive C of a particular server by passing the ComputerName. Next step was to retrieve the same details for an array of computers or servers.

In the below code snippet, I read a file named Computers.txt which has a list of server names listed. Thus, in just few lines of code/script you can retrieve the detailed of the drive of remote computers. Isn’t it quite handy when you are doing lot of system management on day to day basis?

You can format the details as per your requirements. In the following example, the output is generated as the comma separated records with Server Name, Total Disk space and Free Disk space available (in Giga Bytes).

$ServerName = Get-Content "C:\Users\Manas\Desktop\Computers.txt"
$ConvertToGB = (1024 * 1024 * 1024)

foreach ($Server in $ServerName) {

    $disk = Get-WmiObject Win32_LogicalDisk -ComputerName $Server -Filter "DeviceID='C:'" | Select-Object Size,FreeSpace
    $Server + "," + ($disk.Size / $ConvertToGB) + "," + ($disk.FreeSpace / $ConvertToGB)

Further Reference

A minimalist example of using Html5 Canvas to save signature as image using Web API

While working on a proposal for a prospective client, I wanted to have a look at the possibilities of capturing the signature of client in an application (mobile, web). From the first thoughts, I was kind of doubtful about the implementation and was not really sure how easy of difficult would this be to provide as a feature which is easy to use.

I started to brainstorm with my friend Google and after searching with the few possible terms, we were in good direction. As my first thought (so 1990s), one possible option was to use some kind of 3rd part component, ActiveX etc. installed on the client which would help capturing the input. This was something I wanted to avoid at any cost. With so many different possible devices, operating systems and browser, this would not make sense at all and is call for trouble.

Another hint was to use the capability offered by Html5 Canvas. I was like, of course how could I miss this one. ;)

Check out demo here.

Canvas to capture user input

For starters, canvas element is part of HTML5 and allows for dynamic, scriptable rendering of 2D shapes and bitmap images. It is a low level, procedural model that updates a bitmap and does not have a built-in scene graph.

So, I was going in right direction. Use canvas and somehow save this signature on the server side for further use. Well, I am not going into details but if you are storing signature of user; you might need to think if it is really necessary and other privacy issues and measures associated with it.

Capturing user input is one of the most common scenario you would see when using the canvas. Canvas is especially most powerful element in Html5 for game developers these days. Anyway, as I did not want to reinvent the wheel for capturing the signature input (well, actually nothing but a user driven drawing), I decided to use Signature Pad written by Szymon Nowak. In his own words, Signature Pad is a JavaScript library for drawing smooth signatures. Its HTML5 canvas based and uses variable width Bézier curve interpolation based on Smoother Signatures. It works in all modern desktop and mobile browsers and doesn’t depend on any external libraries.

A very basic html page I created looked something like this containing a couple of buttons plus a canvas which would be used for capturing the user signature.

<div class="page-header">
<h1>Signature App demonstration using SignaturePad and Web API</h1>
<div class="panel panel-default">
<div class="panel-body" id="signature-pad">
<div class="alert alert-info">Sign above</div>
 <button class="btn btn-info" data-action="clear">Clear</button>
 <button class="btn btn-success" data-action="save">Save</button></div>

toDataUrl to get canvas image as base64 encoded Url

The internals, initialization etc. are minor and are out of the box from Signature Pad and you can see in the attached sample project with this post. The next step was to save the captured signature on the canvas to the server. It turned out the canvas was awesome beyond my imagination. It offer a method called toDataURL(). It basically URL containing a representation of the image in the format specified by type (defaults to PNG). The returned image is 96dpi. To get the image data URL of the canvas, we can use the toDataURL() method of the canvas object which converts the canvas drawing into a 64 bit encoded PNG URL. If you’d like for the image data URL to be in the jpeg format, you can pass image/jpeg as the first argument in the toDataURL() method. If you’d like to control the image quality for a jpeg image, you can pass in a number from 0 to 1 as the second argument to the toDataURL() method.

Awesome. Isn’t it?

Web API to save image on server

I decided to get my hands dirty on Web API to implement the server side saving as I did not try it earlier. Again for starters, a server-side web API is a programmatic interface to a defined request-response message system, typically expressed in JSON or XML, which is exposed via the web—most commonly by means of an HTTP-based web server.

I started by creating a new ASP.Net project in Visual Studio 2013 and selected Empty Project template with Web API selected.

One the project has been created, the next step is add a new controller and rename it as SignatureController. The controller would look something like this:

public class SignatureController : ApiController
	public IHttpActionResult Post([FromBody]Signature data)
		byte[] photo = Convert.FromBase64String(data.Value);

		var dir = new DirectoryInfo(HostingEnvironment.ApplicationPhysicalPath);

		using (System.IO.FileStream fs = System.IO.File.Create(Path.Combine(dir.FullName, string.Format("Img_{0}.png", Guid.NewGuid()))))
			 fs.Write(photo, 0, photo.Length);

		return Ok();

The controller takes the Signature model as the input. However, this example only has the dataUrl or value of the signature defined but you can possibly thing to extend with additional members for e.g. name of the user.

Now, let’s go back to the html page which I created to start with the SignaturePad. And extend with a jQuery call to access the web API.

            dataURL = signaturePad.toDataURL().replace('data:image/png;base64,', '');
            var data = JSON.stringify(
                                   value: dataURL

                type: "POST",
                url: "/api/signature",
                contentType: false,
                processData: false,
                data: data,
                contentType: "application/json; charset=utf-8",
                success: function (msg) {
                error: onWebServiceFailed

And that’s it. This is a complete minimal solution to have solution for capturing the user input till saving it as a file on server.


The latest development in web technologies have opened up the opportunities to implement the functionalities in an easier manner for developers. What’s important is that we keep ourselves up-to-date with them and trust me this is a challenging part (especially for me J).

And why I called this as minimalist is because it really is. With a least amount of code, we could have a nice functionality in place. And it’s not only limited to signature capture, think about a possibility to have a same implementation on using a big screen white board and sending across the drawing to whole team with just one click of button.

Another reason for minimalist is that it took me less than 30 minutes to build this example from end to end. On the other hand, more than that in writing this blog.

Download sample project


Day Light Saving bug in Amazon Order Tracking

According to Wikipedia, Daylight saving time (DST) or summer time is the practice of advancing clocks during the lighter months so that evenings have more daylight and mornings have less. Typically clocks are adjusted forward one hour near the start of spring and are adjusted backward in the autumn.

And how many times we have seen that how this concept has created troubles for not only small software but also for giants. iOS for iPhone and iPad has already been culprit for having some nasty bugs related to this. And it was rumored that they have done the same mistake again in their latest iOS 7 as well.

Anyway, this post is not about Apple so let me come straight to what I found. I ordered a few books from Amazon UK around 10 days back and was expecting delivery anytime. When I checked the order status yesterday (29th March 2014), the status on the web site showed that the package is in transit (Amsterdam) and has been out for delivery on 29 March 2014 9:49:17.

That’s another story that I am still waiting for my package to me received. This triggered me to check the status again today (on 30th March 2014) and this is what I saw.

Basically, the same message but the time stamp was shifted 1 hour back. That is simply a programming error where they converted the time of out for delivery because of DST. But that’s not how it should be, at least in my opinion.

Not something which Amazon needs to take real action on but they might want to look at it.

And btw, @Amazon do I get a free gift card for finding this bug in your system? J

A beginner’s guide to Product Life-Cycle


The product life cycle is an important concept in marketing. It describes the stages a product goes through from when it was first thought of until it finally is removed from the market. Not all products reach this final stage. Some continue to grow and others rise and fall. An organization’s positioning and differentiation strategy must change as the product, market and competitor change over the product life cycle (PLC).

Product Life Cycle

The main stages of a product life cycle can be illustrated using a bell curve as shown in the figure below:

Figure 1: Product Life Cycle (Source: Kotler & Keller, 2011)

The first phase of the PLC is introduction. This is the period when the product is launched in the market. There is low level of sales, capital utilization and usually negative cash flow because of the high investment in product introduction. The distributors may be reluctant to accept an unproven product and a heavy promotion is required to create awareness among the consumers.

If the product is popular with in the consumers then the sales starts to increase substantially in growth phase. Along with the high sales, the companies see high level of capital utilization, growing acceptance among consumers and eventually with a positive cash flow. This phase can also see the challenge coming from introduction of competitors with the similar product.

Next phase known as maturity is observed with slowdown in sales growth because the product has achieved acceptance by most potential buyers. Another reason for slowdown is often seen as intense competition for the market share. Profits and price usually fall during this phase of the PLC. Weaker competitors also start to leave the market during this stage.

The last stage of PLC is known as decline where the sales and profile starts to decline. Although more and more competitors leave the market during this stage, the cash flow and capital utilisation decline as well. It is often a signal to start looking for an alternative product or to re-incarnate the existing product to the next level.

Common Product Life-Cycle Patterns

The PLC can be used to analyse a product category for e.g. liquor, software and garments etc. It is important to note that not all products follow the bell curve as illustrated in previous chapter.

Figure 2: Common Product Life-Cycle Patterns (Source: Kotler & Keller, 2011)

A product can follow a pattern known as growth-slump-maturity pattern. This kind of pattern usually encounters a rapid growth in the beginning and after later sales decline with a stabilization at a certain level. One of the examples of such product group is kitchen appliances where the late adopters purchase a new product while the early adopters end up replacing their old appliances.

The cycle-recycle pattern usually starts with a period of growth which is followed by decline. Another phase of growth is triggered by promotion of the product which see a lesser growth as compared to the primary cycle. A typical example of this pattern can be seen in pharmaceutical industry where sales start declining the company gives the drug another push, which produces a second cycle.

Another common pattern is called scalloped pattern. Sales observe a succession of growth periods based on the discovery of new product characteristics, uses, or users. Nylon sales, for example, display a scalloped pattern because, over time, new and a new uses have been discovered -parachutes, hosiery, shirts, carpeting, etc.

Style, Fashion, and Fad Life Cycles

It is important to discuss another type of life cycles. The first one is called style. It is basic and distinctive mode of expression. Once invented, styles can last for generations, going in and out of vogue. This is usually seen in products such as homes, clothing and art etc.

Figure 3: Style, Fashion, and Fad Life Cycles (Source: Kotler & Keller, 2011)

Fashion is currently accepted or popular style in a given field. Fashions pretty much follow the typical bell-shaped product lifecycle curve. The length of fashion cycles is difficult to predict as the consumers soon start to look for the missing attributes.

Fads are fashions that come quickly into public view, are adopted with great zeal, peak early, and decline very fast. Their acceptance cycle is short, and they tend to attract only a limited following who are searching for excitement or want to distinguish themselves from others.