Monday, August 11, 2014

Validation failed for one or more entities. See EntityValidationErrors property for more details.
Error-Messages
Today I encountered an error during data insertion through Entity Framework as per the Title.
There could be a various cause of such issue .Here I am talking about one of them.In database I restricted Name column data Type to nvarchar(10).
 and I was inserting value which has more than 10 character.
 
image
 
As soon as I try to insert value it generates me an error as depicted below:
 
clip_image002
.
 
I have used the code as shown below to identify the root cause.
  1: public ActionResult Create(EmpRegistration collection)
  2:         {
  3:             try
  4:             {
  5:                
  6:             }
  7:             catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
  8:             {
  9:                 Exception raise = dbEx;
 10:                 foreach (var validationErrors in dbEx.EntityValidationErrors)
 11:                 {
 12:                     foreach (var validationError in validationErrors.ValidationErrors)
 13:                     {
 14:                         string message = string.Format("{0}:{1}",
 15:                             validationErrors.Entry.Entity.ToString(),
 16:                             validationError.ErrorMessage);
 17:                         // raise a new exception nesting
 18:                         // the current instance as InnerException
 19:                         raise = new InvalidOperationException(message, raise);
 20:                     }
 21:                 }
 22:                 throw raise;
 23:             }
 24:         }

This code  help you to trace exact error.The way it suggested to me that “The field Name must be a string or array type with a maximum length of '10'.”



image



This is the complete code which runs perfectly as shown below .I wish this code will help you sometime.


  1: public ActionResult Create(EmpRegistration collection)
  2:         {
  3:             try
  4:             {
  5:                 if (ModelState.IsValid)
  6:                 {
  7:                     EmpRegistration empRegis = new EmpRegistration();
  8:                     // TODO: Add insert logic here
  9:                     empRegis.Address = collection.Address;
 10:                     empRegis.City = collection.City;
 11:                     empRegis.Id = 7;
 12:                     empRegis.Name = collection.Name;
 13:                     objEnity.EmpRegistrations.Add(empRegis);
 14:                     objEnity.SaveChanges();
 15: 
 16:                     return View();
 17:                 }
 18:                 return View(objEnity.EmpRegistrations);
 19:             }
 20:             catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
 21:             {
 22:                 Exception raise = dbEx;
 23:                 foreach (var validationErrors in dbEx.EntityValidationErrors)
 24:                 {
 25:                     foreach (var validationError in validationErrors.ValidationErrors)
 26:                     {
 27:                         string message = string.Format("{0}:{1}",
 28:                             validationErrors.Entry.Entity.ToString(),
 29:                             validationError.ErrorMessage);
 30:                         // raise a new exception nesting
 31:                         // the current instance as InnerException
 32:                         raise = new InvalidOperationException(message, raise);
 33:                     }
 34:                 }
 35:                 throw raise;
 36:             }
 37:         }

To learn more about MVC please go through the following link.
MVC Articles
Enjoy coding and readingSmile

Friday, August 8, 2014

Difference/Similarities BETWEEN HTML.RENDERACTION AND HTML.ACTION

 

image

Html.RenderAction() and Html.Action()  are action helper methods in ASP.NET MVC. Generally both methods are used for calling action methods or child action methods  and rendering the result of action method in view.

@Html.Action() – Invokes the specified child action method and returns the result as an HTML string.

The way to call action via RenderAction is shown below:

  1: e.g. @Html.Action("ChildAction", "Home", new { param = "first" })

 

This method result can be stored in a variable, since it returns string type value.Kindly look at the image shown below:

image

 

@{ Html.RenderAction() – Invokes the specified child action method and renders the result inline in the parent view.

This method is more efficient if the action returns a large amount of HTML.

The way to call action via RenderAction is shown below:

  1: @{Html.RenderAction("ChildAction", "Home",new { param = "first" });}

It returns Voids and render/give result directly to the response .

 

image 


Both methodsis also used for rendering the partial view using Child Action


The difference between the two is that Html.RenderAction will render the result directly to the Response (which is more efficient if the action returns a large amount of HTML) whereas Html.Action returns a string with the result.

This method is faster than Action method since its result is directly written to the HTTP response stream.

Thanks

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

MVC Articles

Enjoy coding and readingSmile

Thursday, August 7, 2014

  • The RouteData must contain an item named "action" with a non-empty string value
Trouble-Shooting
Hi Folks,

Since I am exploring MVC these days I have tried to temper MVC with given functionality and encountered an error. I think we should understand why it comes and what exactly is wrong with our code.
Errors
  • Value cannot be null or empty. Parameter name: controllerName
  • The RouteData must contain an item named "action" with a non-empty string value

First: Value cannot be null or empty. Parameter name: controllerName.
I changed the route map collection of the application slightly and kept the controller value blank as shown in the image below:
Method for Registering Routes

Because on each URL hit, it first goes to the Route collection and finds a controller to invoke an action method. When it doesn't find a controller value, it issues such an error.

Second: The RouteData must contain an item named 'action' with a non-empty string value.
I changed the route map collection property of the application slightly and kept the action value blank as shown in the image below:


RouteData Error
New RegisterRoute Method

Because on each URL hit, it first goes to the Route collection and finds a controller to invoke an action method. When it doesn't find an action method name, it issues such an error.
The solution for both the errors is, please set some real value for both of the parameters to run an application expected.
For example I have given the value ” Home1” as the controller name but it doesn't exist in my application, so you may encounter a page 404 not found error as depicted in the image below:

Update in Register Route
Page Not Found Error


I hope that if you confront such an issue then this article will be helpful.

Note: The scenarios mentioned above are some of the possible causes of such an error.
Thanks. To learn more about MVC please go through the following link.
MVC Articles
Enjoy coding and reading

Wednesday, August 6, 2014

Child Action Methods in ASP.NET MVC4

Child Action Methods in ASP.NET MVC4

 

ChildAction

 

In this article we will explore Child Action method which is accessible at View level. In general each public method in a controller class is an action method.

There could be multiple scenarios when we want to display some dynamic information (data) on pages. Child action is helpful in those scenarios.

ChildAction method is somewhere an action method thought its accessible from View only, if you invoked this action via URL then it prompts you an error which we will look down the level in this article.

I have a HomeController in MVC application which contains a code as given below:

  1: using System;
  2: using System.Collections.Generic;
  3: using System.Linq;
  4: using System.Web;
  5: using System.Web.Mvc;
  6: using FiltersDemo.Controllers.CustomFilters;
  7: 
  8: 
  9: namespace FiltersDemo.Controllers
 10: {
 11:     public class HomeController : Controller
 12:     {
 13:         #region Commented
 14:         //[CustomAuthorization]
 15:         //[CustomAction]
 16:         //[CustomResultAttribute]
 17:         //[CustomExceptionAttribute]
 18:         #endregion Commented
 19: 
 20:         public ActionResult Index()
 21:         {
 22:             
 23:            
 24:             ViewBag.TempValue = "Index Action called at HomeController";
 25:             return View();
 26:         }
 27: 
 28:         [ChildActionOnly]
 29:         public ActionResult ChildAction(string param)
 30:         {
 31:             ViewBag.Message = "Child Action called. "+ param;
 32:             return View();
 33:         }
 34: 
 35:     }
 36: }
 37: 
 38: 


 


To behave an action as child action it requires decorating with [ChildActionOnly] as shown in image below:


 

clip_image002

Initially it is invoking to Index action which in turn returning to Index views, and at View level it calls to ChildAction named as “ChildAction”.

This is the code of index.cshtml as shown below:

  1: @{
  2:     ViewBag.Title = "Index";
  3: }
  4: <h2>
  5: Index</h2>
  6: <!DOCTYPE html>
  7: <html>
  8: <head>
  9:     <title>Error</title>
 10: </head>
 11: <body>
 12:     <ul>
 13:        <li>
 14:             @ViewBag.TempValue
 15:         </li>
 16:         <li>@ViewBag.OnExceptionError</li>
 17:        
 18:         @*<li>@{Html.RenderAction("ChildAction", new { param = "first" });}</li>@**@
 19:         @Html.Action("ChildAction", "Home", new { param= "first" })
 20: 
 21:     </ul>
 22: </body>
 23: </html>
 24: 
And this is how we declare an action in view as depicted in image below:

clip_image004

Now I run application and it will call an action method via Index.cshtml page. And result is as below:

clip_image007clip_image005

Note: if you try to access ChildAction method directly than it prompts you an error as per image depicted below.

Copy this URL and paste it to browser => http://localhost:50255/Home/ChildAction/Second

It prompts you an error:

clip_image009

It may help you sometime in upcoming time.

Thanks

To know more about MVC please go through with given below link.

MVC Articles
Enjoy Coding and Reading clip_image010

Tuesday, August 5, 2014

Error-Messages

 

Hi Folks

I encountered an error during an implementation of ChildActionOnly attribute in a MVC application .This error occurs when you don’t specified an ChildActionOnly attribute on an action of controller.

You can specified an action at View level as shown below :

Index.cshtml

 @Html.Action("ChildAction", "Home", new { param= "first" })




While the code given below placed at action level.


Note: I didn’t decorated the below action with ChildActionOnly.


HomeController:


 


   1:   public ActionResult ChildAction(string param)
   2:          {
   3:              ViewBag.Message = "Child Action called. "+ param;
   4:              return View();
   5:          }




and I decorated an action with  NonAction attribute as shown below:”



   1:   [NonAction]
   2:          public ActionResult ChildAction(string param)
   3:          {
   4:              ViewBag.Message = "Child Action called. "+ param;
   5:              return View();
   6:          }



an error prompts at View level:


 


image


 


To overcome on error shown above ,Kindly decorate action with childActionOnly attribute as depicted below in image:


 


   1:  [ChildActionOnly]
   2:         public ActionResult ChildAction(string param)
   3:         {
   4:             ViewBag.Message = "Child Action called. "+ param;
   5:             return View();
   6:         }
   7:   



 


Note: This is one of cause to this error.


 


To know more about MVC please go through with given below link.

MVC Articles
Enjoy Coding and Reading Smile

S.O.L.I.D Principle Inversion of Control and Resolution With Dependency Injection

The S.O.L.I.D principle of OOP has one very important principle named Inversion of Control. In this article I'm sharing my thoughts of Inversion of Control.
For a few days I've been exploring more about design patterns and OOP principles. Kindly visit the following links for Design Pattern and OOP principles.
S.O.L.I.D Principles:

Design Patterns:

Why is Inversion of Control required?
The problem here is tight coupling in classes. In other words, "class A depends on class B". Let's take an example and try to understand the tight coupling.
Suppose we have a Samsung class that contains an Android class object. An issue with this is tight coupling between classes. In other words the Samsung class depends on the Android object. So if the Android class changes for any reason then it may affect the Samsung class.

  1. The problem is that the Samsung class controls the creation of the Android object.
  2. The Android class is directly referenced in the Samsung class that leads to tight coupling among address and customer objects.
  3. If we make any changes to the Android class then it might affect the Samsung class also, because the Samsung class is dependent on the Android class. Suppose that we add some properties or methods to the Android class then it might require changes in the Samsung class.

In easier words, this is called Object Dependency. Object Dependency means that, for one object  to work, it needs another object. In other words one object is dependent on another object.
Here is the code segment for understanding this:

  1: using System;
  2: using System.Collections.Generic;
  3: using System.Linq;
  4: using System.Text;
  5:  
  6: namespace IOCSample
  7: {
  8:     class Android
  9:     {
 10:         private string strAndriodVersion;
 11:         private int strInternalMemory;
 12:  
 13:         public string propAndriodVersion
 14:         {
 15:             get { return strAndriodVersion; }
 16:             set { strAndriodVersion = value; }
 17:         }
 18:         public int propInternalMemory
 19:         {
 20:             get { return strInternalMemory; }
 21:             set { strInternalMemory = value; }
 22:         }
 23:  
 24:         public Android(string AndriodVersion, int InternalMemory)
 25:         {
 26:             propAndriodVersion = AndriodVersion;
 27:             propInternalMemory = InternalMemory;
 28:         }
 29:     }
  1: class Samsung
  2:     {
  3:         private string MobileName;
  4:         private Android Android;
  5:         //private string AndriodVersion;
  6:         //private int InternalMemory;
  7:  
  8:         public Samsung(string strMobileName, string objAndriodVersion, int objInternalMemory)
  9:         {
 10:             Android objAndroid = new Android(objAndriodVersion,objInternalMemory);
 11:  
 12:            this.MobileName = strMobileName;
 13:            this.Android = objAndroid;
 14:             //this.AndriodVersion = objAndriodVersion;
 15:            // this.InternalMemory = objInternalMemory;
 16:            
 17:         }
 18:  
 19:         public override string ToString()
 20:         {
 21:             return string.Format("Mobile Name: {0} Version :{1} having internal memory:{2}", this.MobileName, this.Android.ToString(), this.Android.ToString());
 22:         }
 23:     }

 

  1: class Program
  2: 
  3:     {
  4: 
  5: static void Main(string[] args)
  6: {
  7: 
  8: Samsung samsung = new Samsung("Galaxy Grand", "Jelly Bean", 16);
  9: Console.WriteLine(samsung.ToString());
 10: Console.ReadLine();
 11: 
 12:         }
 13:     }
 14: }
 15: 

Look at the image given below to understand the concept of tight coupling.
SOLID1.jpg
Dependency Injection
To solve the problem of tight coupling here we have an easier and simpler way, "Inversion of Control" (IOC).
In more simple words Inversion of Control could be defined as: "delegation of a task of object's creation to a third party, to do low coupling between objects and to minimize dependency between objects".
There are two points related to IOC:



  1. The main class shouldn't be dependent on another class. Both classes should be dependent on abstraction.



  2. Abstraction could be done through an interface or abstract class.


This is the basic concept for implementing the Inversion of Control (IOC) pattern.



  • It wipes out tight coupling between objects.



  • Makes objects and application more flexible.



  • It facilitates creating more loosely coupled objects and their dependencies.
    SOLID2.jpg


Kindly have a look at the code below to understand the IOC implementation. I am using Constructor Injection.
Here the object reference would be passed to the constructor of the business class Samsung. In this case, since the Samsung class depends on the Android class, a reference of the Android class will pass steps to implement Constructor Injection. I am using a very basic approach for this.
Step 1

Create an Interface:

interface IMobile

    { }

Step 2

Implement an interface to the Android class. An object of the Android class references the Samsung class. See:

  1: class Android : IMobile
  2:     {
  3:         private string strAndriodVersion;
  4:         private int strInternalMemory;
  5:  
  6:         public string propAndriodVersion
  7:         {
  8:             get { return strAndriodVersion; }
  9:             set { strAndriodVersion = value; }
 10:         }
 11:         public int propInternalMemory
 12:         {
 13:             get { return strInternalMemory; }
 14:             set { strInternalMemory = value; }
 15:         }
 16:  
 17:         public Android(string AndriodVersion, int InternalMemory)
 18:         {
 19:             propAndriodVersion = AndriodVersion;
 20:             propInternalMemory = InternalMemory;
 21:         }
 22:         public override string ToString()
 23:         {
 24:             return string.Format(" Version :{0} is having internal memory:{1}", this.propAndriodVersion, this.propInternalMemory);
 25:         }
 26:     }

Step 3

Make a reference of the interface in the Samsung class:

  1: class Samsung
  2:     {
  3:         private string MobileName;
  4:         private IMobile objIMobile;
  5:  
  6:  
  7:         public Samsung(string strMobileName, IMobile obj)
  8:         {
  9:            
 10:             this.MobileName = strMobileName;
 11:             this.objIMobile = obj;
 12:  
 13:         }
 14:         public override string ToString()
 15:         {
 16:             return this.MobileName;
 17:         }
 18:  
 19:     }
Step 4

Create a third party class, that creates an instance of all these objects. See:

  1: class IOC
  2:     {
  3:         IMobile objMobile = null;
  4:        Samsung samsung;
  5:  
  6:         public void Assembling()
  7:         {
  8:             objMobile = new Android("Jelly Bean", 16);
  9:             samsung = new Samsung("Galaxy Grand", objMobile);
 10:         }
 11:         public override string ToString()
 12:         {
 13:             return string.Format("Mobile Name: {0} and {1}", this.samsung.ToString(), this.objMobile.ToString());
 14:         }           
 15:     }
Step 5

Use this third party class at the client side.

  1: class Program
  2:     {
  3:         static void Main(string[] args)
  4:         {
  5:             IOC objIOC = new IOC();
  6:             objIOC.Assembling();
  7:             Console.WriteLine(objIOC.ToString());
  8:             Console.ReadLine();
  9:         }
 10:     }


The following is sample output of the preceding codev using constructor injection.



SOLID3.jpg




  • Defects of Constructor Injection



  • In constructor injection, the business logic class doesn't have a default constructor. The reason is that we always require passing values as parameterized constructor.



  • Once the class is instantiated, Object Dependency cannot be changed.



Hope you enjoyed the way to understand the IOC.


To know more about MVC please go through with given below link.



MVC Articles
Enjoy Coding and Reading Smile



Keep coding and Enjoy.

Could not be loaded because it has a parameter or return type of type System.ServiceModel.Channels.Message in WCF
 
WCF
During an implementation of WCF Operation Contract I encountered an error as per the Title.
I was returning wrong parameter value from Operation contract which takes Message Contract as parameter .Kindly refer an image to understand real fact.
 
image
 
There are some limitation which are listed below,which we should keep in mind during implementation of WCF service








You can use the Message class as an input parameter of an operation, the return value of an operation, or both. If Message is used anywhere in an operation, the following restrictions apply:
  • The operation cannot have any out or ref parameters.
  • There cannot be more than one input parameter. If the parameter is present, it must be either Message or a message contract type.
  • The return type must be either void, Message, or a message contract type
Hope it will help you sometime.
 
To know more about MVC please go through with given below link.
MVC Articles
Enjoy Coding and Reading Smile





Monday, August 4, 2014

Differences Between Interfaces and Abstract Classes

Differences Between Interfaces and Abstract Classes

C#

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.
    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 is 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".
  5. If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.
    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.

 

To know more about MVC please go through with given below link.

MVC Articles

Enjoy Coding and Reading Smile

The difference between "as" and "cast" operators?

The difference between "as" and "cast" operators?

C#

Today i read some important about 'as' operator.Which i would like to share with my .Net geeks.This is one of the most frequent question asked in interview.its bit confusing but the excerpt defined here will give you bit idea about the representation.

The difference between "(Dotnet) cSharp" and "cSharp as Dotnet" is that the former throws an exception if the conversion fails, whereas the latter returns null. Though this is correct, and this is the most obvious difference, it's not the only difference. There are pitfalls to watch out for here.

short s = (short)123;

int? i = s as int?;

The "as" operator will not make the representation-changing conversions from short to nullable int like the cast operator would. Similarly, if you have class Dotnet and unrelated class cSharp,  with a user-defined conversion from cSharp to Dotnet, then "(Dotnet) cSharp,  will run the user-defined conversion, but "csharp as Dotnet" will not. The "as" operator only considers reference.

And finally, of course the use cases of the two operators are  similar, but semantically quite different. A cast communicates to the reader "I am certain that this conversion is legal and I am willing to take a runtime exception if I'm wrong"(I am willing to accept such error). The "as" operator communicates "I don't know if this conversion is legal or not;(Let's try once and see what happens how it goes").

In more layman words "The as operator returns null if the object can't be cast to that type, and just casting produces an exception"

To know more about MVC please go through with given below link.

MVC Articles

Enjoy CodingSmile

 

Sachin Kalia

Difference Between Const, ReadOnly and Static ReadOnly in C#

C#

This article is more about to understand most frequently used keywords in daily use.So we will try to understand them.

  1. Const: Const is nothing but "constant", a variable of which the value is constant but at compile time. And it's mandatory to assign a value to it. By default a const is static and we cannot change the value of a const variable throughout the entire program.


image

Here I have created a class named Variables and defined all three variables, so first we’ll look into const.


image


Here I tried to re-initialize the const variable, it gave me an error like "A const field requires a value to be provided".  Ok now I initialize a value for this variable and try to change it further in the class.


image

 


Here I have created a static constructor, default constructor, parameterized constructor and a Simple Method. I tried to change the value of the const variable everywhere but once I assign the value, I am unable to change it again since when I try to change its value ,it prompts me an error as you have seen above.

Now let's on to the Readonly keyword.

 

  1. Readonly: Readonly is the keyword whose value we can change during runtime or we can assign it at run time but only through the non-static constructor. Not even a method. Let's see:

  2. image


Here first I try to initialize the value in the static constructor. It gives me an error. Which you can see above.
Now I try to change the value in a method, see what happened:


image


Here, it is also giving an error that you can only assign a value either through a variable or a constructor.
Now try to change the value in the default constructor.


image


Now in the snapshot above you can see it's built successfully without an error, warning or messages. Let's check if there is a runtime error. OK.


image


Now here we can see that there is not a runtime error and the value was assigned successfully to the Readonly variable.
Now one gotcha is, now that you have assigned the value, can you change this value again ???


Let's try to change the value again.


image


Here I created  a parameterized constructor and created a new object, and passing a value as "Hello Friend's" and as I built it, it gave me the result "Build Succeeded".  Now let's move ahead and check for a runtime error:


image

See guys. There is no runtime error !!  And the value can be changed again and again through a constructor.
Now move ahead to Static Readonly variables.

  1. Static ReadOnly: A Static Readonly type variable's value can be assigned at runtime or assigned at compile time and changed at runtime. But this variable's value can only be changed in the static constructor. And cannot be changed further. It can change only once at runtime. Let's understand it practically.

image

Now in the preceding you can see that I used two variables, one is not assigned and another is assigned, and the static constructor.  Now in the static constructor you can see that the unassigned variable is being assigned and the assigned value is being changed. And there is no compile time error. Further I try to again change this variable's value.  See what happened:

image

As you can see in an image above, After creating Default , Parameterized Constructor and Method I tried to change the value again here. But getting a compile time error for all.

To know more about MVC please go through with given below link.

MVC Articles

ThanksSmile

Keep reading and Smile Smile