Monday 24 December 2012

Xml Serialization Behavior

Xml Serializer behaves differently based on the datatype and the behaviour of the property(Nullable/Not Nullable). Some time we may get confusion on why the xml serializer throwing an exception. Find the below table contains when the xml serializer throws an exception or when the object is instantiated.


Data Type

Property Behavior

Tag removed

i:nil="true"

Empty Tag

Invalid Content

Comments

Int, decimal

Nullable

Null

Null

Exception

Exception

Not Nullable

0

Exception

Exception

Exception

DateTime

Nullable

Null

Null

Exception

Exception

DateTime should be the following format, otherwise throws an exception
1) yyyy-MM-ddTHH:mm:ss
2)yyyy-MM-dd
3)HH:mm:ss

Not Nullable

0001-01-01T00:00:00

Exception

Exception

Exception

Collections

-NA-

Initialized new object with collection count as zero

Initialized new object with collection count as zero

Initialized new object with collection count as zero

Initialized new object with collection count as zero

Decorate property with [XmlElement(IsNullable=true)] attribute to set the property as null instead of initializing new object

Csharp Object

-NA-

Null

Initialized to New Object

Initialized to New Object

Initialized to New Object

Decorate property with [XmlElement(IsNullable=true)] attribute to set the property as null instead of initializing new object

Enum

Nullable

Null

Null

Exception

Exception

Not Nullable

Initialized with firt enum element

Exception

Exception

Exception

Sunday 30 September 2012

'Microsoft' is undefined

When I am trying to access the Windows Azure Mobile Services in the Windows 8 Metro App, I got the following exception.
0x800a1391 - JavaScript runtime error: 'Microsoft' is undefined windows azure mobile services
I searched the google to find the solution for this problem, but I did not found any solution. I tried many ways of referring script files. Finally I got the solution. The mistake what I did was only referring MobileSerivces.js in the groupedItems.html page where I am using grid layout in my metro application.

Solution:

Refer MobileServices.js in the default.html page as well.

Tuesday 10 July 2012

Could not load type 'System.Web.Http.Dependencies.IDependencyScope'

I am working on one Asp.Net WebApi project along with 5 members in my team. We are using
Asp.net MVC4  Beta for the WebApi project. Everything is working for me fine. Suddenly one day I got the latest version of code from TFS and try to run the application. The solution build succeed, but the application throwing the following exception.
Could not load type 'System.Web.Http.Dependencies.IDependencyScope' from assembly 'System.Web.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'
The same application is running in my other teammates. I researched around one day, but did not found any solution that why this dll is not loading run time even though the dll is present in the bin folder.  One of my team mate told that Asp.Net MVC4 is updated from beta to release version. I updated that in my system then the application is working fine. There was mismatch in the team communicatin about this updatation I lost my one day. If any one get this exception try to update the WebApi to release candidate.

Tuesday 5 June 2012

Date Comparision in Entity Framework

When we are writing linq expression in Entity framework as follows
context.GetQuery<TaxLocExtract>().Where(
tle => tle.EffectiveDate.Date == effectiveDate.Date).ToList();
then we will get the following exception
The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.
the solution to resolve is System.Data.Objects.EntityFunctions.TruncateTime() is used. the sample query as follows.
context.GetQuery<TaxLocExtract>().Where(
tle => System.Data.Objects.EntityFunctions.TruncateTime(tle.EffectiveDate) == System.Data.Objects.EntityFunctions.TruncateTime(effectiveDate)).ToList();
I hope this solution helps.

Friday 18 May 2012

structuremap 2.6 IncludeConfigurationFromConfigFile=true not working

When we are using structuremap 2.6.x  and adding structuremap configuration in the app.config/web.config. To  include configuration every one set the property IncludeConfigurationFromConfigFile=true. It is not working and seems to be not implemented. But when we are refering same app.config with AddConfigurationFromXmlFile(configfilepath) then it is working fine. when we are using app.config the file name of configuration is changed after the solution build. To include that configuration file find the solution below.
To get the name and path of configuration file as follows
var configName = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile; 
The example method and usage as follows:

 private static IContainer InitiazlizeFromAppConfigOrWebConfig()
 {
   var configName = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile; 
    return new Container(x =>
    {
     x.AddConfigurationFromXmlFile(configName);
      //x.IncludeConfigurationFromConfigFile = true; //seems not imeplemented
    });
}

Wednesday 16 May 2012

ObjectFactory Vs Container StructureMap

ObjectFactory is a static gateway for an instance of container. If you only ever want one instance of a container, and want a simple static way to get at it, use ObjectFactory. You must Initialize the ObjectFactory, and then retrieve your instances via ObjectFactory.

 Alternatively, if you want to manage the lifetime of the container yourself, you can create an instance of Container, passing an initialization expression to the constructor. You then retrieve instances from the variable you declared to store the Container.

Thursday 26 April 2012

[Fixed]How to overcome the linq contains limitation.Too many parameters were provided in this RPC request. the maximum is 2100

When we want to filter the data from the Linq to Sql query with the collection every one is trying to use the Contains() operator as follows. Linq to Sql will try to generate a sql query to represent the whole expression. This means that it will try to pass in the collection as parameters to a sql query. If there are too many parameters the query will hit the parameter limit (2100) and it cannot be executed. If there are not that many parameters, then you can use a contains expression which will be converted to an "IN" expression in sql. Sample code as follows
List<int> contactIds=Contact.GetContactIds()
//count of contactIds is morethan 2100
var contacts = Context.Contacts.Where(c => contactIds.Contains(c.ContactId)).ToList();
If the parameter limit exeeds then the following exception throws.
The incoming tabular data stream (TDS) remote procedure call (RPC) protocol stream is incorrect. Too many parameters were provided in this RPC request. The maximum is 2100.
To avoid this many developers will try to join the in memory collection with database table as follows. 
List<int> contactIds=Contact.GetContactIds()
//count of contactIds is morethan 2100
var contacts = Context.Contacts.Join(contactIds, c => c.ContactId, ci => ci, (c, ci) => c).ToList();
When developer trying this the following exception throws.
Local sequence cannot be used in LINQ to SQL implementations of query operators except the Contains operator.
This means that the linq to sql generates sql query and executes on the database server. Our in memory collection will not support to execute on the database server. so will get the above exception.
The easiest resolution is to convert the LINQ to SQL table into an IEnumerable list, which can be done as follows.
List<int> contactIds=Contact.GetContactIds()
//count of contactIds is morethan 2100
var contacts = Context.Contacts.AsEnumerable().Join(contactIds, c => c.ContactId, ci => ci, (c, ci) => c).ToList();
I hope this solution helps you.

Wednesday 25 April 2012

How to render partial view on each telerik Panel bar

The solution to render the partilal view on telerik panel bar or each panel bar contains one from is as follows. Here partial view contains form.
  @(
     Html.Telerik().PanelBar().Name("PanelBar").HtmlAttributes(new { style = "width: 300px;" }).BindTo(Model, mappings =>
      {
       mappings.For(binding => binding.ItemDataBound((item, manager) =>
       { 
         item.Text = manager.Name;
          item.Html = Html.Partial("Manager_Partial",manager).ToHtmlString();
          }));
         })
   )

How to read the conig file of class library in C Sharp

Every body knows that we can define the appsettings in the app.config file of class library. When we are refering the existing class library to the other new class library that only takes dll but not the configuration file of existing class library. To read values from the configuration file one option is to define same appsettings in the new class library. the other solution is as follows.

Solution:

  1. Refer the class library to the other new class library.
  2. Copy the .dll.config file from bin/debug folder of the existing class library and add to the new class library.
  3. Use the following code to get the values from the .dll.config file.
/// Load the .config file for the current DLL
System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();

Configuration dllConfig = ConfigurationManager.OpenExeConfiguration(assembly.Location);

KeyValueConfigurationCollection settings = dllConfig.AppSettings.Settings;
//read the value as follows
string value=settings[key].value;

Friday 16 March 2012

Handling string null or empty in Deserialization c sharp

When we are deserializing the string to object which we are passing the parameter with dynamic values, we don't know the parameter is null or empty. If we do not handle null or empty then it will throws an exception. But if the method is generic type then we don't know which type of class it is to create an instance and return. To create an instance without new keyword and the type of class use the solution below.
public static T DeSerializeDataContract<T>(String obj)
        {
            if (string.IsNullOrEmpty(obj))
            {
                Type type = typeof(T);
                return (T)Activator.CreateInstance(type);
            }
            using (var stringReader = new StringReader(obj))
            using (var reader = new XmlTextReader(stringReader))
            {
                DataContractSerializer serializer = new DataContractSerializer(typeof(T));
                return (T)serializer.ReadObject(reader);
            }

        }

Thursday 1 March 2012

JQuery multiselect selectedText does not work with JQuery > 1.4.2 when select list contains only one element

This is the problem with the change in the jquery version. Previous jquery(up to 1.4.2) the checkbox checked can be found by using "[checked]". Later versions of jquery changed to ":checked". To fix this issue go the jquery multiselect plugin js file line number 206 and change  $checked = $inputs.filter('[checked]') to $checked = $inputs.filter(':checked'). This solution works for me.

Monday 20 February 2012

How to get the current controller and action names in View Mvc3

In MVC we can use the partial views to avoid the redundant code. I have one requirement that the action names are same in two different controllers and there is partial view which has one link which needs to point to the current controller with the same action. I want to access the controller name in View to avoid the redundant code. The solution to get the Controller and Action names in View as follows. Solution:
 @{
        var controller = this.ViewContext.Controller.ValueProvider.GetValue("controller").RawValue.ToString();
    
        Change password
        }
If you want to access the action name
var action=this.ViewContext.Controller.ValueProvider.GetValue("action").RawValue.ToString();

Jquery Ajax Request and Unauthorized Access handling in MVC3

When we are posting the data through jquery $.ajax and  we are using asp.net forms authentication, if the user is not authorized then we will redirect to the login page. the same login page response is return result as on jquery ajax success. If we throw any exception in controller or any custom authorize attribute then ajax request returns the 500 status code internal server exception as its default behaviour. 500 status code reruns any exception in the request processing. But our view is to return the 401 as the status code. I research about many hours to get this solution.

Solution1:

1. Custom authentication attribute
public class AdminAuthorizeAttribute : AuthorizeAttribute  
{   
 protected override bool AuthorizeCore(HttpContextBase httpContext)
 {    
  User currentUser = ClientContext.Current.User;    

  return currentUser != null;      

 }

}
If the user is not authenticated the reruns to logon action as i am using forms authentication in asp.net.
2. In the controller action result write the following
 public ActionResult Logon()
 {
  if (Request.IsAjaxRequest())
  {
 
  //this is used when the authentication fails in the ajax request
  //this returns the httpstatus code 401 to the browser.
 
   ControllerContext.HttpContext.Response.StatusCode = 401;
 
   return Content(string.Empty);
  
   }

 } 
3. Handle the status codes in jquery $.ajaxSetup
$.ajaxSetup({
             statusCode: {
                        401: function () {
 
                            // Redirect the to the login page.
                            window.location = "/login/";
 
                        }
                    }
            });
Solution2:
public class AdminAuthorizeAttribute : AuthorizeAttribute  
{   
 protected override bool AuthorizeCore(HttpContextBase httpContext)
 {    
  User currentUser = ClientContext.Current.User;    

  return currentUser != null;      

 }


public override void OnAuthorization(AuthorizationContext filterContext)
{
   base.OnAuthorization(filterContext);

  // If its an unauthorized/timed out ajax request go to top window and redirect to logon.
    if (filterContext.Result is HttpUnauthorizedResult && filterContext.HttpContext.Request.IsAjaxRequest())
    {
filterContext.Result = new JavaScriptResult() { Script = "top.location.reload()"    };
    }

  // If authorization results in HttpUnauthorizedResult, redirect to error page instead of Logon page.
            if (filterContext.Result is HttpUnauthorizedResult)
            {
                if (ClientContext.Current.User == null)
                {
                    filterContext.Result =
                        new RedirectResult(
                            string.Format(
                                "~/logon/logon?ReturnUrl={0}",
                                HttpUtility.HtmlEncode(filterContext.HttpContext.Request.RawUrl)));
                }
                else
                {
                    filterContext.Result =
                       new RedirectResult(string.Format("~/error/unauthorized"));
                }
            }
        }
}
I hope this will help you.