Friday, January 31, 2014

Knockout Durandal DatePicker

While building your SPA application in Durandal or Knockout you may need your users to enter dates, such of Date Of Birth. Would it be nice to provide a DatePicker control for the user to pick the date. In this blog I will show you how to include a DatePicker in your durandal app and do knockout binding.

First of all identify what DatePicker JQuery control you want to use in your SPA application. I typically use Zurb Foundation in my applications, hence I decided to use foundation’s DatePicker, which is based on Bootstrap’s DatePicker. Instead of this you can use Bootstrap’s DatePicker, JQueryUI’s DatePicker or any other DatePicker.

Once you finalized the DatePicker, include that javascript file into the code by any mechanism, such as script tags, bundleconfig in MVC, require AMD etc. For simplicity I am using script tags

    <script src="/Scripts/foundation/foundation-datepicker.js"></script>

Also include the corresponding styles
    <link href="/content/foundation-datepicker.css" rel=="stylesheet"></script>

In addition to the datepicker javascript, I also use moment javascript for formatting dates. So let’s include that script file as well

<script src="/scripts/moment-with-langs.js"></script>

After doing this minimal work, let’s move to Knockout where we have to tell knockout to attach our DatePicker controller. This is done by defining our own binding attribute. Similar to the built-in binding let’s define a custom binding called datepicker. In this custom binding we will do the following steps
  • Attach the DatePicker control to the textbox element on the init method
  • Define format of the date (if needed)
  • Register the change event and in that change event update the model value
  • Whenever the model is updated, change the value of the DatePicker control
  • Format the date using moment (if needed)

Here is the code that does the all the above steps

    ko.bindingHandlers.datepicker = {
        init: function (element, valueAccessor) {
            $(element).fdatepicker({ format: 'mm/dd/yyyy' });
            var value = valueAccessor();

            ko.utils.registerEventHandler(element, "change", function () {
                value(element.value);
            });
        },

        update: function (element, valueAccessor, allBindingsAccessor, viewModel)
        {
            var value = valueAccessor();
            var mmt = moment(value());
            if (mmt.isValid() === false) {
                value("");
                element.value = "";
            }
            else {
                element.value = mmt.format('L');
            }
        }
    };

As I am doing this in my Durandal SPA, I can use composition to define the knockout binding handler as shown below

    composition.addBindingHandler('datepicker', {
        //init & update code as above
    });

The above configuration is a onetime process. After setting up the datepicker binding attribute we can use it anyplace in our application by using the datepicker databinding attribute as shown below

         <input type="text" placeholder="" data-bind="datepicker: DateOfBirth" />

Here is the output of our knockout DatePicker control


Monday, January 27, 2014

MVC DatePicker the easiest Way

Imagine how your user experience will improve if you provide a date picker to pick a date in your applications. As you know there are several JQuery plugins available which provide this functionality. But as a MVC developer you have to integrate Javascript with your code and write both dotnet code and javascript code. We all know that how tedious that it can be.

Again imagine that how it would be to do this in just few simple lines in dotnet code and not worry about JQuery. Now check the below code:

    @(Html.Juime().DatePicker("datePicker")
                    .DataMap(item =>
                        {
                            item.Value = DateTime.Today;
                        }
                    )
    )

Here is the output of the above code:

As you see with few lines of code we were able create a DatePicker control in our application. Juime made this possible J

Juime is a free open source controls built on top of famous JQuery UI. With Juime you can bring JQuery UI controls into your project without any JavaScript code. Juime also provides several customizable configuration options for this date picker or any other controls. 

Check our GitHub site for more details.


Wednesday, January 22, 2014

Export Dynamic Word document in Web API

There may be scenarios where you need to dynamically generate word document (which is not saved on the web server) and download it using Web API. In this blog I will show you how to generate a word document and download that word document using Web API.

First we need create an in memory word document. This word document will not be saved on the web server. As we are creating word document on a web server, let use OpenXml. Here is the code which creates a “Hello World” in memory document

using (MemoryStream ms = new MemoryStream())
{
    using (WordprocessingDocument package = WordprocessingDocument.Create(ms, WordprocessingDocumentType.Document))
    { 
        MainDocumentPart mainPart = package.AddMainDocumentPart();
        mainPart.Document = new Document();
        var body = new Body();
        Paragraph paragraph = new Paragraph();
        Run run = new Run(new Text("Hello World!"));
        paragraph.Append(run);
        body.Append(paragraph);
        mainPart.Document.Append(body);
        package.Close();
    }
}

Once the document is created we can push the document through the response stream using the below code:

HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new ByteArrayContent(ms.ToArray());
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.ms-word");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = "HelloWorld.docx";
return result;

Here is the total WebAPI code:
public HttpResponseMessage Get()
{
    using (MemoryStream ms = new MemoryStream())
    {

        using (WordprocessingDocument package = WordprocessingDocument.Create(ms, WordprocessingDocumentType.Document))
        {

            MainDocumentPart mainPart = package.AddMainDocumentPart();
            mainPart.Document = new Document();
            var body = new Body();
            Paragraph paragraph = new Paragraph();
            Run run = new Run(new Text("Hello World!"));
            //run.Append(new Text("Hello World!"));
            paragraph.Append(run);
            body.Append(paragraph);
            mainPart.Document.Append(body);
            package.Close();
        }

        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
        result.Content = new ByteArrayContent(ms.ToArray());
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.ms-word");
        result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
        result.Content.Headers.ContentDisposition.FileName = "HelloWorld.docx";
        return result;
    }
}

Thursday, January 9, 2014

JQuery UI MVC

With the advent of ASP.NET MVC, the web development paradigm changed. We are now doing more client side coding than ever. Luckily JQuery is helping us to simplify the client side coding. But still there is a big learning curve. This learning in tandem with MVC learning is a humungous task.

Our open source product, JQuery UI MVC Extensions (aka Juime) eliminates or reduces your JQuery coding without sacrificing the rich web development, so that you can focus more on your strengths, MVC development.  

Our goal is to provide simple yet efficient developer experience while creating complex UI elements. That is the reason we based our Juime on top the most populat JQuery UI components. In this blog I will show you how to easily create a tab in your view using the razor syntax you already know.
@(Html.Juime().Tab("tabId")
      .Panels(panels => {
                  panels.Add(panel => {
                               panel.Header = "First Tab";
                               panel.Action('Action', 'Controller');
                        });
                  panels.Add(panel => {
                               panel.Header = "Second Tab";
                               panel.Ajax('AjaxAction', 'AjaxController');
                        });
                 })
)

The above code demonstrates simple usuage of a tab control. Juime provides full control to the developer by providing several complex options and even client side javascript methods and events.

As you see our syntax is simpler and easy to use than most of the commercially available products. For more information go to our GitHub page

Tuesday, January 7, 2014

Converting SQL Server Express 2008 mdf to LocalDB

As a part of my Web Form modernization, I have to upgrade my SQL Server Express 2008 mdf file. Earlier I was using SQL Express 2008 in my project. The conversion is just 3 step simple process using Visual Studio.
Here are the three step conversion process for converting SQL Server Express 2008 mdf file to LocalDB

1. Open Visual Studio Server Explorer and click “Add Connection”


2. In the “Add Connection”, select the mdf file you want to convert. Click on the Advanced button and ensure that the Data Source is LocalDB.


3. Click Yes to upgrade the database file


Voila the SQL Server Express 2008 mdf file is modernized. You can verify the properties to confirm this. 


This conversion is very simple, but unfortunately this was not properly publicized. As a result there were several news groups’ questions regarding this.