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

Thursday, July 31, 2014

Integration of jqGrid With MVC4 Application: Part 2

Integration of jqGrid With MVC4 Application: Part 2

 

jqGrid

 

Actually I needed to implement it in my project and I encountered many difficulties in getting this feature because I hardly found any help for it and if I found something then it was just halfway useful.
I recommend you to visit this before proceeding with this article.

This is a second part of Integration of jqGrid with MVC4 application. This part is more about enabling add, edit, delete and refresh as well as a little validation using builtin validation keywords.

  • Enabling jqGrid add, edit, delete and refresh
  • Validation keywords

To learn more about MVC kindly go to C# Corner MVC Section or My Blog.
I've developed this sample application using Visual Studio 2012 and used Entity Framework to retrieve information from the database.

Step 1 : Enabling jqGrid add, edit, delete and refresh



After enabling values we should run the application and press F5. Kindly see the following image.


I have pasted this URL into a browser http://localhost:26158/Admin to get the above result.
Here is the complete code of AddTopic.cshtml, though I will share the AdminController class file and AddTopic.cshtml file with you as a sample so that you could add it into your solution.
Note: the code segment of jqGrid in the AddTopic.cshtml view is as shown below:

  1: @{  
  2: ViewBag.Title = "ADDTOPICS";  
  3: Layout = "~/Views/Shared/_Layout.cshtml";  
  4: }  
  5: <!DOCTYPE html>
  6: <html>
  7: <head>
  8: <meta name="viewport" content="width=device-width" />
  9: <title>AddTopics</title>
 10: <script src="~/Scripts/jquery.jqGrid.js"></script>
 11: <script src="~/Scripts/jquery.jqGrid.min.js"></script>
 12: <script src="~/Scripts/i18n/grid.locale-en.js"></script>
 13: <link href="~/Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" />
 14: <link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
 15: <!-- The jqGrid client-side javascript -->
 16:     @*   <script type="text/javascript" src="http://www.trirand.net/aspnetmvc/Scripts/trirand/jquery.jqGrid.min.js"></script>*@  
 17: <script type="text/javascript">
 18:         var ClickEventId;  
 19:         $(document).ready(function myfunction() {  
 20:             $('#list').jqGrid({  
 21:                 caption: "Add Topics",  
 22:                 url: '/Admin/GetTopics/',  
 23:                 datatype: "json",  
 24:                 contentType: "application/json; charset-utf-8",  
 25:                 mtype: 'GET',  
 26:                 colNames: ['ID', 'Name', 'Created_by', 'Created_On'],  
 27:                 colModel: [  
 28:                                 { name: 'ID', index: 'ID', width: 150, editable: true, editoptions: { readonly: 'readonly' }, editrules: { readonly: true } },  
 29:                                 {  
 30:                                     name: 'topic_name', index: 'topic_name', width: 150, editable: true, editrules: { required: true }  
 31:                                 },  
 32:                                 {  
 33:                                     name: 'Created_by', index: 'Created_by', width: 150, editable: true, editrules: { required: true }  
 34:                                 },  
 35:                                 { name: 'Created_On', index: 'Created_On', width: 150, editable: true, editrules: { required: true } }  
 36:                 ],  
 37:                 rowNum: 10,  
 38:                 loadonce: true,  
 39:                 pager: '#pager',  
 40:                 editurl: '/Admin/EditTopics/'  
 41: 
 42:             });  
 43: 
 44:             jQuery("#list").jqGrid('navGrid', '#pager', {  
 45:                 edit: true,  
 46:                 add: true,  
 47:                 del: true,  
 48:                 search: true,  
 49:                 refresh: true,  
 50:                 searchtext: "Search",  
 51:                 addtext: "Add",  
 52:                 edittext: "Edit",  
 53:                 deltext: "Delete",  
 54:                 refreshtext:"Refresh"  
 55:             }            
 56:        );  
 57:             $('.ui-pg-button').on('click', function (ev) {  
 58: 
 59: ClickEventId = this.id;  
 60:             });  
 61:         });  
 62: </script>
 63: </head>
 64: <body>
 65: <table id="list"></table>
 66: <div id="pager"></div>
 67:     @*<div>
 68: <%= Html.Trirand().JQGrid("", "EditDialogGrid") %>
 69: </div>*@  
 70: </body>
 71: </html>
 72: 

Code for AdminController: After putting this URL http://localhost:26158/Admin into a browser, it calls the Index Action that returns the AddTopics View and does other operations.

 

  1: using System;  
  2: using System.Collections.Generic;  
  3: using System.Collections.Specialized;  
  4: using System.Linq;  
  5: using System.Web;  
  6: using System.Web.Mvc;  
  7: using QuickBook.Models;  
  8: 
  9: namespace QuickBook.Controllers  
 10: {  
 11:     public class AdminController : Controller  
 12:     {          
 13:         // GET: /Admin/  
 14:         EmployeeEntities edb = new EmployeeEntities();  
 15:         public ActionResult Index()  
 16:         {  
 17:             return View("AddTopics");  
 18:         }  
 19: 
 20:         [HttpGet]  
 21:         public JsonResult GetTopics()  
 22:         {  
 23:             EmployeeEntities edb = new EmployeeEntities();  
 24:             var jsonData = new
 25:             {  
 26: total = 1,  
 27: page = 1,  
 28: records = edb.tblAddTopics.ToList().Count,  
 29: rows = (  
 30:                   from emp in edb.tblAddTopics.ToList()  
 31:                   select new  
 32:                   {  
 33: id = emp.id,  
 34: cell = new string[] {   
 35:                       emp.id.ToString(), emp.topic_name.ToString(), emp.created_by.ToString(),emp.created_on.ToString()   
 36:                       }  
 37:                   }).ToArray()  
 38:             };  
 39:             return Json(jsonData, JsonRequestBehavior.AllowGet);  
 40:         }  
 41:         [HttpPost]  
 42:         public void EditTopics(tblAddTopic postData, string ClickEventId)  
 43:         {  
 44:            // EmployeeEntities edb = new EmployeeEntities();  
 45:             if (ClickEventId == "edit_list")  
 46:             {  
 47:                 var editRecord =  
 48: edb.tblAddTopics.Where(x => x.id == postData.id).SingleOrDefault();  
 49: editRecord.topic_name = postData.topic_name;  
 50: editRecord.created_by = postData.created_by;  
 51: editRecord.created_on = postData.created_on;  
 52: 
 53:                 edb.SaveChanges();  
 54:             }  
 55:             else if (ClickEventId == null && postData.topic_name!=null)  
 56:             {  
 57:                 //var editRecord =  
 58:                 //  edb.tblAddTopics.Where(x => x.id == postData.id).SingleOrDefault();  
 59:                 //editRecord.topic_name = postData.topic_name;  
 60:                 //editRecord.created_by = postData.created_by;  
 61:                 //editRecord.created_on = postData.created_on;  
 62: 
 63:                 edb.tblAddTopics.Add(postData);  
 64:                 edb.SaveChanges();  
 65:             }  
 66:             else if (postData.topic_name==null)  
 67:             {  
 68:                 var DeleteRecord =  
 69: edb.tblAddTopics.Where(x => x.id == postData.id).SingleOrDefault();  
 70:                 edb.tblAddTopics.Remove(DeleteRecord);  
 71:                 edb.SaveChanges();  
 72:             }  
 73:         }  
 74:         [HttpGet]  
 75:         public JsonResult GetQuestionNo()  
 76:         {  
 77:             EmployeeEntities objEmpRegistration = new EmployeeEntities();  
 78:             List<Question> Questions = new List<Question>();  
 79: 
 80: Questions = (from p in objEmpRegistration.tblAddQuestions.ToList()  
 81:                          group p by p.category_id into g  
 82:                          select new Question  
 83:                          {  
 84: QuestionNO = g.Count() + 1,  
 85: categoryID = g.Key  
 86:                          }).ToList();  
 87: 
 88:             return Json(Questions,JsonRequestBehavior.AllowGet);  
 89:         }  
 90:         public ActionResult AddQuestion()  
 91:         {  
 92: 
 93:             return View(new UpdateCategory());  
 94:         }  
 95:         [HttpPost]  
 96:         public void Savequestion(int dropdownid, string Ques,string Ans)  
 97:         {  
 98:             tblAddQuestion addobj = new tblAddQuestion();  
 99: 
100: addobj.category_id = dropdownid;  
101: addobj.question = Ques;  
102: addobj.answer = Ans;  
103: addobj.created_by = 100;  
104: addobj.created_on = System.DateTime.Now;  
105:             edb.tblAddQuestions.Add(addobj);  
106:             edb.SaveChanges();  
107:           //  return ("successfully");  
108:         }  
109:     }  
110: }  

 


 


Validation keywords:



Kindly refer to the following image to understand grid-level validation.


Note: You can control more textual information at the grid.locale-en.js level, like caption, Add caption, the Submit button text and much more as shown in the image below.





I have added AddTopics.cshtml and Admincontroller.cs as a sample though I have already shared a database backup file in Part 1.You can download code from the link shown below:


http://www.c-sharpcorner.com/UploadFile/97fc7a/integration-of-jqgrid-with-mvc4-application-part-2/


Thanks.
Stay happy and stay codingSmile