Skip to content

Month: March 2014

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

While working on a proposal for a project, 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>
<div class="panel panel-default">
	<div class="panel-body" id="signature-pad">
	<div></div>
	<div>
	<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>
	</div>
</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 offers a method called toDataURL(). It basically is a 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
				   });

$.ajax({
	type: "POST",
	url: "/api/signature",
	contentType: false,
	processData: false,
	data: data,
	contentType: "application/json; charset=utf-8",
	success: function (msg) {
		alert("Done!");
	},
	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.

Conclusion:

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

References:

https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement

http://www.html5canvastutorials.com/advanced/html5-canvas-get-image-data-url/

http://www.asp.net/web-api

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

Introduction

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.

Using Spire.Doc to convert documents

Some time back, I wrote an article about my first thoughts on Spire.Doc for .Net. For those who are not familiar with the product, Spire.Doc for .NET is a professional Word .NET library specially designed for developers to create, read, write, convert and print Word document files from any .NET(C#, VB.NET, ASP.NET) platform with fast and high quality performance. As an independent Word .NET component, Spire.Doc for .NET doesn’t need Microsoft Word to be installed on the machine. However, it can incorporate Microsoft Word document creation capabilities into any developers’ .NET applications.

Ad

Background

This article is intended to demonstrate and review the capabilities provided by the Spire.Doc for converting documents from one format to another. We have long passed the days when many developers would install Microsoft Office on the Server to manipulate the documents. First, it was a pretty bad design and practice. Second, Microsoft never intended to use Microsoft Office as a server component and it wasn’t built for interpreting and manipulating documents on the server side. This gave birth to the idea of having libraries like Spire.Doc. And when we are discussing this, it is worth to mention about Office Open Xml. Office Open XML (also informally known as OOXML or OpenXML) is a zipped, XML-based file format developed by Microsoft for representing spreadsheets, charts, presentations and word processing documents.Microsoft announced in November 2005 that it would co-sponsor standardization of the new version of their XML-based formats through Ecma International, as “Office Open XML”. The introduction of Open Xml has given more standardization to the structure of Office documents and using the Open Xml SDK developers can perform a lot of basic operations pretty straight forward, there are still gaps such as converting the word document in to different format such as PDF, image or HTML to name a few. And this is why libraries such as Spire.Doc comes to rescue us ‘developers’.

Ad

Document Conversion

I will use rest of this article to demonstrate various scenarios which can be covered using Spire.Doc. All the example demonstrated in this article are available under the project at Spire.Doc Demo and you can download to get your hands dirty. The project I have been using for the demonstration is a simple console application but it supports other platforms such as Web or Silverlight as well.

In their own words, Spire.Doc claims following which we will see in rest of the article.

“Spire.Doc for .NET enables converting Word documents to most common and popular formats.”

The first step you need to start using Spire.Doc is to add reference to your project to their libraries Spire.Doc, Spire.License and Spire.Pdf which are packaged in the Spire.Doc component.

You will need a valid Spire.Doc license to use the library otherwise an evaluation warning would be displayed on the document. To set the license, simply provide the path to the license file location and the library takes care of the rest to apply and validate the license information. There are other way as well to load the license such as dynamically retrieving it from the location or to add it as an embedded resource. A detailed documentation is available here.


 FileInfo licenseFile = new FileInfo(@"C:\ManasBhardwaj\license.lic");
 Spire.License.LicenseProvider.SetLicenseFile(licenseFile);

To validate the basic feature, I am using a word document with simple text, an image and a table. Looks something like this and you can find the original document in the Spire.Doc Demo.

The crux of the library is of course the Document class. So we start by creating the Document object and loading the document information from the file. The simplicity of Document object is that with just three lines of code, you can convert quite a complex word document with differ elements such as used in this document to a totally different document, in this case Html format.


//Create word document
Document document = new Document();
document.LoadFromFile(@"This is a Test Document.docx");

To Html


//Convert the file to HTML format
document.SaveToFile("Test.html", FileFormat.Html);

So, by now we should already have the converted document ready for use. Let’s see what it had done behind the scenes. What you would observe is that the new Html document has been created with additional files and folder. These files and folders are nothing but retains the additional information which is present in your word document. In this case, the folder contain the Test Image we added to the document and the style sheet contains the styling for the table. Thus, the conversion not only makes sure that your data is converted but it keeps the additional information such as styling intact as well.

The style sheet would look something like this:

Just a single different parameter can help you to convert the document to other format such as PDF as shown below. What I like about this is that it’s just one framework which can do multiple conversion without any additional styling and configurations for different format. And note that this is all done in memory, so that you don’t have to touch the file system rights etc. I remember in the past when in a project we wanted to the conversion and ended up passing the data from one component to another for conversion to Pdf and still you would not be able to retain the same layout across different formats.

To Pdf


//Convert the file to PDF
document.SaveToFile("Test.Pdf", FileFormat.PDF);

Few lines code and you see the PDF document as shown below. The license warning is just because I am using the trial version. Once you have the valid license file, it will disappear.

To Xml

A quick peak at the FileFormat class shows that it supports as many as 24 different formats. My personal favorite is Xml. It expands the possibility of what you can do with the data in the document. For e.g. you can just consume a word document and create an xml file out of raw document.


//Convert the file to Xml
document.SaveToFile("Test.Xml", FileFormat.Xml);

To Image

And what about converting the document as image file. Spire.Doc supports the conversion of document to the Image class and that can be used to save the image file in any supported ImageFormat by .Net framework.


//Save image file.
Image image = document.SaveToImages(0, ImageType.Metafile);
image.Save("Test.tif", System.Drawing.Imaging.ImageFormat.Tiff);

Conclusion

Spire.Doc is a very capable and easy to use product for converting Word documents to any other format. If you also use the reporting capability, then it’s even better. As with any 3rd party product, there’s usually other ways to do the same thing, and you need to weigh up the benefits against the cost involved in buying the product or in replicating another way.

From a license and pricing overview, it’s not very expensive compared to other products in the markets which are offering the same functionality. Thus, a real value for money in my opinion.

Disclosure of Material Connection: I received one or more of the products or services mentioned above for free in the hope that I would mention it on my blog. Regardless, I only recommend products or services I use personally and believe my readers will enjoy.

A beginner’s guide on Enterprise Resource Planning

Introduction

An Enterprise Resource Planning (ERP) is an integrated system which supports various modules such as sales and marketing, production and inventory control, human resources, finance and accounting, distribution, quality, procurement etc. It is stressed that the various modules are integrated to each other without any duplication of information. The key motivation behind this integration of various sub systems is to provide the real time updated information to the organization so that a consequence of change of decision in one sub system of the organization is immediately reflected to other parts as well so that they can plan their actions effectively.

Evolution of ERP

The evolution of today’s ERP is a result of development of Materials Requirements Planning (MRP) system which became popular in 1970s. Although the logic and planning system behind MRP was already in place, the availability of computer power to support basic planning and control gave it a boost. Another technological shift in 1980s with support of local and wide area networks resulted in Manufacturing Resource Planning (MRP II) systems.

Figure 1: Evolution of ERP

The beginning of 1990s resulted in the introduction of ERP systems. The ERP was much more sophisticated in nature than its predecessors. It was able to collaborate, integrate the information from various parts of the organization and also handle the “what-if” kind of conditions to alert the stake holders if a situation arises. With introduction and popularity of web 2.0 in early 2000, the ERP has evolved from traditional desktop to web enabled or ‘collaborative commerce’ system. With more and more employees and executives mobile devices for professional purposes, major ERP vendors such as SAP and Oracle and pushing hard to provide mobile apps for sub systems of ERP. Web enabled ERP systems are often complex and need periodic maintenance. This can mean that every time the ERP system is taken offline for routine maintenance or other changes, the web site also goes offline.

What ERP entails?

Although integration of various source of databases and information is the core of an ERP system, the installation and configuration of these system is complex and expensive task. Lot of organisations continue to use old database and information systems (often called legacy), which sometime creates challenges while implementing the ERP system in an organisation because of lack of support for information retrieval in the legacy system. The new and latest ERP systems ensure the smooth transfer of data between different parts of the organization. As implementation of ERP changes the way people work, top management has to be proactive in explaining the reasons for, and how the organization as a whole will benefit from the implementation. A proper change management initiative can lower the potential risk of an ERP implementation, through a comprehensive communication and training process.

ERP’s effect on an organisation

ERP changes the way organisation functions. One of the major challenges in many an organisations decision to buy an off-the-shelf ERP system is that of its compatibility with the company’s current business processes and practices. It is very important that the ERP fits the current policies and process or the organisation sees benefit in changing them to adapt based on the offering of ERP. There have been many examples where the wring ERP implementation has caused major loss to organisations. One such example is US Levi Strauss when company’s net income suddenly dropped by 98% to 1 million USD. Alternatively, they could modify the software within the ERP package to fit their processes. Both of these options involve costs and risks.

At a practical level, the implementation of ERP in an organisation brings a lot of challenges in often cumbersome. Most often it has been noted that the major issue in implementation in not proper planning, underestimating the time, effort, resources and cost which would be spent on the installation and configuration of ERP system.

Benefits of ERP

ERP systems have the potential of improving the performance of organizations in various sectors. The introduction of ERP in an organisation also makes sure that all best practices in processes are followed and not one disturbance in one part of the organisation would affect the other parts. ERP helps to create the visibility and transparency of processes within the organisation. Major ERP vendor solutions come with discipline of forcing business process changes. This helps the organisations to adapt the best practices and review their existing processes to make any necessary improvements. It helps to have more sophisticated communication with suppliers, partners and customers to provide more timely and accurate information. Automating business processes such as invoicing and sales and purchase orders within one systems improves forecasting accuracy and reduces inefficiencies. At the same time, using a single base of information for billing and other customer interactions improves service levels and increases customer retention.

Critical Success Factors

From a strategic perspective, the following factors are required in an organisation to have a successful rollout of an ERP system:

  1. Top management commitment and support – strong and committed leadership at the top management level is essential to the success of an ERP implementation
  2. Visioning and planning – articulating a business vision to the organization, identifying clear goals and objectives, and providing a clear link between business goals and systems strategy
  3. Project champion – the individual should possess strong leadership skills as well as business, technical and personal managerial competencies
  4. Implementation strategy and time frame – implement the ERP under a time-phased approach
  5. Project management – the ongoing management of the implementation plan

Popular ERP choices

These are some of the popular ERP systems available in the the market:

Interesting fact is that although Microsoft is one of the top ERP supplier, it uses SAP for their own organisation. Although this has been driven due to various factors such as the capabilities offered by Microsoft Dynamics, the business alliance between SAP and Microsoft.

Conclusion

We live in a completive world which is moving fast with technological advances. Organizations today are not only just focusing on producing goods or offering services but are involved in marketing their products and services, gaining insight on new opportunities etc. To help processing the huge amounts of information and data generated in different parts of organisation, they need a system in place which could present a consolidated and real time information. ERP helps the organizations to run their operations smoother and in a co-ordinated way so that parts of organisations are not left behind. The importance of ERP would increase in future as organisations are more and more investing in big data related technology and infrastructure.

Recommend Reading

Levi Strauss: SAP rollout ‘substantially’ hurt quarter

2013 ERP Market Share Update: SAP Solidifies Market Leadership

What is Big Data?

Why Does Microsoft HQ Use SAP Instead of Microsoft Dynamics ERP?

SAP and Microsoft: Frenemies with Benefits, But What’s in It for Customers?