Skip to content

Month: April 2014

Snakes and Ladders – Another attempt using SVG (Scalable Vector Graphics)

Introduction

This article is a follow-up of my earlier post where I tried to create the Snake and Ladders game using HTML5 canvas. This time, I am going to give a try using SVG.

Again, for those of you who have never heard of this game, here is a Wiki article about it.

Demo

You can find a working demo of this implementation here:

Snake & Ladder Demo

Not a long ago, this image was making the rounds on internet and was getting as a popular joke among the developer community. It symbolized poor, homeless guy who was ready to ‘code html for food’ in return of help.


Fast forward 2007, the W3C accepted the HTML5 specification as the new for work for the HTML. Not only HTML5 gave a new overhaul to the web application landscape, it came almost at the right time when JavaScript was also getting more powerful and popular. Antwood’s law which states that any application that can be written in JavaScript will eventually be written in JavaScript was also coming to reality.

Although HTML5 specifications are not yet final and various browsers have implemented their own versions of interpretations, we are seeing more standardization in web development. The web developers are more equipped with new tags and elements introduced. This article would particularly address one of the HTML5 standards known as Scalable Vector Graphics (SVG).

So, what is SVG?


The history of SVG goes well beyond HTML5. The first public draft specification of SVG was introduced by W3C in the year 1999. Its standards were based and derived from the experience of Precision Graphics Markup Language and Vector Markup Language.

Citing from the official spec at W3.org, SVG is described as: A language for describing two-dimensional graphics in XML. SVG allows for three types of graphic objects: vector graphic shapes (e.g., paths consisting of straight lines and curves), images and text.

Vector graphics are based on vectors (also called paths or strokes), which lead through locations called control points or nodes. On the other hand, raster graphics image, or bitmap, is a dot matrix data structure representing a generally rectangular grid of pixels, or points of color, viewable via a monitor, paper, or other display medium.

The most basic SVG file contains the following format:

  • Size of the viewport (Think of this as the image resolution)
  • Grouping instructions via the element — How should elements be grouped?
  • Drawing instructions using the shapes elements
  • Style specifications describing how each element should be drawn.

What are the advantages of using SVG?

  • SVG images can be embedded into the HTML document and rendered by the client browser, thus reducing the request traffic load.
  • SVG object can be animated when it uses the animation element or through JavaScript Library like jQuery.
  • The SVG images give you constant performance. It only deteriorates when the image resolution considerably increases.
  • SVG images can be printed with high quality at any resolution.
  • You don’t need an image editor to build SVG images. Because SVG is an XML based image format, you can practically use any text editor (my favorite is Notepad++).
  • You have full control over each element using the SVG DOM API in JavaScript.
  • SVG is an XML file format, which means that depending on each Web browser implementation the accessibility of SVG documents can be much better than that of canvas elements.

And how is it different from Canvas?

Developers often confuse the usage of SVG with another HTML5 feature called Canvas. While both of the can be sometime used to achieve the same functionality (see my earlier article on implementing Snake & Ladder game using canvas), one should consider a few points before deciding the tool for job.

With canvas, you don’t have any DOM nodes or elements to draw from. It’s all free format drawing on pixels. While in SVG you can implement animation and motion natively, that’s the not the case in canvas where you are on your own to implement animation using timer etc.

If accessibility is a concern, HTML might be better suited than SVG, being that it has more tools available for enabling and testing accessibility.

It should be noted that SVG itself might not be the best way to developer complex drawing in games and the best way to do that is take a mixed approach path of using SVG along with Canvas.

Time for some hands-on: Let’s build Snake & Ladder’s game

For starter’s Snake and Ladders in typical setting is dual player game and the object of the game is to navigate one’s game piece, according to die rolls, from the start (bottom square) to the finish (top square), helped or hindered by ladders and snakes respectively. Not to mention that having played this game so much in my childhood is one of the first thing I wanted to try out when I heard of HTML5 capabilities. I had attempted to have an implementation of this game using canvas earlier.

I started with an empty SVG tag in my html document.


<svg id="templateContainer">
</svg>

The SVG element indicates with in the HTML document that this section or element contains a SVG image and should be treated as. The typical attributes in SVG element are width and height which are used to specify its dimensions. I intentionally left them empty in the document html. However, they are being set at the document ready event using the jQuery.


$(document).ready(function() {

var dimension = $(window).height() - 100;

$("#templateContainer").height(dimension);
$("#templateContainer").width(dimension);

});

The above code should be very familiar to most of you and it does nothing more that setting the height and width attribute of the SVG element during the page ready event. This also indicates that you can simply treat it as any other element you would treat in HTML.

Next, I wanted to build a grid with 100 rectangles using the SVG. Of course, there are other ways using standard tables, div etc. to do this as well. Plus, I did not want to have static definition of 100 rectangle elements in my document. So, I defined a template SVG rectangle element as shown below:


<div class="row">
	<div class="col-md-8">
		<svg id="templateContainer">
			<rect x="0" y="0" width="0" height="0" class="orig">
			</rect>
		</svg>
	</div>
</div>

Later, I used a jQuery clone function to create 100 clones of the template rectangle and is assigned a different random class to create a fancy colorful grid.


function drawBoard() {		
		 
	var squareSize = _winHeight / 10;
	
	var columnNr = 1; var leftToRight = true;
	var x = 0; var y = 0; var position = 100;
    for (var row = 1; row <= numerOfRows; row++) 
    {	
		if (leftToRight) 
        {
            x = 0;
        }
        else 
        {
            x = $("#templateContainer").width() - squareSize;
        }
		
		for (var column = 1; column <= numerOfcolumns; column++) 
        {
			rows[position - 1] = x.toString() + "," + y.toString();
			
			var clonedRect = $(".orig").clone();	
			
			clonedRect.attr("x", x);
			clonedRect.attr("y", y);
			clonedRect.attr("width", squareSize);
			clonedRect.attr("height", squareSize);
			
			var rnd = Math.floor(Math.random() * 6) + 1;
			var className = "Rect Rect" + rnd.toString();
			
			clonedRect.attr("class", className);	
			clonedRect.appendTo( "#templateContainer" );

			var clonedText = $(".origText").clone();	

			clonedText.text(position.toString());
			clonedText.attr("x", x + 30);
			clonedText.attr("y", y + 30);
			clonedText.attr("class", "text");	
			clonedText.appendTo( "#templateContainer" );
			
			if (leftToRight) 
			{
				x += squareSize;
			}
			else
			{
				x -= squareSize;
			}	
					
			position--;
		}		
		
		y += squareSize;
		
		leftToRight = !leftToRight;
	}
	
	$( ".orig" ).remove();
	$( ".origText" ).remove();
	
	drawLadders();	
}

The width and height attributes of the element define the height and the width of the rectangle. You can use the style attribute is used to define CSS properties for the rectangle. Alternatively, you can use a CSS class to define the styling as shown in the above example.

The other predefined shapes you can have in SVG are:

  • Circle
  • Ellipse
  • Line
  • Polyline
  • Polygon
  • Path

In an ideal game, the snake and ladders are drawn. I decided to use the arrows pointing up and down to have the alternate for snakes and ladders. The red arrows represent snakes and white ones represent ladders.


<line x1="0" y1="0" x2="200" y2="200" class="origLine"/>

The element is used to create a line. The x1 attribute defines the start of the line on the x-axis. The y1 attribute defines the start of the line on the y-axis. The x2 attribute defines the end of the line on the x-axis. The y2 attribute defines the end of the line on the y-axis.

The end of the line I decorated with the circles to show the direction. This is drawn using the circle element.


<circle cx="0" cy="0" r="8" stroke="white" stroke-width="3" fill="red" class="origCircle"/>

The circle element is an SVG basic shape, used to create circles based on a center point and a radius. The cx and cy attributes define the x and y coordinates of the center of the circle. If cx and cy are omitted, the circle’s center is set to (0,0). The r attribute defines the radius of the circle

Download

The example project used in this demonstration is available here:

Download Example

Conclusion

SVG is powerful and necessary tool for any web developer these days considering the vastness of technological changes we have seen in the last few years. Not only it makes it easier to develop but at the same time opens the possibility for the areas which were not possible to implement on client side with this ease.

The Snake & Ladder game I have used for the demonstration in this article is by no means a symbol of best practice and should only be seen as a way to learn various available possibilities using SVG. In the meanwhile if you want to extend and take this idea further, please feel free and I would be glad to see that.

Thanks for spending your time to read this article and if you liked this please share with others.

By the way, did you know that there is this awesome website called CanIUse.com where you can check the compatibility of various desktop and mobile browsers for the various HTML5, CSS3, SVG features?

References and further reading

http://www.w3schools.com/SVG/svg_intro.asp

http://en.wikipedia.org/wiki/Jeff_Atwood

http://en.wikipedia.org/wiki/Scalable_Vector_Graphics

http://caniuse.com/svg

https://developer.mozilla.org/en/docs/Web/SVG

http://www.codeproject.com/Articles/262179/SVG-World-Map

http://www.w3.org/Graphics/SVG/IG/resources/svgprimer.html

http://dev.opera.com/articles/svg-or-canvas-choose

Upload Files to Library in SharePoint 2013 using PowerShell

One of the most common questions I see on various forums is on “How to upload files to SharePoint Library?” and to a larger extent of these questions are related to a scheduled upload of files.

Thus, the problem statement becomes “How to schedule upload of files to a SharePoint Library?”.

You can always do it by writing a SharePoint Timer Job using .Net code and deploying the timer job to your SharePoint farm. Wait a second, did we just say deploy to farm? So, does it makes sense to have a new timer job running at farm level for a such a common, simple problem?

Let’s take it to another extent and just assume that we want to have our solution cloud ready so that if we want to move to Office 365 in future, that’s ready for it as well.

Hold on, there is no timer job in Office 365. So what do we do now? Jamie McAllister discussed this scenario in his post Alternatives to SharePoint Timer Jobs and he proposed a nice design to use Windows Scheduler as an alternative of Timer Jobs. Kind of makes sense that you don’t want to overload of SharePoint environment with all these small tasks/timer jobs and have them maintained outside your SharePoint environment. In fact, it is not responsibility of SharePoint Farm to upload files but of a client (application) to do that at a time (interval) when it wants.

Following the same principle, here is a PowerShell script which you can use to upload files to SharePoint.


[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
if((Get-PSSnapin | Where {$_.Name -eq "Microsoft.SharePoint.PowerShell"}) -eq $null) {
     Add-PSSnapin Microsoft.SharePoint.PowerShell;
 }

#Site Collection where you want to upload files
$siteCollUrl = "http://webapplication/sites/Upload"
#Document Library where you want to upload files
$libraryName = "Shared Documents"
#Physical/Network location of files
$reportFilesLocation  = "C:\Users\manas\Desktop\Files"

$spSourceWeb = Get-SPWeb $siteCollUrl;
$spSourceList = $spSourceWeb.Lists[$libraryName];

if($spSourceList -eq $null)
{
	Write-Host "The Library $libraryName could not be found."
	return;
}

$files = ([System.IO.DirectoryInfo] (Get-Item $reportFilesLocation)).GetFiles()
foreach($file in $files)
{
	#Open file
	$fileStream = ([System.IO.FileInfo] (Get-Item $file.FullName)).OpenRead()

	#Add file
	$folder =  $spSourceWeb.getfolder($libraryName)

	Write-Host "Copying file $file to $libraryName..."
	$spFile = $folder.Files.Add($folder.Url + "/" + $file.Name, [System.IO.Stream]$fileStream, $true)

	#Close file stream
	$fileStream.Close();

}
$spSourceWeb.dispose();
Write-Host "Files have been uploaded to $libraryName."

Download Script

And if you want to schedule, you can use Windows Scheduler to schedule your script.

Here are the steps to schedule a PowerShell script using Windows Task Scheduler.

  1. Save your PowerShell script to a location for e.g. C:\Manas\Scripts
  2. Go to Windows Task Scheduler and schedule your script using the command PowerShell.exe <PATH TO YOUR SCRIPT>.

There is this good post on using Scheduled Tasks to Run PowerShell Commands on Windows.

Creating Word documents in .Net using Docentric Toolkit

Introduction

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),

Review1

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
GenerateReport(templateDocumentSimple, catalogOverview.book[0]);

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.

Revie2

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);

Conclusion

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).

Further Reference

http://technet.microsoft.com/en-us/library/ee176860.aspx