Tuesday, October 6, 2015

What's new in View Component : ASP.NET MVC 6

There are lots of new features added with ASP.NET MVC 6 and View components is one of them.  In this blog post we are going to learn about View Component in ASP.NET MVC 6 in detail.

What is View Components and how it is different from partial views:


As per ASP.NET official web site
New to ASP.NET MVC 6, view components (VCs) are similar to partial views, but they are much more powerful. VCs include the same separation-of-concerns and testability benefits found between a controller and view. You can think of a VC as a mini-controller
So the first question comes in our mind is why we need a View Component as all? As partial views are there and its serving its purpose very well.  But if you have worked with partial views you know that there is a limitation for partial views you can not have controller associated with it. You have to use Child actions with partial views and as you now when you mark any actions with child actions it will only allow for child you can not use that as a complete action. Also it will make a extra server trip which could make your application slow if you have a very complex view.  That where View Component can help.  It's contains a view and backing class It's not a 100% controller but it acts like a controller.

Let's create a View component that can be reused at multiple places. Think about a ECommerce application where you have multiple product categories which can be displayed multiple places in ECommerce application. We are going to create a view component that will list multiple categories.

How to create View Component in ASP.NET MVC 6 Application:


So to create a View component we need a ASP.NET 5 ASP.NET MVC 6 application. So have created web application from Visual Studio 2015.

mvc-view-component-application

Then created a model class category for storing categories information.
namespace ViewComponentMVC.Models
{
    public class Category
    {
        public int CategoryId { get; set; } 
        public string Name { get; set; }
        public string Description { get; set; }
    }
}
Then created a View component with following code.
using System.Collections.Generic;
using Microsoft.AspNet.Mvc;
using ViewComponentMVC.Models;

namespace ViewComponentMVC
{
    [ViewComponent(Name = "ProductCategoriesComponent")]
    public class CategoryViewComponent : ViewComponent
    {
        public IViewComponentResult Invoke()
        {
           var categories = new List<Category>()
           {
               new Category {CategoryId = 1, Name = "Clothes",Description = "Men and women's clothes"},
               new Category {CategoryId = 2, Name = "Elentronics", Description = "Eletronics"}
           };
            return View(categories);
        }

    }
}
Here there are three things to notice

  1. I have inherited class from ViewComponent from Microsoft.AspNet.MVC name space
  2. I have created a invoke method which will return data for the view. In our case we have created manual list as we don't need database for this example. But you can write any code for the same.
  3. See view component attribute on the top of class. We need to use same name when call this view component.
Now it's time to create a view for the view component. I have created this component under /Views/Home/Components/ProductCategoriesComponent/default.html as we have given same name in attribute. As this view component is used home/index.cshml I have putted there but if you have generic view than you can put that in share component also. Following is a code for the same. A simple ul-li listing.
@model IEnumerable<Category>
<ul>
   @foreach (var category in Model)
   {
       <li>@category.Name </li>
   }
</ul>
Now it's time to use this view component in one of view. I have putted following code in Views/Home/Index.cshtml.
<div>
    @Component.Invoke("ProductCategoriesComponent")
</div>
When you run this application, It will look like following in browser

view-component-mvc6-brower-rendering.

So you can see how our hard code categories renders under view. Even you can passed argument with view component invocation that we will see in future blog post.
You can find complete source code of this application at following location on github- https://github.com/dotnetjalps/ViewComponentMVC6
Hope you like it. Stay tuned for more!!
Share:
Saturday, October 3, 2015

Routing with UI-Router and Angular.js

In Today's world, Angular.js is one of best JavaScript framework available to create Single page applications. It's provides some great features and with the help of this features we can built great interactive apps. In any single page application routing is very important as in most of the time single page application will not have full post backs. So routing will be very important to give feel like normal page application and sometimes proper routing will increase search engine ranking also.

So in this blog post we are going to learn how we can create routes in Angular.js application with help of UI-Router.

What is UI-Router:


UI-Router is a routing frame work created Angular.js team and its not a part of Angular.js But it built on top of Angular.js. You can say it's a 3rd-Party module and is very powerful. It support most of things that we can do with ng-route and also do many other stuff that is not possible with ng-route.
You can find more information about UI-Router at following link.

https://github.com/angular-ui/ui-router
http://angular-ui.github.io/ui-router/site/#/api/ui.router

Here are few features that is provided by UI-Router.
  1. UI-Router allows nested views and multiple views
  2. It allows you to strong type linking between state based on state names.
  3. State allows you to map and access different information about different states and you can easily pass information between states via $Stateparams parameter.
  4. With states approach your views are not tied to the URL and it is tied to states. Which can be very useful in large applications as you can change UI part without changing URLs.
  5. You can also change Partial UI of application which is not possible with ng-route.

So what are we waiting for let's create a sample application with UI-Router and Angular.js.

Sample application with UI-Router:


I'm going to use visual studio for creating this sample application. So that we can use IIS local express to host this application. I'm going to create asp.net web application.

angular-Ui-route-demo-project

We are going to use empty asp.net web forms application as we are not going to use asp.net code here it's a simple HTML page application to demonstrate the power of UI-Router.

empty-web-application-angular-ui-route-demo
We are going to create sample application with 3 pages.
  1. Home
  2. About Us
  3. Contact Us

So for that we need three html pages which will acts as partial views just like ASP.NET MVC partial views or user control in ASP.NET Web Forms.
I'm going to create a very basic HTML pages with following code.
home.html page code:
<h1>Home</h1>
About Us HTML page code:
<h1>About us page</h1>
Contact Us HTML page code:
<h1>contact us </h1>
And now we are going create index.html and following is a code for that.
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>Angular UI Router Demo</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.min.js" type="text/javascript"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.min.js"></script>
    <script src="app.js"></script>
</head>
<body ng-app="routerDemoApp">
    <ul >
        <li><a ui-sref="home">Home</a></li>
        <li><a ui-sref="aboutus">About us</a></li>
        <li><a ui-sref="contactus">Contact us</a></li>
    </ul>
<div>
    Angualr UI Router Demo
</div>
<div>
    <div ui-view></div>
</div>
</body>
</html>
If you see above code you can see I have added angular.js and angular-ui-router-min.js JavaScript files from the cloud flare CDN and then I have created a ng-app "routerDemoApp" with body tag of html page. I have used UL and Li ta and UI-Sref to create link for our routes. Here also notice ui-view tag in one of div where html pages will be rendered in this div.

So now basic infrastructure is ready now its time to create JavaScript code for our application. So lets create app.js file and write code like following.
// JavaScript source code
var routerDemoApp = angular.module('routerDemoApp', ['ui.router']);

routerDemoApp.config(function ($stateProvider, $urlRouterProvider) {

    $urlRouterProvider.otherwise("/home");

    $stateProvider
        .state('home', {
            url: '/home',
            templateUrl: 'home.html'
        })
        .state('aboutus', {
            url: '/aboutus',
            templateUrl: 'aboutus.html'
        })
        .state('contactus', {
            url: '/contactus',
            templateUrl: 'contactus.html'
        });

});
So if you see above code carefully, Here I have created a angular app module called routerDemoApp and I have injected dependency of UI-Router. Then in config function we have created different states for Home, About Us and Contact Us. You can see I have passed two parameter url and template url for each state with respective html pages. Also I have written otherwise function which will return home state by default.

Now let's run this application in browser.

demo-application-browser-ui-router-angularjs

So by default Home page is loaded as you can see and in URL also you have /home now when you click on About us it will load about us page like following.

about-us-demo-page-in-browser-ui-angular-js

So it's very easy to create routing with Angular UI-Router in future post we will see how we can use nested view and multiple view.
You can find complete source code of this application at github on- https://github.com/dotnetjalps/AngularUIRouter
Hope you like it. Stay tuned for more!.
Share:
Friday, October 2, 2015

Convert C# Object into JSON and vice versa using Jil

I have also written couple of posts about converting C# object into JSON and vice versa. Following is a list of post for the same.

Converting a C# Object into JSON string
How to convert C# object into JSON string with JSON.NET

In this blog post we will learn about how we can convert C# object into JSON with Jil- Fast .NET JSON (De)Serializer, Built On Sigil an open source library by stack exchange team.

What is Jil:


Jil is a open source (De) Serializer library written by Kevin Montrose and stack exchange team. It is built on Sigil- with a number of crazy optimization tricks.Sigil is also a custom fast validation helper for .NET CIL Generation. Jil is one of fastest Serializer and deserializer library. It is also open source. You can find more information about at following link.

https://github.com/kevin-montrose/Jil

Example:

So let's create example which demonstrate both Serializing and Deserializing object. So first we will create JSON string from C# object via serializing with Jil and then we again deserialize that string to C# object. I'm going to create a console application for this.

jil-jason-converter

After creating a application first thing we have to do is to add Nuget package from JIl via following command.

nuget-package-jil-json-serializer

I'm going to use a Employee class for this example which have four properties Employee Id, First Name, Last Name and Designation.
namespace CsharpJSON
{
    public class Employee
    {
        public int EmployeeId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Designation { get; set; }
    }
}
Then I have created a function Get Employee function to initialize Employee class with some data.
private static Employee GetEmployee()
{
    var employee = new Employee
    {
        EmployeeId = 1,
        FirstName = "Jalpesh",
        LastName = "Vadgama",
        Designation = "Technial Architect"
    };
    return employee;
}
Now it's time to serialize that employee class into JSON string so I have created  Serialize Employee function.
private static string SerializeEmployee(Employee employee)
{
    using (var output = new StringWriter())
    {
        JSON.Serialize(
           employee,
            output
        );
        return output.ToString();
    }
}
Here you can see I have use JSON.Serialize function which serialize C# object into string writer. Same way I have created Deserialize Employee function to deserialize JSON string created by previous function.
private static Employee DeserializeEmployee(string employeeString)
{
    return JSON.Deserialize<Employee>(employeeString);
}

Here you can see I have used  JSON. Deserialize function to convert JSON string into C# object. Finally I have called this function in my console application Main method and print it with Console.Writeline method.
static void Main(string[] args)
{
    var employee = GetEmployee();
    string employeeSerializedString = SerializeEmployee(employee);

    Console.WriteLine("Serialize Employee");
    Console.WriteLine(employeeSerializedString);

    Console.WriteLine("\n\nDeserializing Employee");
    var employeeDeserialized = DeserializeEmployee(employeeSerializedString);

    Console.WriteLine(employeeDeserialized.EmployeeId);
    Console.WriteLine(employeeDeserialized.FirstName);
    Console.WriteLine(employeeDeserialized.LastName);
    Console.WriteLine(employeeDeserialized.Designation);

    Console.ReadKey();
}

Now when you run application it will generate output like following.

json-csharp-object


You can find complete source code of this application at following location on GitHub- https://github.com/dotnetjalps/CsharpJsonJil

Hope you like it. Stay tuned for more!
Share:

A Better Solution to create PDF with Rotativa and ASP.NET MVC

In most of the line of business application we need some kind of reports. Now days we need those reports as PDF format as it is the most convenient way of storing documents. I have written a post about creating a PDF in ASP.NET MVC with Razor PDF and it is one of the top visited page on my blog.

Creating PDF with ASP.NET MVC and RazorPDF

But now I have found a better way to create a PDF with ASP.NET MVC so I thought it will be a good idea to write a blog post about it. So in this blog post we are going to learn about creating PDF with ASP.NET MVC with the use of Rotativa as open source framework for creating PDF with ASP.NET MVC.

What is Rotativa:


It is a framework created by Giorgio Bozio with the purpose of creating PDF in ASP.NET MVC extremely easy way. It is based on wkhtmltopdf tool to create PDF from html content rendered on browser. It uses the web kit engine which is used by Safari and Chrome browser to render html. And support most of HTML tags and styles. It is a open source command line tools so Giogio has created a nuget package to use this tool as PDF creator. You can find more information about Rotativa from the following links.

http://letsfollowtheyellowbrickroad.blogspot.it/
http://www.codeproject.com/Articles/335595/Rotativa-how-to-print-PDF-in-Asp-Net-MVC

You can find source code of rotativa-

https://github.com/webgio/Rotativa

Now let's create example to demonstrate the power of Rotativa with ASP.NET MVC

Creating PDF with ASP.NET MVC and Rotativa:


So to create example, I have created a ASP.NET MVC application.

asp-net-mvc-pdf-application

The first thing we need to do is to add Rotativa Nuget Package in our application.

nuget-package-for-rotativ-asp-net-pdf
Here is the model class I have used to demonstrate power or Rotativa.
namespace MvcPdf.Models
{
    public class Customer
    {
        public int CustomerId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string ProfileImage { get; set; }
    }
}
In this example, we are not going to use any database so we are going to hardcode data in customer. so We have done is hardcode list of customer in controller and returning it to a view.
using MvcPdf.Models;
using Rotativa;
using System.Collections.Generic;
using System.Web.Mvc;

namespace MvcPdf.Controllers
{
    public class CustomerController : Controller
    {
        private List<Customer> _customers;

        public CustomerController()
        {
            var imagePath = "profile.jpg";
            _customers = new List<Customer>()
            {
                new Customer {CustomerId = 1, FirstName = "Jalpesh",
                               LastName = "Vadgama", ProfileImage = imagePath},
                new Customer {CustomerId = 1, FirstName = "Vishal", 
                               LastName = "Vadgama", ProfileImage = imagePath}
            };
        }

        // GET: Customer
        [HttpGet]
        public ActionResult Index()
        {
            return View(_customers);

        }
    }
}
And in view we has displayed this list as table like following.
@model List<MvcPdf.Models.Customer>

@{
    ViewBag.Title = "PDF Title";
  
}

<h2>Convert to  PDF</h2>

<table class="table">
    <tr>
        <td class="alert-success">First Name</td>
        <td class="alert-info">Last name</td>
        <td style="background-color: yellow;">Profile Image</td>
    </tr>
    @foreach (var item in Model)
    {
        <tr>
            <td>@item.FirstName</td>

            <td>@item.LastName</td>
            <td><img src="@Url.Content("~/content/" + Path.GetFileName(item.ProfileImage))" alt="" width="100" height="100" /></td>
        </tr>
    }

</table>    
          
@Html.ActionLink("Print", "Print", "Customer")
If you see in above code, I have used a image to display profile pic. I have also used different styles for td element in table to display power of Rotativa. Even I have used hardcoded style directly.  At bottom I have created  Html Action link to print this view as PDF and following is a code the printing this view as PDF in Action Result.
public ActionResult Print()
{
    return new ActionAsPdf("Index", _customers);
}
And when we run this application it looks like following.

browser-demo-pdf

Now when you click on Print it will create a PDF like following.

pdf-created-with-rotativa-with-browser

This was pretty basic demo but there are lots of options also available with Rotativa you can find that options in documentation on Github as well. I have shared same link above.
You can find source code of this sample application on github at following location - https://github.com/dotnetjalps/AspNetMvcPdfRotativa
Hope you like it. Stay tuned for more!!
Share:

My Interview on Geek.Fest - What's new in C# 6

I have been featured on Geek.Fest a you channel by Fanie Reynders. I have lots of fun while talking about latest C# features. We had interesting discussion and demo of latest c# features. Following is a video on the you tube.



You can find blog from Fanie at following location.
http://reynders.co/2015/10/01/geekfest-9-whats-new-in-csharp-6/

Following is the sample code and demo for the discussion.
https://github.com/dotnetjalps/LatestCSharpFeatures

Thank you very much Fanie Reynders and Geek.Fest for featuring me.
Share:
Friday, September 18, 2015

Why it's the right time to learn TypeScript.

In Today's world, If you are an web developer and you don't know JavaScript then you will feel left behind. It's never been a good time to be a JavaScript developer than now. With the rise of Node.js  JavaScript is everywhere now. But as you know when Size and Complexity of your JavaScript is Increased it's very difficult to maintain and mange. That's where TypeScript comes into picture. It is a life saver some times. So in this blog post we will see Why It's the right time to learn TypeScript.

What is TypeScript?


TypeScript is a free and open sourced programming language developed and Maintained by Microsoft. It works as a super set of JavaScript. As we all know that JavaScript is very liberal language by nature. So that we tend to make more mistakes and we does not know all the errors at run time. TypeScript is a strict super set of JavaScript so that you can get most of errors at compile time only.  As per official website of TypeScript it's a language that lets you write JavaScript in the way you really want to. TypeScript offers all the features that you need for Object oriented programming. You can find more information about TypeScript on it's official web site on below link.

http://www.typescriptlang.org/

ECMAScript and TypeScript:


ECMAScript is the specification standard of the JavaScript. So right not standard stable version if ECMAScript 5 and some of the browsers support ECMAScript 6. ECMAScript 6 features are being adopted by latest browsers.While TypeScript follows most of syntax of ECMAScript 6 so that you don't have a feel of the learning new language. As per official road map of Typescript 1.6 comes with ES6 Generator so you can convert your script code into ECMAScript6. Your can find more about that on following blog post.

http://blogs.msdn.com/b/typescript/archive/2015/09/16/announcing-typescript-1-6.aspx

TypeScript is everywhere:


As we know TypeScript is a fully Object Oriented language, It's provide great productivity boosts than JavaScript and it's super set of JavaScript so it will be compiled into JavaScript itself. So because of this lots of great framework started using TypeScript like following.
  1. Angular JS
  2. Iconic Framework for creating frond end mobile App
  3. Native Script from Telerik is also completely written TypeScript itself.
Take a example of AngularJs, It is one of the most popular JavaScript Framework on earth. With Angular.js 2.0 it will be fully written with TypeScript.

Tooling:


Most of Web Development editor whether it's paid or free are having TypeScript tooling.  Most popular editors like Visual Studio, Visual Studio Code, WebStorm, Atom, Sublime text and Eclipse are having great tooling for TypeScript.

Why to use TypeScript:


Followings are reason why we should use TypeScript instead of JavaScript.
  1. Fully Object Oriented support with classes and interfaces. So It's a great productivity boost for any developer and easily maintainable and understandable.
  2. It's provide most of the errors compile time while JavaScript is more liberal than this. So less run time error means less bugs for your application.
  3. Refactoring is very easy in TypeScript compare to JavaScript.
So it's never been late. It is the right time to learn TypeScript. Hope you like it. Stay tuned for more!.
Share:
Thursday, September 17, 2015

Which visual studio themes you use? Interesting Survey

I have been using Visual studio since 2003 version and it's been decade and still my favorite editor. With visual studio 2010 they have introduced blue theme and With Visual Studio 2012 they also introduced a black theme. Lots of people are using lots of different themes. Some people like black themes and some does not. I had always argument with my friends about visual studio themes. So I thought it will be a good idea to get survey about themes and so what I have done is to put a survey on my blog. As you know this blog is technical blog so most of my readers will be developers. So far I have got a interesting data so I thought it will be a good idea to write a blog post and share those data with you.

So till now I have got total 124 votes for my survey  and here is the result of the survey till now.

visual-studio-theme-survey

From, the above survey I get following fact.
  1. Lots of people like black themes out of 124 votes I got 49 for black themes. So black theme is most the popular one.
  2. To my surprise light theme comes second which I thought will be a third place but I got 39 votes for that.
This survey is still open for the five days. So if you are new to this blog and still not cast your votes then its right time to do.

Where I can get customize Color themes:


If you need more customized colour  themes than I request you to visit http://studiostyl.es/. It got thousand of customized colour themes.

Visual Studio Theme editor extension:


If you need more option than this three themes and then you should also try visual studio color theme editor extension. It's available from visual studio 2010. Here is the links for different visual studio versions color theme editor extensions.

Visual Studio 2010:
https://visualstudiogallery.msdn.microsoft.com/20cd93a2-c435-4d00-a797-499f16402378

Visual Studio 2012:
https://visualstudiogallery.msdn.microsoft.com/366ad100-0003-4c9a-81a8-337d4e7ace05

Visual Studio 2013:
https://visualstudiogallery.msdn.microsoft.com/9e08e5d3-6eb4-4e73-a045-6ea2a5cbdabe

Visual Studio 2015:
https://visualstudiogallery.msdn.microsoft.com/6f4b51b6-5c6b-4a81-9cb5-f2daa560430b

Once you install you will get lots of default color theme choice as well you can customize your theme and save it.

visual-studio-theme-editor-default-options

Which color theme I'm using:


Now it's time to write about my personal preferences. It totally depends on the lighting condition where I am using visual studio. If there a lots of light I prefer to use light theme while if it is dark then I like to have dark visual studio theme.

Hope you like it. Stay tuned for more. Still this survey is open for next five days. Please do vote for your favorite themes.

Update on 1st October 2015

Here is the latest update for the survey, the survey are closed now and here is the final result.


Here are the some statistics

Survey period : 1 Month
Total votes so far: 149
Winner : Black

Clearly Black themes are more popular!.

Thank you all who participated on survey!!. Keep reading my blog and participate in this kind of survey
Share:

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog

  

My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews