Getting Started with WCF – Part 4

Hi Friends,

Now with previous theoretical concepts, let’s jump into some practical implementations for the same. So, what i do i simply go ahead and launch my service which i have written earlier for WCF Demo. So, below in the screen shot, test client gets popped from VS 2013. Notice that our Demo service is up and running now.



Now, from this Host, i can go ahead and copy metadata and paste the same in notepad for later reference, which i’ll be using for creating my client.


Now, at this instant, i will return to my Visual Studio and add new project basically to build my client which an talk to the service. So, what i’ll do, i will simply go ahead and add simple console app to talk to this service as shown below.



Then, i can simply go ahead and add reference to my client project with the metadata which i copied initially. For doing the same, i’ll simply click on references and say add service reference as shown below


Then, it will open dialog box, wherein i will simply paste the metadata and click on go.


so, here it downloaded the metadata and showed me the service contract available for the service and also the operation. So, below in the dialog either i can change my service reference name or keep the same, but i am going to make it EmployeeServiceReference and press ok. So, as soon as i clicked ok, it downloaded the metadata and generated all required components for me. In the below screen shot, 1st thing which you will notice it generated all the assemblies required to run the WCF, then it created one App.config file which is nothing but the client side configuration file having the endpoints in it.


It also created service reference in there. So, now if you right click the service reference, you can see all the object level details in the object browser like what properties we created while creating the class, methods etc.


Now, the very 1st thing which we need to do here in our code is to include the client side reference as shown below in the screen shot.


Then, i can go there and instantiate my employee client as shown below in the screen shot. Now, when i instantiate this, it has to be done against one end point


Now, in order to get the endpoint details at the client side, you can open the app.config file at the client side and check what Visual Studio has created for you like shown below


Now, from these options i will select any endpoint of my interest and paste in there. Now, it will construct the communication channel based on the endpoint. Then i need to generate the required information like properties which i used while writing the class then fill the same with data and then in the end i’ll just invoke the method and print the same on the console.


Now, i need to do some setting in the project to make sure that it will run in my console client app. So, for that i’ll come to my service project and click on properties and then


Now, here i need to change this name with our client app which is “ClientDemo.exe”. And then i also need to assign the working directory of my client till debug as “C:\Rahul\Books\WCF\WCFServiceDemo\ClientDemo\bin\Debug\” Now, with that change in place i am good to go.



So, with this output i would like to wrap this session here. Will see in another session more about WCF and it’s terminologies. Till then stay tuned and happy coding.

Happy Coding

Getting Started with WCF – Part 3

Hi Friends,

In today’s post i will talk more about Endpoints and Services. So, basically in the last session we saw how to write a simple WCF program and host the same. So, basically with WCF we write services which expose end points to the outside world. Here, our service implementation will define the actual business logic and endpoints define the communication logic. Basically, endpoints serve various communication logic. We’ll see some of these in some time. Now, below is the diagram which explains the relationship between services and endpoints. So, basically services expose multiple endpoints to it’s consumers and consumers then utilize this service via endpoint.


Now, the question arises here is that what is an Endpoint? well endpoint is basically an information that tells WCF how to setup communication channel. Now, each endpoint address consists of three Major things.
Now, below is the diagram which shows the actual meaning of endpoint in a nutshell.

EndPoints consist three major things. These are

Address:- Basically tells where to send the messages.
Binding:- How to send them.
Contract:- What messages will contain.

Now, these are basically A,B,C of WCF. Address defines network address for sending and receiving messages. Here, WCF runtime will produce a communication channel which will be served as listener for these messages. Then comes the binding which defines the protocol for how to send messages like it specifies what kind of Transport Protocol needs to be used, what message format and what WS-* protocol you want to use. Then, we have Contract, which tells what the messages must contain. So, each endpoint contains three basic information. Hence, services exposes endpoints and client consume them.

Now, let’s discuss binding in detail. In the below table, you can see some of the built in bindings and it’s usage scenarios.


So, as you see in the table 1st three bindings all use HTTP. So, here Transport mechanism is also associated with the binding name. The 1st one provides Restful style communication whereas other two provides SOAP style communication. We’ll understand all these styles of communication in detail in coming sessions. Now, one important point to note here that these 1st three bindings are meant for interoperability which means they will use XML message format for communication.Now, the remaining bindings shown here are basically not meant for interoperability. Basically, they assume that WCF is used on both sides as these bindings are .Net Specific. That is why their naming also begins with net which means .Net to .Net communication. Now, irrespective of these built in bindings, you can always write your custom binding which could be a mix of these built in bindings. By the way, before selecting any binding you should always know which one would be best suited in your case.

Now, let’s see the process of consuming WCF Service. Now, in order to consume the WCF service, client need to know several things like

Where to send the message
How to send the message
Then what the messages are going to contain

So, basically these are the endpoints of any WCF service. So, in order to consume any WCF service client need to know the endpoint of that particular service. Now, below is the most generalized description from the higher level which shows how communication happens.


Now, with WCF we consume services via channels. Below, is the labeled diagram explaining how clients consume WCF service.

Now, channels are basically built based on endpoints. Now, here, the client has to retrieve the endpoint definition from service metadata. Now, as you can see in the diagram we have a Service which is exposing multiple endpoints. I have shown in diagram two endpoints but it can be any number. Then, let’s suppose client wants to talk to this service via this endpoint. Then, in order to do so, client has to request metadata or WSDL definition from the service. Now, once metadata is available to the client, client will run one metadata import tool which will produce client side version of the endpoint. Now, once client has endpoints available; client can then go ahead and construct the channel based on one of the endpoints. And, once the channel has been constructed, client can send message through that channel to the service. So, basically WCF provides nice symmetrical architecture on both sides of the wire.

So, in this session we have seen closely about endpoints, services and then how to consume services theoretically. We will see all these practically in coming sessions. Till then stay tuned and Happy Coding.


Don’t use Data- attribute with anonymous object in C#

Hi Friends,

Today, i just like to share one small tip. Never use Data- attribute with C# anonymous object as C# compiler doesn’t interpret this. Rather than this you can use data_ attribute, which will be understood by the compiler and then it will be converted as data- once page finally rendered. Below, I have small example for the same.

@Html.RadioButtonFor(model => model.IntentToExport, “true”, new { id = “exportYes”, name = Model.ShippingExportFormFieldName, data_action = @Url.Action(“GetCountryAndProductUsageDropDown”, “Shipping”), _checked = Model.IntentToExport.IsTrue() ? “selected” : “” })

will emit

<input id=”exportYes” checked=”checked” name=”ExportCompliance.IntentToExport” type=”radio” value=”true” data-action=”/cart/us/en/rc1005388/Shipping/GetCountryAndProductUsageDropDown” data-val=”true” data-val-required=”Please choose Trade Compliance” />

If you try data- in anonymous object itself, C# compiler will throw error.

Happy Coding

C# in a nutshell

Posted in C# | Tagged

Hands-on With ASP.NET MVC Releasing worldwide on 25th Sept

1st Chapter Glimpse – Hands-On with ASP.NET MVC

Hands on With ASP.NET MVC
Rahul Sahay
Quills Ink Publishing
Copyright © 2014 Rahul Sahay
Hardcover ISBN : 978-93-84318-52-9
Softcover ISBN : 978-93-84318-53-6
Ebook ISBN : 978-93-84318-54-3
Design and Setting By
Quills Ink Publishing

All rights reserved. No part of this publication may be reproduced, distributed, or transmitted in
any form or by means, including photocopying, recording, or other electronic or mechanical
methods, without the prior written permission of the publisher.
The views and characters expressed in the book are of the author and his/her imagination and do
not represent the views of the Publisher.

Chapter 1: Getting Started
WHAT DO you find in this CHAPTER? 1
Introduction 2
Understanding ASP.NET MVC 2
The MVC Pattern 3
Brief History of MVC Pattern 4
MVC Life Cycle 6
Software Requirements 7
Application Glimpse 8
Creating a MVC application 19
How MVC applications are structured 22
Summary 24

Chapter 2: Understanding Controllers
WHAT DO you find in this CHAPTER? 25
Introduction 26
Controllers 26
Working with your 1st controller 30
Action Results 39
Action Selectors 45
Action Filters 49
Summary 49

Chapter 3: Views
WHAT DO you find in this CHAPTER? 50
Introduction 51
Views 51
Syntax of Razor Views 59
How to Prevent Cross Site Scripting Attack 60
More on Razor Syntax 62
Layout Views 68
HTML Helpers 77
HTML.ValidationSummary 86
Some more HTML Helpers 87
Partial Views 91
Viewbag and Viewdata 94
Summary 95

Chapter 4: Getting Started with Data modeling
WHAT DO you find in this CHAPTER? 96
Introduction 97
Using Entity Framework 97
Entities Creation 98
Database Migrations 107
LINQ 114
Search Query 118
Summary 122

Chapter 5: Data modeling- Part 2
WHAT DO you find in this CHAPTER? 123
Introduction 124
Organizing Movie Controller 124
Reviews Listing 137
Create and Edit Facility of Review 142
Validation Annotations 154
Summary 157

Chapter 6: JavaScript and AJAX in MVC
WHAT DO you find in this CHAPTER 158
Introduction 159
Managing Scripts 159
Ajax Helpers 165
Async Search 174
Paging 179
Summary 188

Chapter 7: Security with ASP.Net MVC
WHAT DO you find in this CHAPTER? 189
Introduction 190
Authentication 190
Membership and Forms Authentication 196
Authorize 212
Seeding Membership 216
Cross Site Vulnerability 223
OpenID and OAuth 226
Summary 230

Chapter 8: Caching – ASP.Net Terminology
WHAT DO you find in this CHAPTER? 231
Introduction 232
Caching 232
Cache Profiles 235
Localization 237
Resource Files 241
Diagnostics 247
Summary 256

Chapter 9: Unit Testing
WHAT DO you find in this CHAPTER? 257
Introduction 258
TDD 258
Home Controller Tests 268
Web Tests 276
Load Tests 281
Code Coverage 290
Summary 292

Chapter 10: Deployment
WHAT DO you find in this CHAPTER? 293
Introduction 294
Configuration Files 294
Hosting ASP.Net MVC Application 298
Deployment Preparation 301
Deployment on IIS 309
Deployment to Azure 324
Summary 333

Chapter 11: Routing Basics
WHAT DO you find in this CHAPTER? 334
Introduction 335
Route Definition 335
Areas 337
Ignore Routes 338
Debugging Routes 338
Constructing URLs from Route 340
Route Data 341
Route Constraints 342
Summary 342

Chapter 12: Web API and Dependency Injection
WHAT DO you find in this CHAPTER? 343
Introduction 344
Why Web API 344
Creating a new empty Project 345
Adding Web API to an ASP.Net Project 351
Creating your 1st controller 353
Dependency Injection 356
Implementing POST 363
Implementing DELETE 367
Implementing PUT 370
Summary 372

Chapter 13: Making a Mobile Site Using Jquery Mobile
WHAT DO you find in this CHAPTER? 373
Introduction 374
Setup 374
Viewports, Widgets and Attributes 377
Themes and Swatches 386
Media Query 387
Layouts and Pages 389
Collapsibles 400
Grids and Buttons 406
Forms 410
Summary 411

Chapter 14: ASP.NET MVC 5
WHAT DO you find in this CHAPTER? 412
Introduction 413
Scaffolding 413
ASP.Net Identity 421
One ASP.Net 421
Bootstrap 427
Attribute Routing 432
Filter Overrides 435
Summary 438

Chapter 15: ASP.NET MVC 6
WHAT DO you find in this CHAPTER 439
Introduction 440
Features 440
Prerequisites 442
Setting up VM 442
Getting Started with Visual Studio 14 447
Creating your 1st Visual Studio 14 MVC Project 449
Configurations in MVC Project 451
project.json 452
Startup class 459
Adding a Class Library Project 462
Deployment to Azure 468
Bin 476
Self Hosting 477
Summary 483

Index 485

Hands-on with ASP.NET MVC book give you a fine Launchpad to get started on MVC. I have written the book in such a fashion that you will solve one case study while studying the book. By the time you will finish the book, you would have completed web version and mobile version of development using MVC. Now, one important point to understand here that ASP.NET MVC is a major shift for all Microsoft developers. ASP.NET MVC emphasizes clean architecture, design patterns and testability. At every part of the book you will get practical example of all the theoretical concepts with complete demo.

ASP.NET MVC is basically a web development framework from Microsoft which combines the features of MVC (Model-View-Controller) architecture. Now, ASP.NET MVC is not something which is built from the ground zero. It built on the top of ASP.NET, so developers enjoy almost all the ASP.NET features while building the MVC application. ASP.NET MVC is an alternative approach to an existing Web Forms approach. This book is basically comprised of 15 chapters covering all the parts of MVC development. 1st chapter starts with the introduction of ASP.NET MVC where in you will see how MVC gained maturity in different releases. 1st chapter will also showcase that what you are going to build by giving the application glimpse in its finished form. Then, you will start creating your MVC project right from the scratch.

In 2nd Chapter you will get the complete idea of controllers. Here, after understanding the basics of controllers, you will be writing your 1st controller. 2nd chapter also covers different types of action results, filters and many more things. 3rd chapter will have view introduction with syntactic sugar. This section also explains some of the core concepts of data – (dash) attributes that how views behind the scenes emit these tags. Apart from HTML helpers, you will also work with different types of view in it. Chapter 4 and 5 will be all about data modeling. In this chapter you will come to know how to get started with entity framework, also how to setup the entities and migrations. Here you will also see different types of validations in action.

Chapter 6 is all about Client side scripts. Its main focus would be on how to manage scripts, how to work with Ajax helpers and how to write an Async Search. Chapter 7 is covering all the security related features like Membership, Authentication, Roles, Open Authentication and many more things. Now, chapter 8 is all about infrastructure topic like Caching and different Diagnostics techniques. This topic stresses how to improve the Application performance by implementing caching. 9th chapter is all about testing. It start with unit testing where in you can test your application logic, then web testing and load testing where in you can test your website performance in different test scenarios. Then we have 10th chapter which is all about deployment. In this case you will 1st deploy the application to IIS, then on internet on AZURE.

Chapter 11 is all about routing concepts. This chapter deals with different routing rules. Then, chapter 12
comprise of Web API and Dependency Injection. Both of these topics are really important and interesting as well. You will learn how to implement both with a complete application demo. In chapter 13, you will be optimizing your application in such a way that it will support mobile browsers as well. Then, Chapter 14 is dedicated to the new features of ASP.NET MVC 5 with complete demo. Last but not the least which is the bonus part of this book MVC 6; here, in chapter 15 you will start from the features discussion, then prerequisites required for MVC 6. MVC 6 is a major breakthrough from Microsoft side towards being Open Source Compliant. So, stay tuned for a stunning journey.

This book would not have been possible without the patient and loving support of my wife Nivi, who had to take over much of the household responsibility apart from her teaching activities, so I could whisper to myself in the corner and do my activities with my laptop. Many thanks also go to my publisher, Rohan Vij, who took this responsibility, to publish the book in a precise and correct way. Appreciation also goes out to my Mom and Dad for believing in me and always keeps on encouraging me to complete the book in a best possible way. Also, I need to acknowledge you, the reader, for your desire to continue your own growth not only as developer but a smart
developer. Obviously, your efforts to improve your skills make me all work to improve myself to keep up the good work. Kudos to you, and keep setting the pace at your workplace!

I would also like to Thank Sanjay for writing the FOREWORD for me. He took his time from his day to day busy schedule, read the complete book; gave his suggestions for improvement and finally after implementing his suggestions he wrote foreword for me.


Hand-on with ASP.Net MVC is designed to teach ASP.NET MVC, from grass root level to advanced topics. I have written the book in such a way that even if you are new to ASP.Net background, you won’t feel difficulty in understanding the concepts. I also understand that many of our readers are familiar with ASP.NET Web Forms, so one important point to understand here that ASP.Net MVC is not a replacement to Web Forms at all. Now, onwards there will be one more design technique to build websites. I have worked hard to make sure that this book is valuable for developers who are experienced with ASP.NET MVC, or even freshers coming out of college. This book is also very well suited to 3rd year and Final year student as this will help them greatly while building their projects.

Also, since ASP.NET MVC is one of the hottest trends across industry, so from the point of interview
preparation as well, it will be a good reference book. Now, apart from MVC you will also learn how to convert the same app to support mobile browsers, also how to host the app on Azure (Microsoft’s Cloud Version).

Today I am really thrilled to introduce this book covering the latest release of ASP.NET MVC, written by one my friend Rahul Sahay. Rahul was developer when I interacted with him for the first time. He is tech extrovert and
interacting with wide variety of technology to gain knowledge, guideline and feedback. His interactions with the diverse ASP.NET community give him some great insights on how developers can begin, learn, and master ASP.NET MVC. He is helping number of blog followers on various topics which is known to him and generated a lot of fans and followers with his technical skills. With a background rooted in community and open source, I count him not only as an amazing technologist but also a close friend. There are number of frameworks available in market but ASP.NET MVC 6 brings you a new ASP.NET Web API (a new framework for building HTTP services), updated default project templates that leverage modern web standards, solid mobile web application support, enhanced support for asynchronous methods, and more with easy integration with other microsoft technology. Currently, MVC 6 is in beta version, which will be officially releasing next year. But, Rahul took this opportunity to include MVC 6 as well in this book. Before touching MVC 6, he has also covered MVC 5 and 4 with complete detail with live demo.
Rahul also developed number of tutorials to help developer understand concepts and also planning to upload a number of videos in line with it. One can always refer his articles on his blog (

Sanjay Kumar Sinha
BTech- IIT
Solution Architect


Finally, this book is mostly based on my opinions. I made every possible effort to ensure that there are no errors in the text or in the code. However, no one is perfect, and mistakes do occur. I’ve spent a lot of time researching the topics in this book and I implement from real world experience as much as possible. With that words, if you find something you believe is absolutely wrong—or even something you strongly disagree with—let me know

Chapter 1: Getting Started

WHAT DO you find in this CHAPTER?

Understanding ASP.NET MVC
The MVC Pattern
Brief History of MVC Pattern
MVC Life Cycle
Software Requirements
Application Glimpse
Creating a MVC application
How MVC applications are structured

Hi Friends, My name is Rahul Sahay, your instructor for ASP.NET MVC. In this section I’ll walk you through the overview of MVC. I’ll also give a brief snapshot of the History of MVC when it’s first introduced and then start the development process. I assume that most of the readers who are reading this book are from the ASP.NET background. However, even readers who are new to ASP.NET architecture don’t need to bother at all as I start right from the grass root level. So, let’s get started.

Understanding ASP.Net MVC:-
ASP.NET MVC framework basically designed to build the web applications which take the general legacy approach Model View Controller Pattern. This pattern existed in tech space since decades; this is not something which is being built by Microsoft from ground Zero. However, Microsoft has introduced its very own MVC framework called as ASP.NET MVC Framework. Also, it’s equally important to understand that Microsoft hasn’t written this MVC Framework right from the scratch, rather it’s been built on the TOP of ASP.NET which means, ASP.NET MVC still has almost all features of ASP.NET like Master Pages, Session Management, Caching, Different types of Authentication and many more thing.

Also, one more important thing to understand here that ASP.NET MVC is not the replacement of ASP.NET Web Forms. Microsoft has provided MVC as an alternative approach to build the web application. So, going forward, now there will be two different approaches to build the web application. However, ASP.NET MVC basically follows the same core principle what other languages follow, plus it has got ASP.NET advantage, like it has got the support of Managed Execution Environment, it uses .Net feature like Extension Methods, DLR features and many more. Some of the common features of MVC which I would like to list out are:-

Stateless: – MVC Framework follows the stateless pattern which means there will be no illusion of state at all. Also, there will be no Page Life Cycle, no Server Side Controls and no View State also. So, instead of using any server side controls like Grid Controls or Menu Controls, we will be writing and crafting the HTML completely from scratch. So, this way we’ll be having complete control on our HTML.

No Page Extensions: – This is also one of the best things which MVC says, so there will be no page extension like .aspx. So, here URL comes is pretty handy and easy to use and easy to remember for readers and also for the search engines. Basically, it is said that pages which are coming without any page extension are ranked higher in the search engine.

Extensible: – This is also one of the common goals for MVC to be completely extensible throughout all the aspects. So, like when we talk about views, one may use aspx view engine to write the view or use the razor to do the same or user can download any other view engine and use the same with the project as well. But, in this case we’ll stick to Razor view engine.
Testability: – Testability is the one of the most important factor of using MVC. It’s basically quite simple, it maintains complete separation of concerns, and hence it’s easy to write and test for each module explicitly. So, here we can easily write test cases for each module explicitly.

The MVC Pattern:-


Having said to my earlier statement that ASP.NET MVC design pattern is not new, this is the technique which is being used since decades across many different technologies like C++, Java, etc. and now in C# as a design pattern for building web applications. It’s powerful and stylish design pattern mean for separation of concerns which means within the application itself we’ll be having separate Data Logic and UI Logic. Neither of these are dependent on each other. Hence, each of these can be tested separately by writing unit test cases. Below is the brief snapshot of MVC and its responsibilities.

Model: – Models are basically a collection of classes where in you will be working with data logic as well as business logic. So, basically models are containers which are business domain specific or I would say section which is used to interact with database and also used to manipulate the data to implement the business logic. So, with ASP.NET MVC this is pretty much easy to use data access layer with Entity Framework, ADO.Net or NHibernate combined with custom code.

View: – Views are nothing but a pure HTML which decides how the UI (User Interface) is going to look like. All I can say is that views are basically templates which decide the look and feel or presentation of your app. This is the section which is going to present the static HTML with extracted data from database @ the desired place.
Controller: – Controllers are basically a bunch of classes which handles communication from the user. This is the one which is responsible for taking incoming HTTP Request and transferring the control to the appropriate section of the application. So, this is the special class which wires up the relationship between view and model. So, it responds to the user input, interacts with the model and decides which view to render. Basically, Controller classes maintain one convention that it has to be suffixed with the name “controller”.
Brief History of MVC Pattern:-
ASP.NET MVC Pattern is the idea which is being developed by Scott Guthrie in 2007. He is the key architect of this design pattern. As far as my knowledge goes, I always designate Scott Gu, as the father of .NET. He is the main person who originated the idea of .NET. Since, then Microsoft or Scott’s team has added tons of feature in .NET development, which makes developer feel comfortable writing any kind of project using .NET.

ASP.NET MVC 1 Features:-
Here, in this section apart from separation of concerns, Unit tests were added. So, while writing any project, you could write unit test for specific modules side by side. MVC 1st was released on 13th March 2009.

ASP.NET MVC 2 Features:-
ASP.NET MVC 2 was released just in a span of 1 year. This has got some really cool features which make MVC more robust and powerful. This version was released on March 2010. Some of the features of MVC 2 have been listed below:-

• UI Helpers with Scaffolding templates.
• Model validation on Client and Server side.
• Strongly typed HTML Helpers.
• Enhanced Visual Studio tooling.

ASP.NET MVC 3 Features:-
ASP.NET MVC 3 was officially released in 2011. MVC 3 has come with major improvements in many sections. Some of the MVC 3 features are listed below:-

• Inclusion of Razor View engine.
• .Net 4 Data annotations.
• Robust model binding and validation.
• Inclusion of Global Action Filters.
• Nice JS, JQuery support. Also, included Unobtrusive JavaScript validation.
• JSON Binding
• NuGet Integration to resolve the software dependencies on the fly.

Don’t worry I’ll do detailing each of the topic in coming chapters; here I just want to make things clean and simple.

ASP.NET MVC 4 Features:-
ASP.NET MVC 4 has done value addition on MVC 3. On the other hand it has become a complete web development package as a whole which offers developer complete suites of development stack. Some of the common features are listed below:-

• Improved Project Templates. Added new Ones
• Inclusion of Mobile Projects using JQuery Mobile.
• Various Display Modes
• Asynchronous Controllers
• Bundling and Minification

ASP.NET MVC 5 Features:-
Again ASP.NET MVC 5 has done many value additions to MVC 4. But, all of these changes are around its scaffolding templates, authentication technique, Bootstrap and many more. Some of the common features are listed below.

• Scaffolding
• ASP.Net Identity
• One ASP.Net
• Bootstrap
• Attribute Routing
• Filter Overrides

You will learn complete features with demo in chapter 14.

ASP.NET MVC 6 Features:-
ASP.NET MVC 6 in many terms is a unique framework as it’s a major change in MVC. All these features will be discussed in the last chapter in detail, where we’ll see the glimpse of MVC 6. Below, I have listed some of the common features of MVC 6.

• Common Framework for MVC, Web API and Web Pages
• Smooth Transiting from Web Pages to MVC
• Built DI First
• Runs on IIS or Self Host
• Based on the new Request Pipeline in ASP.NET vNext
• Runs Cloud Optimized
• No Build Dependency
• Enhanced developer experience
• Open Source
• Cross-Platform Support

Apart from above listed features there are other things also involved which are explained with complete demo in Chapter 15.

MVC Life Cycle:-
MVC Life Cycle in a nutshell will give you glimpse of overall architecture. Here, in the below diagram you will come to know How MVC application behaves when it’s invoked from the browser. So, as you see in the diagram, as soon as request comes from the browser, it is picked up by the routing engine. Hence, ASP.NET Routing is the first step in MVC Life cycle. Basically it is a pattern matching system which matches the request’s pattern against the registered patterns in the Route Table. When a matching pattern found in the Route Table, the Routing engine forwards the request to the corresponding IRouteHandler for that request. If the routing engine doesn’t match the pattern then it returns 404 HTTP Status code.
Then, MVC handler implements IHttpHandler interface and further process the request by using ProcessRequest method. Then in third step MVCHandler uses the IControllerFactory instance and tries to get a IController instance. If successful, then Execute method is called. Now, once the controller has been instantiated, Controller’s ActionInvoker checks which action to invoke on the controller. Next, the action method receives user input, prepares the appropriate response data, and then executes the result by returning a result type. The result type can be ViewResult, RedirectToRouteResult, RedirectResult, ContentResult, JSONResult, FileResult, and EmptyResult. Now, the next step is the execution of the View Result which involves the selection of the appropriate View Engine to render the View Result. It is basically handled by IViewEngine interface of the view engine. Now, at last Action method returns a string, binary file or a JSON Formatted data. The most important Action Result is the ViewResult, which renders and returns an HTML page to the browser by using the current view engine.


Software Requirements:-
MVC 4 runs comfortably on any of the following windows Operating Systems.

• Windows 8
• Windows 7
• Windows Vista
• Windows XP
• Windows Server 2008 R2
• Windows Server 2008
• Windows Server 2003

MVC 4 tooling comes by default with Visual Studio 2012/13. This can also be installed on Visual Studio 2010 as well. However, if you are not having the professional version of Visual Studio, you can use free version of visual studio, Visual Web Developer Express from the Microsoft Site itself. If you’re using Visual Studio 2010, you can install MVC 4 using the Web Platform Installer

Application Glimpse:-
Now, before jumping to create our 1st MVC application, let me give you demo that what we are going to create here. So, below is the snapshot of “MovieReview” site in its finished form. If you look at the URL, you will notice that I have already deployed the same on Azure (Microsoft’s Cloud).


So, here we are at the home page listing couple of movies. It has got features like Paging, Async Search, Bootstrap Features and many more UI related stuffs which you will be exploring in the coming chapters.


Now, the above page is quite descriptive. So, when you click the Edit link corresponding to the movie, it will emit text in editable mode as shown below.


So, when you click on “Back to List”, it will take you to the Movies List back and from there if you click the “Details” link, it will give the movie details as shown ahead.


Now, from here also you can edit the record. Now, back from Movies List if you click on “Reviews” link, it will take you the below page.


So, from here you can obviously create a new review as well as shown in the screen shot.


Now, as you can see in the above screen shot as soon as user tried to enter a rating 6 which is greater than 5, it threw an error. So, at this point of time, you cannot submit this review. You need to fix this 1st and then submit as shown below.


So, as you can see in the above screen shot, as soon as I corrected the error, error description wiped out automatically. Now, I can go ahead and submit the record.


Now, if you click “Delete” option back from the list, then you will land up in the below shown delete page.


So, from here, you can go ahead and delete the page. Now, if you come back on the Movies List, you will notice that there is no option for creating the movie.


Well, for that I have made couple of changes like you should be authenticated 1st and authenticated as an admin, then only you will be able to see the Create Link. So, let me go ahead and login using my credentials.


Then, it will show me the below Create Link.


So, with that Create link, only admin users can go ahead and create the movies. So, this way I have restricted this action for anonymous users. Now, one more thing which I would like to show you is glimpse of my logging technique. I am a big fan of ELMAH Web UI which you learn in detail in coming chapters. But, for now just look at the glimpse of that. So, when you navigate, then it will produce you the application snapshot as shown ahead.


Currently, my application is running fine; hence it didn’t produce any error log. Like this there are many more features which you can delve while building the application right from the scratch. So, stay tuned and get ready to build your 1st MVC application end to end.

Also, after creating the web application, I have converted the same app to support mobile browsers as well. So, now, if you open the same site in your mobile phone, it will get stacked as per your mobile resolution. So, the application has become smart enough to figure out that it is getting invoked from which device. Now, below are screen shots of this sample application.



So, as you can see it has got different mobile user interface, and menu styling is also different. Also, the browser here I am using to test the same is opera mobile browser for desktop. Other features like collapsible panes as shown ahead fits very nicely with mobile devices.


On similar lines you can see other pages like movie and movie reviews as shown ahead.

19th 20th 21th

So, this was the application glimpse in a nutshell. So, during this entire course you will be learning how to build an End to End Application which will not only support desktop version browsers rather mobile as well.
Creating a MVC Application:-
I always believe to learn anything is to get started with the hands-on the same, so that way you will understand the practical approach of solving any problem statement. However, we’ll be building a simple web app for “Movie Review” where in I’ll walk you through all the tiny steps involved in building the site. So, let’s get started. Before we begin, we must install the prerequisites for making this app. Now, to create a MVC Application, open the Visual Studio, click on New Project and select the below mentioned project as shown in the snapshot.


Note: – Here am using Visual Studio 2013 Ultimate Version.

Now, as soon as you select the MVC 4 web application, it will present couple of different application templates option as shown ahead in the screen shot.


Empty Template: – Empty template will just have the basic folder structure that’s it and nothing more than that.
Basic Template: – The basic template will give you the MVC infrastructure in the solution. However, basic templates are for experienced MVC guys who want to customize the solution their way.
Internet Application: – Internet Application is the one which I am interested in as you can see in the above screen shot. However, it will give all the required dependencies in my solution structure to get started with my web application.
Intranet Application: – Intranet application is the one which deals with Windows Authentication. So, once you select this option, you app gets automatically configured with windows related settings.
Mobile Application: – Mobile application is the one which is included with MVC 4. The mobile application is preconfigured with JQuery Mobile. It helps developer to create just mobile sites. It includes themes which is supported by mobiles, touch enabled UI etc.
Web API: – Web API terminology will be discussed in detail later in this book. However, for now you just need to know that Web API is basically a framework which supports creating HTTP services.
Single Page Application: – SPA is a new terminology which offers building Single Page Application, focused mainly on client side interactions using tons of JavaScript and different JS Frameworks like Knockout, Durandal, Angular etc. This kind of web application is highly interactive and feature rich for ex: – Gmail, Outlook etc.
Facebook Application: – Facebook application is I would say a kind of API support which offers developer to use the Facebook API in their application to build a Facebook centric website. This is really a cool stuff.
Now, the next option which I have selected above is razor as view engine, so if I click on this dropdown I could see two options available as Razor and ASPX.


I also have a habit of checking Unit Test Project as you can see below in the screen shot. So, upon checking this checkbox, Visual Studio will create one more project for me in the solution which is going to be Test project. Here, I can go ahead and write my test cases against any specific module or scenarios.


So, when you click on the dropdown of Test framework, you will see only one test framework in there. However, Microsoft has given an option to developers to install their friendly testing framework like NUnit, XUnit, etc. So, once these frameworks will get installed, this will get added in the dropdown box.

How MVC Applications are Structured:-

Below is the snapshot of the MVC application structure. This gives a brief idea that how your simple MVC app is structured initially.


Below I have listed specific directories which are there in the solution and their meaning.
Models: – Section containing all the classes related to fetching the data and manipulating the same.
Views: – Section containing all the UI related stuffs. These are the ones which are going to be rendered based on controller’s action.

Controllers: – Section where in the entire controller classes are placed which basically handles all the incoming requests from the browser.
Scripts: – Section where in all the scripts related stuffs are placed.
Images: – Section where in all the images are placed which is used across your site.
Filters: – Section where in all the filters are placed. We’ll do deep dive usage of filters later in coming chapters.
App Data: – Section where in all the data files are stored meant for reading and writing the same.
App Start: – Section where in all configurable stuffs resides like Web API, Routing etc.

Note: – This is basic internet app MVC structure. However, please note that MVC Framework never enforces any kind of folders organization. You can obviously customize the folders your way, like in many enterprise projects Models go in a separate class library project just to make sure reusability. However, you could do higher level of separation, it entirely depend on you.

So, in this chapter we have just seen the overview of MVC, history of MVC and its different releases. We also understood that ASP.NET MVC is another technique of building web application, a completely different strategy rather stateless technique to build the web app. We have also seen the application glimpse which we are going to build right from the scratch and host the same on cloud. As we progresses module by module in different chapters your doubts regarding MVC development will be getting clearer.

Getting Started with WCF – Part 2

Hi Guys,

So, in today’s discussion, will move next step by writing a simple WCF program. So, let’s get started. Below in the screenshot, you can see I am in Visual Studio instance 2013.


Then,i’ll click on new project and select WCF tab and from there i will select WCF Service Library.


Now, this will create one simple class library solution as shown below in the screen shot.


Now, let’s understand what visual studio has given us by default. so, basically it gave me basic implementation of WCF service to get started. But, i don’t want these stuffs; rather i am quite interested in getting started right from the scratch. so, i’ll go ahead and delete these two files. Now, let’s look at the references which visual studio gave me with this template.


Now, these two namespaces are the basic things which required for building any WCF Service. Now, it also gave me app.config file which is pretty much required for all types of WCF configurations. Now, i’m going to write new class to it


Now, i am going to modify this, i’ll add one more class here itself and then annotate the same with [DataContract] as shown below so that this class will get exposed for WCF. Now, for each field within the class also needs to be annotated with [DataMember] as shown below in the screen shot.


Now, i am going to create one interface which will have one operation which will basically return one string with values which we have in the class. Also, if you have noticed that this service contract has taken Employee as an object. Now, in order to expose this as a service contract, i also need to annotate the same with [ServiceContract] attribute and the other attribute which i need to apply on the method is the [OperationContract] as shown below in the screen shot.


Also, one point to note here that [ServiceContract] is available under the namespace “System.ServiceModel”.

Now, to implement this WCF service contract, I will come to my base class and simply derive it from here as shown below in the screen shot.


So, above is my WCF Implementation. Notice that for WCF Implementation, I don’t need any kind of annotation. Now, we are good to host our service either in IIS, or we can write our own custom hosting mechanism also known as self hosting or we can test the same with WCF Test client. For now, i’ll be using WCF Test client. But, in either case, we need to update our App.Config with correct endpoints so that TestClient will come to know which service you are interested in hosting.

Now, i have completely modified the App.Config with my requirements. So, basically i have set configured three endpoints in it with service contract which i have written during implementation. i have also configured the base address of my service. Now, below is the modified app.config file.


Now, with the above changes in place, we are ready to host the service on WCF Test Client. Now, all i need is to save this file and press F5. Now, when i press F5, it will launch the below shown window which is basically a confirmation that your service has started.


Now, as you see in the screen shot, there are three endpoints hosting the same contract but different ways. So, now if click on any of these methods of any endpoint it will present me the same result. For example, I click on PrintEmployee() of BasicHttpBinding and it will present me the below UI.


Now here i can go ahead and mention the values in those text box and then click on invoke button, then it will return me expected result in string format.


With this i would like to wrap this session here. In the next section, will do more deep dive and see other important things related with WCF. Till then stay tuned and Happy Coding.


Getting Started with WCF

Hi Friends,

In Today’s discussion, we’ll be discussing more about WCF and its features. So, before delving in WCF directly. Let’s look at the basics like how WCF came into picture. WCF is all about connected systems. Basically, a connected system is the one which is distributed across multiple machine nodes. you can see the glimpse of connected system in below diagram.


Now, if you see closely, you will notice that these machines communicate with each other via some medium. Currently, i just labeled it with communication. It means, different machines will pass information to and fro via some protocol. So, this is the connected system in a nutshell. Now, let’s see how can we build connected systems on Windows. Years before, we used to have “DCOM/COM+/ES“, a component oriented architecture. So, here we used to take our COM components and deploy them on the network and then invoke them remotely. One of the key features of this was Distributed Transactions, where basically logical transactions are handled by multiple COM components spanned throughout the network. Now, the disadvantage of this feature was, it did require to have DCOM Infrastructure installed on each and every machine.

Now, at the next level with the release of .NET, they also released a distributed object technology known as .Net Remoting. It was also very similar to COM based architecture but only difference is that it runs under the Managed Execution environment of CLR. As a result, .Net Remoting became very simple, extensible but still in this case as well it depends on .Net CLR.

And then MSMQ came into picture. It’s very different from other two frameworks. MSMQ is completely based on messaging. It allows you take a message and transmit it between two machines in a connected system in a asynchronous durable and reliable fashion. It has nothing to do with components. But, it still requires MSMQ infrastructure installed on each and every participating machine.

so, here in the above case, each infrastructure comes with it’s own programming style which means developers need to learn different styles of coding before they jump start execution. Also, there is one more disadvantage of this system as each of these restricts its execution to Windows environment only.

So, now in today’s era interoperability is the key demand across all the companies. For example, consider the below example, companies need to have environment where in they can seamlessly do transactions.


so, here in the above diagram, this connection is via services. A service is the simple unit of functionality which you can expose to any ecosystem via messaging. So, we can implement services on each of these nodes and then expose the functionality via messaging. Now, the way we achieve interoperability via standard protocols like HTTP and message formats like XML. So, this way we can easily achieve more loosely coupled architecture.

Now, Let’s discuss a design strategy a bit.


So, as you can see in the above diagram, the 1st one is the SOAP which also incorporates various WS-* specifications. Now, this style has been used for several years and still working nicely. This design is very popular across enterprise level where in projects are basically Intranet based. Another design strategy which is gaining traction these days is REST(Representational State Transfer). This design approach is very popular at internet space.

Now, let’s discuss the same in detail. Below is the basic diagram of SOAP based architecture.


As you can see in the diagram that SOAP and WS-* based specifications build on a full fledged stack of different technology suites. So, the 1st thing is Transport Neutrality which is the foundation of this approach. Now, in-order to accomplish the same we need to make use of XML based messaging layer. Now, this is the place where in SOAP comes into picture. SOAP is basically XML for bundling the messages which we need to transmit across our services. Then comes various WS-* based specifications like Security, Reliable Messaging(RM), Transactions etc. Now, if you are using any of these advanced features, we also need to provide Metadata to our clients

Now, on the other hand Restful service is completely different from SOAP based. In fact, they don’t try to achieve Transport Neutrality as they support only HTTP protocol. So, basically with REST services are modeled as resources with Unique identifiers also known as URIs. Now, in order to interact with these resources we need to have a uniform interface which is commonly known as “GET,POST,PUT,DELETE….”. Now, in order to represent these resources, we need to have concrete format like XML, JSON, RSS, ….

Now, let’s look at the below picture. It basically shows Microsoft Services in a nutshell.


So, as you can see that the 1st one is ASP.NET Webservices also known as ASMX. So, basically it provided support for SOAP 1.1 and 1.2. Just after this, they came with Web Service Enhancements also known as WSE. This is basically meant for supporting WS-* protocols. It means it actually added, Security, Secure Conversation etc. Now, one can use WSE standalone or in conjunction with ASMX to add some of these behaviors to ASMX services. But, again this approach was also quite limited in terms of Transport neutrality.

Later on, Microsoft realized, they need to work on one framework which will complement Uniform programming model for building any kind of service oriented architecture. Hence, they tried to incorporate below listed dependencies under the same hood.


So, in a nutshell above diagram shows that it has got every required things under one programming model and hence, It turned out to be the birth of WCF.

So, in today’s discussion, we have just discussed birth of WCF by focusing on the evolution of connected systems and services. In the next section, we’ll start with WCF programming from the scratch. Till then stay tuned and Happy Coding.

Happy Coding