Thursday, August 8, 2013

Unit Testing MVC4 Application With Dependency Injection

Introduction

In this article we will see how to Unit Test a MVC4 application with Dependency Injection. 

Steps

The MVC application we will be using is already explained to a previous article. As explained in the previous article, we have a "GuestBook" controller as explained below.

UnitTesting1.jpg

One of the issues with the current implementation of the "GuestbookController" is that it directly instantiates and uses the "GuestbookContext" object, which in turn accesses the database.

The solution to this is to decouple the controller from the GuestbookContext. Instead of accessing the "GuestBook" data directly from the DB, we will create a repository as below.

UnitTesting2.jpg

A concrete class that implements the "IGuestBookRepository" interface method is created as in the following:

UnitTesting3.jpg

Note that this concrete class has the direct reference to the "DBContext". Let's integrate this repository into the "GuestBook" controller.

Before making any changes to the "GuestBook" controller, remove the DBcontext code and create a local variable to hold the "IGuestBookRepository" interface instance. 

UnitTesting4.jpg

Rather than instantiating the GuestbookContext, we now store an instance of our repository within a field. The controller's default constructor populates the field with the default implementation of the repository. The second constructor allows us to provide our own instance of the repository rather than the default. This is what we'll use in our unit tests to pass in a fake implementation of the repository.

The actions in our controller now use the repository, instead of using the LINQ queries that will do the direct DB call.

UnitTesting5.jpg

All these changes are for removing the dependency with the database and we make the existing application work without any issues.

UnitTesting6.jpg

Create a simple fake repository as below that implements the "IGuestbookRepository" interface.

UnitTesting7.jpg

Let's start to create a new unit test project from an existing application.

UnitTesting8.jpg

Create a new test method that is using our Fake repository: 

UnitTesting9.jpg

Create a complex test method like the following one, it asserts that a list of "Guestbook" objects was passed to the view.

UnitTesting10.jpg

Both tests make use of the fake repository "B". By passing it to the controller's constructor, we ensure that the controller uses our fake set of in-memory data rather than connecting to the real database.

UnitTesting11.jpg

As we saw in the Test Explorer, both tests are run successfully, independent of the database.

Summary

In this article we saw basic unit testing of MVC4 application. Dependency Injection was used in the controller to remove the database dependency. For more information about Dependency Injection, please check the following link.

http://martinfowler.com/articles/injection.html 

Monday, August 5, 2013

Working With MVC4 Application

Introduction

In this article we will create a simple "GuestBook" application using MVC4 and Entity Framework.

Steps
First install the "EntityFramework.SqlServerCompact" NuGet package in your application.

MVC1.jpg

Create a simple Model class for our application:

MVC2.jpg

After this package installation, we need to create a Database context class that helps to interact with a database using our GuestBook Model.

MVC3.jpg

The class inherits from the DbContext base class (that resides in the System.Data.Entity namespace), and it begins by declaring a parameterless constructor that uses constructor chaining to pass the name of the database to the base class.

We pass the string "Guestbook" to the base constructor. If we don't do this then the Entity Framework will default to using the full type-name of the context class as the name of the database, and will instead look for a file called "Guestbook.Models.GuestbookContext.sdf".

In the "App_Data" folder we can see the "GuestBook.sdf" file.

MVC4.jpg

We will create a controller that we use in GuestbookContext.

MVC5.jpg

We created two action methods, "index" retrieves the data from the Database and "create" is used to post data to the database.

We also created two simple views to render the Action Results.

MVC6.jpg

Index view to show the "GuestBook" result from the database.

MVC7.jpg

Let's see the results in a browser. The Guest Book create page looks like the following image, we simply enter the data and save that to the local database.

MVC8.jpg

The result page look likes the following image:

MVC9.jpg

That's it. But how is the data is stored in the database? Let's do some analysis. Install the "Glimpse" tool to begin analysis of the MVC application. Check the following link for more information about it.

http://www.hanselman.com/blog/NuGetPackageOfTheWeek5DebuggingASPNETMVCApplicationsWithGlimpse.aspx

As you can see, there's no connection string in Web.config, instead we will see the following data provider.

MVC10.jpg

We check the Glimpse and we will get the database details as below.

MVC11.jpg

Summary

In this article we saw "Guest Book" application creation in MVC4, used the Entity Framework to work with the database and used "Glimpse" to understand the Entity Framework local database.

Tuesday, June 25, 2013

Using Productivity Power Tools 2012

Introduction:
In this post we will features of Productivity Power Tools 2012 in Visual Studio 2012 and how it improves developer productivity.
Why Productivity Power Tools 2012 :
In VS 2012 already has many features while compared to other versions, but Productivity Power Tools 2012, A set of extensions to Visual Studio 2012 Professional (and above) which improves developer productivity. We will some of features below.
Features:
Format document on save 
usually developers will formatting the code manually, but this really just we want to save the file, by default it automatically format the file.
Remove and Sort Usings on save
Removing unused using statements is one of the Re-factor method and it also sorts the remaining using statements in the C# document being saved.
Email CodeSnippet
Creates an email with the currently selected text. Available via right-click menu in the source code editor.
Undo Close
It's just like browser tab, we can reopen the closed tab in visual studio also.
Auto Brace Completion
Automatically inserts the closing code construct when an opening construct is typed for VB & C#.
Ctrl + Click Go To Definition
Enables clickable hyperlinks to symbols in source code in your code by holding down the Ctrl key when hovering with the mouse.
Move Line Up/Down Commands
Maps the Alt+Up Arrow & Alt+Down Arrow keys such that they will move the current line of code or the selected lines up and down through the editor.
PresentOn
Turns  on presenter mode which increases environment and text editor font sizes, and  sets them to certain font families, so that VS is easier to see and read on a  projector.
Summary:
If we are using Visual Studio 2012 “Productivity Power Tools 2012” is must required extensions and its free. Still some other features also there.
Download Link:

Friday, January 18, 2013

Create Sites Using Custom Site Templates in SharePoint 2010


Introduction

In this article we will see how to create sites using custom site templates programmatically in the SharePoint 2010 Server Object Model.

Steps

The following code shows how we usually create a site using the default SharePoint 2010 templates/definitions.

Creating-site-in-SharePoint1.jpg

The "SPWeb" object's "Add" method creates a Web Site object with the specified site-relative URL, title, description, locale ID  and site definition or site template name. "STS#1" represents the blank site template.

We will create a sample UI page to get the inputs as shown below.

Creating-site-in-SharePoint2.jpg

Once the site has been created successfully, we can navigate to the site and check whether the blank site was created or not.

Creating-site-in-SharePoint3.jpg

But we need to create a site using a custom template. For demo purpose we use any existing site and store it as "Site Template" in the "Solution Gallery" and activate the solution. We will see the solutions in the following navigation path for any root site. All the solution files are saved in .wsp file format.

Path: "Site Actions" --> "Site Settings" --> "Solutions"

Next we need to get the solution/template id dynamically from the solution gallery. We will have the following code to get the template id and write it as a helper function.

Creating-site-in-SharePoint4.jpg

Usually many templates are available in the collection. If required we will pass the "Solution Name" as input and get the particular template id.

Creating-site-in-SharePoint5.jpg

Finally we need to pass the result template Id to create a new site, instead of default templates. It'll create a new site using our custom template.

Creating-site-in-SharePoint6.jpg

Summary

Suppose we have a large site with hundreds of lists and a document library, it's really easy to get the entire site structure as a template and using this method we can use the same custom template to create new sites programmatically.

Notes
  • Before we try this logic, we need to ensure that the "SharePoint Server Publishing Infrastructure" feature is activated at the site collection and site level.
  • The Site template will not have any information about the sub-sites and its content.
  • Before we save the site as "Site Template", we need to check to determine if any custom features are deployed and activated. Because while we use the same template , it'll expect the same features need to be activated.
  • The entire sample code is attached here.

Friday, January 4, 2013

Chrome control in apps for SharePoint 2013



Introduction:

        In this post we will see the basics about “Chrome Control” in apps for SharePoint 2013.


About Chrome Control:

                The Chrome Control downloads a copy of the style sheet used in the parent site and applies it to the HTML pages in your client-side App. We can find the default style for any site in the below URL format.

http://{SharePointSite}/_layouts/15/defaultcss.ashx

Chrome control basically apply style sheet to App page.

Steps:
                We need to dynamically load the "SP.UI.Controls.js" file, which is available in “/15 hive” path. We load this script using Jquery library as mentioned below.




Then create a collection to hold the chrome control option values. 


Finally, instantiate a new Navigation object using the container <div> added to the page markup in the previous step and make the object visible.


We can combine all these scripts into a single file called “ChromeLoader.JS” and refer this JS in our HTML/ASPX page and mention a div with “chrome_ctrl_container” id.

Now if we run the page we will get the below output.

The Navigation Bar with setup icon and menu will be loaded as per our configuration mentioned above.


The same settings will be configured directly in HTML as in below image and the output will be the same.

 

Summary:

            Chrome control in SharePoint 2013 App allows addition of custom navigation nodes that links to other pages and help pages. The demo App in Office 365 hosted App.



Thursday, December 13, 2012

Hello World App Using ASP.NET SignalR


Introduction

ASP.NET SignalR is an async signaling library for .NET to help build real-time, multi-user interactive web applications. In this article we will see, how do create a basic application using ASP.NET SignalR.

Previously SignalR was a standalone entity, now it's integrated as part of ASP.NET framework. You can check the following fall update.

http://www.microsoft.com/en-us/download/details.aspx?id=35493

Procedure

We can check the following documentation to understand the basics about SignalR.

https://github.com/SignalR/SignalR/wiki

We will create a simple application that the user can drag and drop the Div/Box and the same position of the box will be updated to all clients. First we need to add a reference for the SignalR dlls; we can use the Nuget package also to add the references.

http://nuget.org/packages/microsoft.aspnet.signalr

ASP.NET-SignalR.jpg

The same Nuget Package can also install the required JavaScript files and we added the "Jquery.UI" plug-in for the demo application.

Nuget-Package.jpg

We will create a simple "Hub" to broadcast the required actions (method) from the server as explained below. Please note that we need to add the "Microsoft.AspNet.SignalR.Hubs" namespace and the application namespace should be unique across the application files.

Microsoft.AspNet.SignalR.Hubs.jpg

We will prepare the client, just added a HTML page and the following JavaScript references and div tag.

JavaScript-references-and-div-tag.jpg

We don't have the manual reference for "signalR/hubs" js, it'll automatically be created at runtime and does the all magic. We'll add the following JavaScript to complete our functionalities.

manual-reference-for-signalR-hubs.jpg

In the preceding script we have three parts:

  1. We need to create a connection to the server and the same "Hub" name should be used in this connection statement.
  2. We can define the client side event called "shapemoved" and do the actions at the client side. Here we set the CSS property to the "shape" div. If we notice the "Hub" code we are calling this client side event from the server.
  3. The final one to do is we need to call a server side method "action" which is a "Hub" method. We called the "action" method in the client side "drag" function.
That's all, now we will see the result in action, if we drag the box in one browser and it's automatically updated in other clients.
result-in-action-Nuget-Package.jpg

Summary

ASP.NET SignalR is a new library for ASP.NET developers that make it incredibly simple to add real-time web functionality to your applications. What is "real-time web" functionality? It's the ability to have your server-side code push content to the connected clients as it happens, in real-time.
 

Hello World App Using Client Web Part in SharePoint 2013

Introduction

In this article we will see how to create and use a "Client Web Part" using the Office Napa Tool. In the previous article, we covered the basic App development using Napa Tool.
Steps

First we will navigate to the "Napa office 365 Development Tools" and select any existing App or create a new one.

Image1.jpg


Image2.jpg

Image3.jpg

Once your application opens, select the "ClientWebPart.aspx".

Image4.jpg

Add the following code to develop a simple application that will just list the latest 10 tweets.

Image5.jpg

Add the "JS" event to populate the tweets.

Image6.jpg

Create a new site page (wiki page) in our SharePoint 2013 site and edit the page.

In Edit mode navigate to the Ribbon ->Insert -> click App part

Image7.jpg

Select the SharePoint App and add it to our page.

Image8.jpg

Image9.jpg

We will ensure that the web part will work fine. Now it will load the tweets.

Image10.jpg

Summary

Using "Client Web Part" we easily add any "App Functionality" to our pages.