Saturday, February 22, 2014

Creating Durandal SPA application without Visual Studio template

As you know there are several Visual Studio Templates which gives a quick start for your SPA development. If you are like me, then you want to know what is the plumbing code for the SPA development. In this blog I will give you step by step instructions on building a Durandal SPA application using any Visual Studio Templates

Before we start, we need all the dependencies of our application. Download all the below dependencies from their websites


In addition we also need couple of nuget packages. Which we will download while setting up the project.
Once all the necessary scripts files are downloaded, let’s fire up Visual studio. Below are the steps we need to follow to create a Visual Studio durandal project

  • Create MVC Empty project
  • Create Content & Scripts Folder
  • User Scripts create Durandal and copy all the files downloaded from durandal under js. Include them in the solution
  • Again under Scripts Create foundation and copy the scripts from zurb foundation and include them in the solution
  • Copy Knockout under scripts folder, similarly copy jquery, require, text
  • Under content copy durandal.css, foundation.css, normalize.css
  • Under content create app.css which is used by our SPA
  • In the root project create folder App & under it create viewmodels & views. This is where we will keep all our SPA scripts
  • Under App_Start create BundleConfig.cs which will include the bundle configuration for all the javascripts and css.
  • Install the Nuget package: Install-Package Microsoft.AspNet.Web.Optimization
  • Include the following code in the BundleConfig.cs
    public class BundleConfig
    {
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(
                new ScriptBundle("~/scripts/libraries")
                    .Include("~/scripts/jquery-{version}.js")
                    .Include("~/scripts/knockout-{version}.js")
                    .Include("~/scripts/knockout.validation.js")
                    .Include("~/scripts/knockout.viewmodel.js")
                    .Include("~/scripts/foundation/foundation.js")
                    .IncludeDirectory("~/scripts/foundation""*.js")
                );

            bundles.Add(
                new StyleBundle("~/content/css")
                    .Include("~/content/normalize.css")
                    .Include("~/content/foundation.css")
                    .Include("~/content/durandal.css")
                    .Include("~/content/app.css")
                );
        }
    }


·         In the global.asax on the Application_Start initialize the bundle config
 BundleConfig.RegisterBundles(BundleTable.Bundles);

  • Add Home Controller
  • Add a view without using layout page option and use the below code
@using System.Web.Optimization
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>My First SPA</title>
    @Styles.Render("~/Content/css")
</head>
<body class="main">

    <div id="applicationHost">
        <div class="splash">
            Page loading ...
        </div>
    </div>

    @Scripts.Render("~/scripts/libraries")
    <script src="~/Scripts/require.js" data-main="@Url.Content("~/App/main")"></script>
</body>
</html>

With this we are done with MVC setup. Now we need to create the javascript files


  • Create main.js which is starting point for Durandal and include the below code
//require configuration for durandal
require.config({
    paths: {
        'text''../Scripts/text',
        'durandal''../Scripts/durandal',
        'plugins''../Scripts/durandal/plugins',
        'transitions''../Scripts/durandal/transitions'
    }
});

//defining global libraries
define('jquery'function () { return jQuery; });
define('knockout', ko);

//starting the app
define(['durandal/system''durandal/app''durandal/viewLocator''durandal/composition'], function (system, app, viewLocator, composition) {

    app.title = 'Hello World';

    //specify which plugins to install and their configuration
    app.configurePlugins({
        router: true,
    });

    app.start().then(function () {
        //Replace 'viewmodels' in the moduleId with 'views' to locate the view.
        //Look for partial views in a 'views' folder in the root.
        viewLocator.useConvention();

        //Show the app by setting the root view model for our application.
        app.setRoot('viewmodels/shell''entrance');
    });
});

  • Create shell.js & shell.html under viewmodels & viewfolders. Shell is like a layout page in MNC and include the below code
     o   shell.js
define(['plugins/router'], function (router) {
    return {
        activate: activate,
        router: router
    };

    function activate() {
        var routes = [
                        { route: ['''home'], moduleId: 'home', title: 'Home' },
        ];

        router.makeRelative({ moduleId: 'viewmodels' }) // router will look here for viewmodels by convention
            .map(routes)            // Map the routes
            .buildNavigationModel() // Finds all nav routes and readies them
            .activate();            // Activate the router

    }
});

     o   shell.html
<div>
    <h1>Title</h1>
        <br />
        <div class="content"
data-bind="router: { transition: 'entrance', cacheViews: true }"></div>
</div>

  • Finally define home.js and & home.html. This is like an index page in MVC
     o   home.js
define([], function () {
    var vm = {
        activate: activate
    };

    return vm;

    function activate() {
        return true;
    };

});

o   home.html
<div>
    Hello World!
</div>


We are done. Now compile and run the application to see our SPA application that was built without any template.

Source : http://www.slideshare.net/PrasannaPattam/creating-durandal-spa-application-without-visual-studio-template

Friday, February 21, 2014

Team Foundation Server and Git Mirroring

I typically use TFS for all my development. I also work on some open source projects. I want to host those open source projects on GitHub for public access. At the same time I want to keep all my projects on a single place, which is my TFS. So I want keep TFS as my master source and push my changes to GitHub for public access. In other words I want to mirror my TFS projects on GitHub.

It turned out that the mirroring TFS and Git seems to be simple. First we need to setup TFS using local git repository. Check the below MSDN link for more details:


Once you have local GIT & TFS configured. You do the development and push the code to TFS as you do always. Whenever you want to push the code to GitHub go the command prompt and navigate to the .git folder that is under the repository directory. Run the below command line to mirror your TFS code to GitHub

(replace username, passwod and repo with your values)

With above command all the changes done in TFS will be mirrored. With this command line you can decided when to sync your TFS changes to Git. If you want to do this automatically you can use one of the Git hooks.

Friday, February 14, 2014

ASP.NET SPA Naming Conventions

As we started embracing rich client side technologies such as Single Page Applications and some popular JavaScript libraries, we will all face the challenges of diversities in .NET and JavaScript. One of those diversities is the naming convention.

As Javascript is based on java, its naming conventions will be similar to that of Java. For example in JavaScript we use camel casing for methods, where as we use Pascal casing in .NET. Similarly .NET naming guidelines discourage the use of underscores, but they are freely used in JavaScript.

With SPA technologies we need to pass data between the JavaScript objects and .NET objects. That means objects will be passed from one technology to another. The objects defined in .NET will be used in JavaScript and similarly objects defined in JavaScript will be used in .NET.

Being a hardcore .NET developer I could say use .NET naming conventions throughout, why should I learn or use other naming convention? On the counter argument, there is a popular saying, be a Roman in Rome, so we have to follow JavaScript naming conventions in JavaScript. Doing so will make our code readable by non .NET folks. So the dilemma is to use .NET naming conventions or JavaScript naming conventions.

As ASP.NET is a conglomeration of technologies, we should find an amicable solution for this. I would recommend to use a hybrid naming conventions. I propose to use JavaScript naming conventions in JavaScript and .NET naming conventions in .NET. For the objects that will be passed across layers use .NET naming convention. By following this approach, the .NET side will have a clean naming conventions and JavaScript will have a hybrid naming convention.

Wednesday, February 12, 2014

Ranking Functions


Today we are going to discuss about ranking functions and their benefits.Lets start with a basic question ,
  • What is a Function ?
A function is a method which expects some parameters and will return an output.SQL Server has many functions.Since our point of interest for now is ranking function so we will discuss the same first.
  • What is a Ranking Function ?
Ranking functions return a ranking value for each row in a partition. Depending on the function that is used, some rows may receive the same value as other rows.SQL Server 2005 introduced four new functions, ROW_NUMBER, RANK, DENSE_RANK, and NTILE that are collectively called as ranking functions.. Ranking functions are non-deterministic.Non-deterministic as the name suggests cannot be determined(i.e output is not known to us).
Lets start with a simple example to make a better understanding.First i will create a table consisting some column and rows as follows:
CREATE TABLE tblSample (ID INT IDENTITY, Column1 INT, Column2 INT, Column3 INT)
CREATE UNIQUE CLUSTERED INDEX CLTDINDX ON tblSample(ID)
INSERT tblSample  VALUES (0, 1, 8)
INSERT tblSample  VALUES (0, 3, 6)
INSERT tblSample  VALUES (0, 5, 4)
INSERT tblSample  VALUES (0, 7, 2)
INSERT tblSample  VALUES (0, 9, 0)
INSERT tblSample  VALUES (1, 0, 9)
INSERT tblSample  VALUES (1, 2, 7)
INSERT tblSample  VALUES (1, 4, 5)
INSERT tblSample  VALUES (1, 6, 3)
INSERT tblSample  VALUES (1, 8, 1)
Now we are good to go.Lets start with a basic ROW_NUMBER Function:
SELECT *, ROW_NUMBER() OVER (ORDER BY Column2) AS RowNumber FROM tblSample
Above query will select all the rows from tblSample and will order Column2 and will assign sequential numbers (like sequence object or Identity) to each row.so the result will be:


From the above result you may see the column 2 has been ordered and the sequence number(in RowNumber column) has been assigned to each row.This will clear the definition of a ranking function i.e  Ranking functions returns a ranking value for each row.
Lets take another scenario where you want to group the rows in a particular format.If you closely look at the values in column 1 you will see column 1 has two numbers 0 and 1.Now you want to group the sequence numbers according to column 1.Here we will use partition on column 1.see below query :
SELECT *, ROW_NUMBER() OVER (PARTITION BY Column1 ORDER BY Column2) AS RowNumber FROM tblSample
Above query will partition or you can say group the column1 into two parts one containing 0 and other as 1.output will be :



Above result,all the 0 of column1 has different set of sequence numbers and 1 of coulm1 has different set of sequence.
It is possible to combine multiple ROW_NUMBER functions (or multiple of any of the other ranking functions) with different ORDER BY clauses in a single query:
SELECT *, ROW_NUMBER() OVER (ORDER BY Column2) AS RowNumber1,ROW_NUMBER() OVER (ORDER BY Column3) AS RowNumber2 FROM tblSample
That was all about ROW_NUMBER().Lets see how other function behaves.next Function we are going to discuss is about RANK() & DENSE_RANK().Both the functions are pretty much same.the tables and values are going to be same for better understanding.
lets get back to the previous query we used for rownumber to get a better understanding about rank and dense rank.
SELECT *, ROW_NUMBER() OVER (ORDER BY Column2) AS RWNUM,RANK() OVER (ORDER BY Column2) AS Rank,
DENSE_RANK() OVER (ORDER BY Column2) AS DRank FROM tblSample
Output of this query will be:



RANK gives you the ranking within your ordered partition. Ties are assigned the same rank, with the next ranking(s) skipped. So, if you have 3 items at rank 2, the next rank listed would be ranked 5.
DENSE_RANK again gives you the ranking within your ordered partition, but the ranks are consecutive. No ranks are skipped if there are ranks with multiple items.

Friday, February 7, 2014

Knockout Date Format Extender

As you know Knockout is great on two-way binding and provides a clean mechanism for showing data on the page. There will be scenarios where you want to format your data to make it user friendly. This is especially true when you are showing dates. You don’t want to show the default javascript format to your users. You can certainly format dates while doing the databinding. But formatting dates inside your binding quickly becomes clumsy and sometimes you lose your two-way binding.

In this blog I will show you how to modularize the date formatting and use it throughout the application. Thanks to the Knockouts extenders which allows us to define our date formatting in an elegant way. If you are not aware of Knockout extenders, please check documentation on their site


Before getting into the extender, I want to tell you about a small javascript library, Momentjs, I use for all my date related functionalities. Momentjs is small javascript library for parsing, validating, manipulating and formatting dates. For more information check their website


Using MomentJS, I can do the date formatting to MM/dd/YYYY format by the following syntax.

    moment(newValue).format('L')

MomentJS provides several formatting options. For more information check their website.
Coming back to knockout extender, let’s create an extender called dateformat which format the observable with the specified format.

    ko.extenders.dateformat = function (target, format) {
        var result = ko.computed({
            read: target,
            write: function (newValue) {
                target(moment(newValue).format(format));
            }
        }).extend({ notify: 'always' });

        //initializing with the formatted value
        result(target());

        //return the new computed observable
        return result;
    };

We need to define this extender only once. In Durandal you can define it in the main.js.

This extender can be consume while defining the observable as below:

    var DateOfBirth = ko.observable(new Date('1/4/2000')).extend({ dateformat: 'L' });      

That’s all we need to do. The databinding in the view is same as earlier.

<span data-bind="text: DateOfBirth"></span>


You can use this dateformat extender throughout your website with different format options.

Wednesday, February 5, 2014

Refresh all Browser by Browser link

Browser link features are available in visual studio 2013 onward.

To Check this feature first Create project
Refresh all Browser by Browser link





You can follow below image to debug

Refresh all Browser by Browser link












You can select multiple browser as below by holding CTRL
Refresh all Browser by Browser link


















Now Press the Refresh button or press CTRL+ALT+ENTER all browser window will  refresh.


Refresh all Browser by Browser link













Source: http://www.asp.net/visual-studio/overview/2013/using-browser-link

Tuesday, February 4, 2014

jQuery Plugin to Create Quizzes-SlickQuiz

As we know that creating a quiz is really a complicated task. So help the developer and reduce the coding part we are going to introduce a jquery Quiz plugin...


Click here to check Demo
 
Download Zip File

Could not open a connection to SQL server – Fix Connection Problems of SQL Server

 SQL SERVER – Fix : Error : 40 – could not open a connection to SQL server – Fix Connection Problems of SQL Server

An error Occurred while establishing a connection to sql server.

Solution 1

Go to Control Panel -> Administrative Tools -> Computer Management : Open It
Expand Services And Application-> SQL Server Configuration Manager->

After this Sql server services restart it. then Check.

if it not work 
Check Aliases Option Under.
If you find any aliases for the SQL Server that you are getting problem. Delete it for time being and test it.

Suggestion 2:

Try checking these things,

1. Check SQL Server Browser service is running and is kept in automatic Start mode.

This can be checked by.

Start -> run- > type services.msc -> enter -> check for SQL Server browser service, and start if it is not running.

2. Under SQL Server Surface Area Configuration check if SQL Server allows remote connections, by default it will allow only local connections.

This can be checked by,
Login to Server ( Where SQL Server is installed )
Start-> allprograms -> Microsoft SQL Server 2005->Configuration Tools -> SQL Server Surface Area configuration -> Click Server Area configuration for Services and connections ->choose your sql server – remote connections -> on the right side, choose allow remote connections to this server and choose both TCP/IP and NamedPipes.

3. Or Check your Windows Firewall, if SQL Server is being blocked, try to disable Firewall and then connect if it works then problem could be WIndows firewall.

Suggestion 3:

There are couple of ways to troubleshoot this problem. The one you should use depends on how your databse server was configured and some other factors as well.

For example, if you configure the database engine to use dynamic port allocation, make sure that sql browser is runnning. SQL browser provides the connection information about the database engine to the the client.

If the sql browser is not running and you have restarted sql server and port 1433 is being used by other applications, database engine will be allocated a different port number. Imagine that the client has been configured to use port 1433 to connect and the database engine is using a different port number. The client wont be get the connections properties to the database engine from sql browser because sql browser is not running.

Monday, February 3, 2014

Frog Fu - Open Source Game

 Frog Fu is The Game for you and your family. Children love it! Parents enjoy it! The game takes you deep into a colorful cartoon world of the kung fu frog. Quality animations and rich graphics will quickly make you feel part of this wonderful world.

Frog Fu is iOS game written on C++ with OpenGL 2 now available as open source project on GitHub
Frog Fu - Open Source Game

You can find it on the App Store at: https://itunes.apple.com/us/app/frog-fu/id574269225?mt=8