Blog from Saravanan Arumugam

Let us talk about Technologies

Monthly Archives: March 2012

Entity Object as Data Contracts in WCF service


I have come across an interesting issue recently while I used Entity Objects in WCF. Before explaining the actual issue, let me explain a few concepts of serialization.

Entity Object vs. WCF

Entity objects are designed so rich, so that if it is chosen to be used in WCF, WCF would not require additional classes to serve as Data Contracts because the entity objects are usually decorated with the following attributes.

    [EdmEntityTypeAttribute(NamespaceName = "IntradoModel", Name = "ICRecord")]
    [Serializable()]
    [DataContractAttribute(IsReference = true)]
    public partial class ICRecord : EntityObject

EdmEntityTypeAttribute links the class to the conceptual model. It helps the Linq to Entity to recognize this type as a legal entity object. SerializableAttribute says that the object of this type can be serialized if needed. DataContractAttribute on the other hand also means that the the type is seriablizable but, by a special serializer – DataContractSerializer.

Note that the classes are partial, so just incase we need more members in the Data Contract, we can always write the partial class with additional members and extend it.

 

Some Concepts of Serialization

There are differences in the way the regular serializers (XmlSerializer, BinaryFormatter, SoapFormatter) and the DataContractSerializer chose the members to serialize. For example consider the following class.

public class SampleClass
{
    public int Number1 { get; set; }
    public int Number2 { get; set; }
    public int Number3 { get; set; }
 
    public int Sum { get; set; }
    public int Product { get; set; }
}

If we serialize an object of the above type, we would get something like below.

<SampleClass>
  <Number1>2</Number1>
  <Number2>2</Number2>
  <Number3>2</Number3>
 
  <Sum>6</Sum>
  <Product>8</Product>  
</SampleClass>

Serialization is usually a costly process, in terms of size, space, or transmission overhead. So its usual that you’d try to ignore some of the members during serialization without losing information. In our example, the information is carried through Number1, Number2, and Number3. But Sum and Product can always be calculated from the numbers at any point of time. So we can ignore them during serialization to save space, size and transmission overheads.

 

Opt-in vs. Opt-out method of serialization

The usual serializers, XmlSerializer, BinaryFormatter, and SoapFormatter works in the Opt-Out method. This means that all the members would be a part of the serialization unless you particularly ignore some. XmlIgnoreAttribute, NonSerializedAttribute, SoapIgnoreAttributes are the ones used to opt-out a member from getting serialized.

[Serializable]
public class SampleClass
{
    public int Number1 { get; set; }
    public int Number2 { get; set; }
    public int Number3 { get; set; }
 
    [NonSerialized]
    [XmlIgnore]
    [SoapIgnore]
    public int Sum { get; set; }
    
    [NonSerialized]
    [XmlIgnore]
    [SoapIgnore]
    public int Product { get; set; }
}

On the other hand DataContractSerializer, works in the Opt-in method. This means that during the serialization only the members marked with DataMemberAttribute would be serialized. Members without the attribute would be ignored during the serialization. Here we are opting-in what we want.

[Serializable]
[DataContract]
public class SampleClass
{
    [DataMember]
    public int Number1 { get; set; }
    [DataMember]
    public int Number2 { get; set; }
    [DataMember]
    public int Number3 { get; set; }
 
    [NonSerialized]
    [XmlIgnore]
    [SoapIgnore]
    public int Sum { get; set; }
 
    [NonSerialized]
    [XmlIgnore]
    [SoapIgnore]
    public int Product { get; set; }
}

 

Possible Issue in using Entity Objects as Data Contracts

I found the following exception when I tried using the Entity Objects as Data Contracts.

The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.

Usually an Entity Object contains the following structure. (We can find the structure of the entity model in Entities.Designer.cs)

    • Factory Method to create an object of its own type.
    • Primary Properties
    • Navigation Properties

Here factory method is not going to be part of the serialization, since its not a property. Primary and Navigation Properties would be part of serialization.

Primary properties provide all the information that you might need from the object. Navigation properties are to help the entity users for accessing the related tables/objects. So it doesn’t have the significance in serialization.

So Navigation Properties need not take part in serialization. XmlSerializer, and SoapFormatter would ignore them, but DataContractSerializer would not (I guess it’s a miss from Microsoft developers group or may be intentional). This is due to the attributes placed on these Navigation properties.

[XmlIgnoreAttribute()]
[SoapIgnoreAttribute()]
[DataMemberAttribute()]
[EdmRelationshipNavigationPropertyAttribute("MyModel", 
    "FK_ICRun_ICFile", 
    "ICFile")]
public ICFile ICFile
{
    get{

Reason for the exception

Usually the entity object uses the concept of Lazy Loading. In your code you’d be filling the object by using an object context, and close the context. But this would only fill the primary properties. Navigation properties would be filled only if you need them when you explicitly access them.

using (var context = new IntradoEntities())
{
    return context.ICFiles.Where(record =>
        (FileStatus)record.Status == FileStatus.Error).ToList();
}

When the DataContractSerializer encounters a navigation property, it would try to retrieve it during the runtime. But at the time of serialization Object Context would not be alive, so we end up with the exception.

The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.

Even the Eager Loading, the issue wouldn’t be over since there’s always a limit for the depth of objects during Soap transmission.

Solution

The solution is simple. Remove the DataMemberAttribute from the navigation properties.

To avoid any accidents of removing useful members from serialization, make sure you remove DataMemberAttribute only to those properties within the #region named as Navigation Properties.

I hope we’ll get a better Entity Framework version next time.

The type ‘System.Data.Objects.DataClasses.EntityObject’ is defined in an assembly that is not referenced


I am working on an MVC 3 application where I use an Entity Object as the model to the View. I was getting the following error in the browser.

Exception

Compiler Error Message: CS0012: The type ‘System.Data.Objects.DataClasses.EntityObject’ is defined in an assembly that is not referenced. You must add a reference to assembly ‘System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089’.

Solution:

It was interesting that the MVC project by default has the reference to System.Data.Entity namespace. But still the issue was presented. I finally figured out the clue from another word press blog. I had to add the assembly entry in the Web.config to resolve the issue.

  <assemblies>

    <add assembly=System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35 />

    <add assembly=System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35 />

    <add assembly=System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35 />

    <add assembly=System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35 />

    <add assembly=System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35 />

    <add assembly=System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089/>

  </assemblies>

Note that the complete assembly name is presented in the exception message itself.

Error message 401.2.: Unauthorized: Logon failed due to server configuration.


I was trying to get my MVC 3 web application work through IIS 7.5 Express, and when I ran the application I got the following error.

Exception

Access is denied.

Description: An error occurred while accessing the resources required to serve this request. The server may not be configured for access to the requested URL.
Error message 401.2.: Unauthorized: Logon failed due to server configuration. Verify that you have permission to view this directory or page based on the credentials you supplied and the authentication methods enabled on the Web server. Contact the Web server’s administrator for additional assistance.

 

Solution

As the first step I had to look at the web.config. The authentication mode was set to Windows Authentication.

    <authentication mode="Windows" />
    <authorization>
      <deny users="?" />
    </authorization>

Even though the web.config says that I need windows authentication, IIS Express need to be informed about it.

To resolve it, I did the following.

1. Clicked on the Web Project, and hit F4. (Right click and properties will get you to a different place)

2. Made sure that I can see the Properties Pane. (Not the property window).

3. Select Enabled for the Windows Authentication Property.

image

This would enable the windows authentication and get rid of the exception.

Use IIS Express option doesn’t appear on the context menu of a Web based Project


I wanted to use IIS express as the development server instead of Visual studio’s built in Development Server. For that I had to install Visual Studio 2010 SP1 and IIS 7.5 Express.

However in Visual Studio, I couldn’t fine the option “Use IIS Express” when I right click on the web project.

 

Solution

As an alternate to selecting Use IIS Express, right click on the project select Properties. In the property page select the Web Tab. Here, select Use Local IIS Web Server.

Make sure that Use IIS Express is checked.

image

This will ensure that the web application is starting in IIS Express.

Sneak Peak at Windows 8


Microsoft has recently made the Windows 8 Customer Preview available. I installed it in a virtual machine made out of VirtualBox.

Here is some of the screenshots, my observations and my views on Windows 8 at first look.

 

Download

A setup package (in .exe form) can be downloaded from here, or an ISO file can be downloaded from here.

ISO download size is 3.3 GB for 64 bit version, 2.5 GB for 32 bit. After installation it consumed 7.37 GB of my hard disk space.

 

Installation

Installation takes about an hour or less, which is good.

Screenshot 1

Pros:

1. Installation completes really quick.

2. It doesn’t ask too much of questions as other Windows versions used to do. It grabs most of your information from windows mail profile. I used my Live id to register it which is already associated to Microsoft. However it might take some additional steps to register your windows profile if you don’t have one.

Cons: I didn’t see any blue screens like from other version.

 

Personalizing

Personalizing has the steps of choosing desktop colors, PC name, your network etc.

Screenshot 2

Pros: Again the number of steps look to be very few.

Cons: I would say, as a windows desktop user for years, the interface appears to be too simple, in some way too primitive. It reminds me the graphics and interface we used to have when we were using MS-DOS.

 

Screenshot 4

 

Home / Start Screen

Windows phone users can easily recognize the screen. It’s appears to be a strategically idea of Microsoft to make the line between Desktop and Mobile operating system thinner / disappear completely.

I like the idea of making the platform application centric. Since most people using a computer likes to work on some apps. So its not necessary to insist the user to go to the desktop, click on Start, Go to All Programs etc.

image

image

Pros:

1. As a developer, I like the idea of making the desktop and mobile platforms the same, since with the existing knowledge and technology I used for desktop development can be extended to Mobile development.

2. Its good that they preserved the desktop, windows explorer, control panel etc., so that we always have some workaround if we think we run out of some option.

3. Its good to see a little thumb nail of every running apps all at one place.

4. Application switching preserved in Windows 8 unlike Windows Mobile phones. Alt+Tab and Win+Tab are still active.

Cons:

1. Fixed sized icons/boxes: The boxes appears to be fixed size, at the max you can make the rectangle to square and vice versa. Nothing much can be customized, at least can not be done easily. (Or Perhaps I have not seen the options yet)

2. NO START BUTTON ON DESKTOP: Its being difficult to work in a desktop without a start button. It looks like a read only desktop, you can see something running, but you can’t start any app from desktop Sad smile

However, Windows key on the keyboard bring us quickly to the start page.

 

Applications

The apps are cool as usual. I checked out some and I like their appearance. Its good to see that apps have retained their richer colors.

Screenshot 6

Screenshot 7

Screenshot 8

image

 

Task Manager

We have a cute looking task manager with Windows 8. I love it at the first site.

image

Pros: Task manager looks to have been carefully changed. Its well organized and color coded. However, the Resource Monitor hasn’t changed a bit.

Cons: I don’t see any.

 

Synchronizing and Sharing

All the apps are synchronized to your profile cloud. It enables you to work with all your application independent of your devices. If synchronization is made ideal (I haven’t tested it yet.), I can create a word file from my home machine, travel to office and open the same file from my office machine to edit it. However, for now I can see my calendar is synchronized to my google account.

image

Sharing feature is available in many apps, and enables us share things through mail (I haven’t seen any option to share things on the social network, like facebook, etc.).

image

 

Summary

As usual with any change, windows 8 will go though a lot of resistance from its users. But eventually, things will settle down. Windows 8 has a long way to go.

However, personally I like the bigger idea of the Windows 8. It brings the desktop and mobiles closer. From the development stand point, an application made for a desktop can work on any mobile device. We don’t need to learn any additional technologies.