Thursday, September 25, 2014

Use ModelState Property within the View of ASP.NET MVC 4

Hi Folks,



Some time you may encounter a situation to verify your Model is valid or not .

If you want to access the ModelState property in the View , you can use the ModelState in your Razor View as depicted below in image:

Generally this property used to identify that model is valid or not.


This is the source code as shown below: 

  1: @model IEnumerable<MVCSample.Models.EmpRegistration>  
  2: @{  
  3:     ViewBag.Title = "Verify";  
  5: if (@ViewContext.ViewData.ModelState.IsValid)  
  6:     {  
  7:         ViewBag.Title = "Verify";  
  9: if (TempData["EmployeeRegistration"] != null)  
 10:         {  
 11:             var tempDataEmployeeRegistration = TempData["EmployeeRegistration"];  
 12:         }  
 13:     }  
 14: }  

To learn more about MVC please go to the following link.

MVC Articles

Enjoy coding and reading.

Wednesday, September 24, 2014

Facts about Extension Methods in C# with Practices

Facts about Extension Methods in C# with Practices


In this article I am going to demonstrate some facts about Extension Methods in C# keyword of LINQ. This keyword is very helpful when working with extension of existing type like already created classes.
Extension methods enable you to add methods to existing types without creating a new derived type or sub-class.
Facts: Though we generally used to have some helper class to extend the functionality as well as have an option to create a subclass of existing class to add new functionality.
However you may confront with one of following issue as shown below:
clip_image002If the class is sealed than there in no concept of extending its functionality. To tackle with such concern we have concept of extension methods.

  2: public sealed class MathOps
  3:     {
  4:         public int Add(int x, int y)
  5:         {
  6:             return x + y;
  7:         }
  8:     }
 10: public static class StringHelper
 11:     {
 12:        public static int Add_Ex(this MathOps onjmaths, int x, int y)
 13:        {
 14:            return x + y+2;
 15:        }
 16:     }


Number2Extension methods allow existing classes to be extended without relying on inheritance or having to change the class's source code.
Points for the Remember about extension methods
· An extension method must be defined in a top-level static class

  1:  public static class StringHelper
  2:     {
  3:         public static int Add_Ex(this MathOps onjmaths, int x, int y)
  4:         {
  5:             return x + y + 2;
  6:         }
  7:     }

  • · An extension method contains “this” keyword, which has to be the first parameter in the extension method parameter list.



  • · An extension method with the same name and signature as an instance method will not be called.



  • Extension methods can't access the private/protected methods in the extended type; it prompts you an error related to protection level.


  • The concept of extension methods cannot be applied to fields, properties or events.

These all are some finding which I have shared with you.
I wish it will help you utilize both feature at best.
To learn more about MVC please go to the following link.
MVC Articles
Enjoy Coding and Readingclip_image015

Tuesday, September 23, 2014

Differences between Interfaces and Abstract classes Which we use ?


An abstract class is "which is lack of implementations”. Means it doesn't keep it complete implementations.

And if you want to perform some "protocols (some method to be execute)" at application level than we should follow an interface.

1. A class may implement several interfaces but can only extend one abstract class.
An interface cannot provide any code, just the signature. An abstract class can provide complete, just the details that have to be overridden.

2. If various implementations only share method signatures then it is better to use Interfaces.
If various implementations are of the same kind and use common behavior or status then abstract class is better to use.

3. An interface cannot have access modifiers for the subs, functions, properties etc. everything is assumed as public
An abstract class can contain access modifiers for the subs, functions, properties

4. Abstract Class may contain constructor but interface does not contain constructor.

5. If we add a new method to an Interface then we have to track down all the implementations of an interface and define implementation for the new method.
Though if we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly. (e.g.)
We can either add concrete method or abstract method.

6. Very effective example of both like below:

Suppose we have an interface that has method like "Android" which is applicable for all mobile devices like Samsung, Micromax, Karbonn.which makes satisfactory for this Line "If various implementations only share method signatures then it are better to use Interfaces"

While if you have method named as "Galaxy" than would be applicable only for Samsung abstract class. Which makes satisfactory for line? “If various implementations are of the same kind and use common behavior or status then abstract class is better to use".

To learn more about MVC please go to the following link.

MVC Articles

Enjoy coding and Smiling.

Sunday, September 21, 2014

Extension Helpers Method in MVC

Extension Helpers Method in MVC


There are many ways to create your own helpers using Razor syntax. I am using one of them. The Helper Method is an optimum way to do it.
So let's start and create a Helper Method.

First we'll start with Extension Method syntax. I have created a sample application and it has HtmlHelpers.cs in the HtmlHelpers folder.


Open the HtmlHelpers.cs file and you will find the following code snippet, which is an Extension Method that takes two parameters and removes a string using the substring method.


So far we have declared an Extension Method, now to use it in our View page (.cshtml). I'll use it in the Verify.cshtml page. Here is the code snippet of that page.



As you can see we are using the RemoveString() Helper Method in the Verify.cshtml page, that caters the raw string (raw string as declared in the ViewBag.Message property) using two parameters being passed.
Now let's run this and see the execution:



Notice that it took the complete string that we've passed, like @Html.RemoveString(ViewBag.Message as string, 20) and performs the code down the level.

Again Press F5 and see the result.


Notice that it only gives you "Welcome to C#Corner" out of the complete string.
So this is how to create a Helper Method on demand in Razor view Engine. The sample application is attached as a reference.
Stay Happy Stay Coding.

You can download source code from here : Extension Helpers Method in MVC

To learn more about MVC please go to the following link.

MVC Articles
Enjoy coding and reading.

Thursday, September 18, 2014

Faults Vs. Exceptions


Faults Vs. Exceptions

The main thing in faults and exceptions is that "faults and exceptions are not the same thing".


An exception is a .Net mechanism. It is used when the program encounters an error. The .Net language allows us to throw, catch and ignore the exception. At some point
they should be handled or the .Net runtime will terminate the thread in which the exception was thrown.


Faults refer to the SOAP fault mechanism to transfer error information from a service to a client. WCF provides the FaultException class. Whenever a service throws a Fault Exception, WCF serializes the information sent to the client.

Warm Regards

To learn more about MVC please go to the following link.

MVC Articles


Enjoy Coding and Readingclip_image015

Wednesday, September 10, 2014

Custom Value Providers in ASP.Net MVC

This article describes Custom Value Providers in MVC and their uses. Value Providers are the components that feed data to model binders. Feeding the data means installing the data to the Model binder for further use at the action level.
The framework contains a few built-in value providers named FormValueProvider, RouteDataValueProvider, QueryStringValueProvider and HttpFileCollectionValueProvider that fetch data from Request.Form, Request.QueryString, Request.Files and RouteData.Values.

These Value Providers are called in the order they are registered and so the one that is registered earlier gets the first chance. We can easily restrict the model from binding with the data from a specific Value Provider.
In this article we will see how to create custom value providers that fetch a value from a cookie and pass model binders at the action level.
Down the level, I have created a controller that has an action declared as an index. When the Index action is called using GET a cookie is added to the browser called "Id" with the value "E001" assigned to it.
When the form is posted [HttpPost] an index action is again called and the cookie value is automatically assigned to the Id parameter on the POST index method. But how?

Each value provider implements an interface IValueProvider that has two methods as shown below in the image:
value provider implements
The ContainsPrefix method is called by the model binder to determine whether the value provider has the data for a given prefix. The GetValue method returns a value for a given data key or returns null if the provider doesn't have any suitable data. Here is an implementation of both methods as shown below in the image:

In the image shown above the ContainsPrefix method checks whether the passed parameter is stored in the cookie (or the value the user has registered in another request/response parameters) and returns true or false. In the GetValue method it returns a value from the cookie collection for the passed key (in our case it's Id).

Now it's time to register the value provider through factories to make them install data to the model binder. We need to create a factory to register our CustomValueProvider by deriving from the abstract class ValueProviderFactory. The factory contains a single method GetValueProvider where we should instantiate our custom value proivder and return it.


Now we need to register CustomValueProviderFactory to the ValueProviderFactories.Factories collection in the Application_Start event of Global.asax.cs as shown in the following image:

Now I press F5 and run the application.
run the application
Let's run the application and discuss the points step-by-step to fetch the value from the CustomValueProvider.
Step 1: As soon as it runs the application it registers a cookie value as depicted in the image below:

cookie value

Step 2:
Fill in the required values and press the ok button, kindly see the following image:

Fill the required values

Step 3: It calls the CustomValueProvideFactory class to instantiate CustomValueProvider as depicted in the image below:


Step 4: At the time of the model binding the DefaultModelBinder checks with the value providers do determine if they can return a value for the parameter Id by calling the ContainsPrefix method. If none of the value providers registered can return then it checks through CustomValueProvider whether such a parameter is stored and if yes it returns the value. Kindly refer to the screen shot given below:

parameter Value

Step 5: A final step is at the post action method when it retrieves a cookie value from CustomValueProvides.

post action method

Important Note: If we change the parameter exists in action method then it doesn't find a value from the registered custom value provider due to a mismatch and it returns null. You can also retrieve multiple values from value providers. Kindly find the attached sample application.

Kindly refer to the image below:

sample application
The Value Providers Magic is Over.

I hope you enjoyed this and that it may help you down the line.

To learn more about MVC please go to the following link.

MVC Articles
Enjoy Coding and ReadingSmile

Implement Joins in Entity Framewok Using DB Context and LINQ

Excerpts from MSDN about LINQ


Language-Integrated Query (LINQ) is a set of features introduced in Visual Studio 2008 that extends powerful query capabilities to the language syntax of C# and Visual Basic. LINQ introduces standard, easily-learned patterns for querying and updating data, and the technology can be extended to support potentially any kind of data store. Visual Studio includes LINQ provider assemblies that enable the use of LINQ with .NET Framework collections, SQL Server databases, ADO.NET Datasets, and XML documents.
In this article I am sharing how to use joins in Entity Framework with a DB context and a LINQ query.
I will use a sample application to demonstrate this feature.
We need to create DB Context object to understand the fact and advantages, so let's create a .edmx and dig into more details. Kindly follow the following procedure to create a DBContext. Create a sample MVC application and follow the procedure below.

1. Right-click on the Model folder and proceed as shown in the following screenshot:


Choose "Visual C#" => "ADO.NET Entity Data Model" then provide the name as you need to (for exampleNorthwind.edmx) as in the following:


Click "Add" then a new window will appear as in the following:


Select "Generate from database" and click "Next"; the following window will appear:


Click on "New Connection" and fill in the required details as shown in the following image to connect with the server (in this for example I have used "local DB Server").


Click on "Test Connection" to verify that the connection has been established.


Click "Ok" and proceed further.


Click "Next", the following window will appear:


Select the required database objects as per your needs and click on the "Finish" button.
An edmx file will be added into the solution as per the image show under the following:


These are the very basic steps to create an entity object from an existing database as shown above. Now let's proceed further and get to the core topic to use Joins with Entity Framework.
Now open the RegisterController class file and write my code in Action "Verify" also as shown in the following image:


You can see the code snippet in the above diagram states that we are using an inner join on two tables, Orders and OrderDetails, and return the result to the view (that is of type OrderModel having the following code snippet).


Now I run the sample application and press F5.


It's very simple in use, we just need to understand how to implement this. Hope it will be helpful somewhere someday. And I will contimue to post a few more articles related to MVC, Entity and many more.

A sample application is attached as a reference here

To learn more about MVC please go to the following link.

MVC Articles

Keep coding and Stay Happy Smile