.NET Attitude

Tuesday, November 18, 2008

Loading XmlSchema files out of Assembly Resources

Please refer the article written by the God of .NET Sir Scott Hansleman
http://www.hanselman.com/blog/CommentView.aspx?guid=413e8258-ae5b-4949-9cee-43c112c0d3b2

Hope this would help everyone.

Friday, October 24, 2008

Structs & Inheritance

There is no inheritance for structs as there is for classes. A struct can't inherit from another struct or class and it can't be the base class for a class. But remember that in C# all types are directly or indirectly inheriting from the super base class object and hence the structure also. Since structs doesn't support inheritance, we can't use the keywords virtual, override, new, abstract etc with a struct methods. C# struct types are never abstract and are always implicitly sealed. The abstract or sealed modifiers are not permitted in a struct declaration.
Since inheritance is not supported for structs, the declared accessibility of a struct member can't be protected or protected internal. Since all struct types are implicitly inherit from object class, it is possible to override the methods of the object class inside a struct by using the keyword override. Remember that this is special case in C# structs.

WCF Data Integrity Problem (Use of Specified Fields)

Hi Guys,

As part of the requirement of the Remarketing tool, I needed to create two services which needs to communicate with each other. One being the RDTSecurityService and the Other is the UserDALService. RDTSecurity Service consumes the UserDAL Service for some of it Authentication related functionalities. When I was working on it and after careful observation I found out that the Data sent from RDTSecurity Service to the UserDALService is getting disappeared. This is sounding weird, that how can the data disappear ?

Disappearing the data means the object sent from RDTSecurity Service which has a valid data is found missing(or you can say the object is getting reinitialized) when seen at the UserDALService level. After complete verification of the code, I had a look in the Proxy file of the UserDAL Service which is at the RDTSecurityService.

And it was looking something similar to this :

public partial class LoginCredentials : object, System.Runtime.Serialization.IExtensibleDataObject
{

private System.Runtime.Serialization.ExtensionDataObject extensionDataField;

private bool activeCenterFieldSpecified;

private string clientIPAddressField;

private bool isFromObeliskField;

private bool isFromObeliskFieldSpecified;

private int noOfDaysLeftForExpiryField;

private bool noOfDaysLeftForExpiryFieldSpecified;

private string passwordField;

private string serverIPAddressField;

private string sessionIDField;

private int userIDField;

private bool userIDFieldSpecified;
}
}


If you observe carefully that for few fields some extra variable declared as Boolean.
(Ex: private bool userIDFieldSpecified;)

This was not declared by me explicitly; but I found it in the proxy class. I was amazed how come these variables are created, and what could be the purpose.

WHO IS THE CULPRIT??
---------------------------

When I did some RND, I found that here, the WCF Data Contract Serializer is the Culprit.
{
Basically there are 3 types of Serializer :
- XmlSerializer
- DataContractSerializer
- NetDataContractSerializer

Each performs the same fundamental task i.e., mapping between .NET objects and XML Infosets.
}

DataContractSerializer is the default and is always used unless specified.

Why
--------

The answer is the schema that the WCF data contract Serializer generates by default. Because of the way its versioning model works, the Serializer generates all data members as optional elements.
The older web services stack, ASP.NET Web Services (“ASMX”), uses a different Serializer, the XmlSerializer, which maintains full schema and XML fidelity. The XmlSerializer maps all optional elements to two members: one represents the data itself, and one specifies whether or not the data is actually present – this is the “xxxSpecified” member.

These xxxSpecified members must be set to true to enable the serialization of the corresponding “actual data” members

Solution
--------------

1) You can prevent the xxxSpecified members from being generated by marking the data members as required instead of optional:

[DataContract]
public class LoginCredentials
{
[DataMember(IsRequired=true)]
public int UserID;
}

2) Change the generated proxy code on the client side. You could specify default values of “true” for the xxxSpecified members, or you could modify the property setter for each member (e.g. zipCodeFrom) to set the corresponding xxxSpecified member (e.g. zipCodeFromSpecified) to true whenever that property is set.

There are many circumstances in which modifying the generated proxy code is unacceptable – e.g. when you expect the service to change and thus expect to have to regenerate the proxy code often. In this situation, you can take advantage of the “partial class” feature to add a helper method to do the property setting work.
{ Inother words, we can find all the member which name xxxSpecified and set the value as true}

3) If you really need to avoid xxxSpecified with parameters, there is a workaround involving

[MessageContract(IsWrapped=false)] containing a data contract with required data members

Note:- This will affect the interoperability

4) Switching to XmlSerializer on the service side instead of the DataContractSerializer.


References :
------------
http://blogs.msdn.com/eugeneos/archive/2007/02/05/solving-the-disappearing-data-issue-when-using-add-web-reference-or-wsdl-exe-with-wcf-services.aspx

Thursday, October 23, 2008

WCF Service shows plain/ blank page during hosting

The problem is solved by:

1.Go to Run. type 'inetmgr'. this will open a Internet Information Services.

2.Under websites. go to default web site and select properties.

3.Under Home Directory Tab,Select Configuration, which will show you the Application Configuration.

4.Under Application Configuration,Under Mappings Tab,please check wether you can see an extension with '.svc'.

5. if it is not there please add an extension named as .svc and with the Executable in %WIN%\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll

6.reset your IIS by typing 'iisreset' in the run menu.

7. Run your application again.

Saturday, September 1, 2007

Assembly Resource Files for Storing Key Value pairs

Its always a good practice to Store the Controls Text or Storing SQL Queries Used within an

SQL Application. There are many ways of achieving this functionality

1. By using XML files
2. Putting into Database
3. Using Assembly Resource Files(.resx)

XML Files can be used for the Application which doesn't much of the Security.This is

because there XML file's is more exposed to the Outside world and there is always a chance

to show copyright informaytion to the external world.
So Using XML files is also not a good practice.


Putting into SQL Queries and Controls field Text in Database inturn affects the performance

of the Database Server.

One of the Best ways of addressing this Problem is to use Assembly Resource Files(.resx)


-- Just Create a Class file named as ResourceInterface and Copy the Following Code


using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Windows;
using System.Resources;
using System.Collections;

/*
Date : 03/09/2007
Created By : Pratap.BVNP(PSI Data Systems)
Last Modified By : Pratap.BVNP
*/


///
/// This Class is used to retrive data from a Hastable,Put the Hastable into cache and then used Cached Hastable for Accessing the various Contents of the Resource File
/// Requirement for this Class to run is to Add System.Windows.Forms as a Reference to the Project.
///

public class ResourceInterface
{
public ResourceInterface()
{
//
// TODO: Add constructor logic here
//
}
///
/// This function puts the Resource file ino the Cache as a Hastable.It is used inderectly by the getKey() function
///

/// Name Of the File for which you want to use as a Cache Key
/// Hashtable containing all the contents of the Resource file.
private Hashtable putResourceInCache(string strFileName)
{
ResXResourceReader res = new ResXResourceReader(strFileName);
IDictionaryEnumerator ideEnum = res.GetEnumerator();
Hashtable htResourceData = new Hashtable();
while (ideEnum.MoveNext())
{
htResourceData[ideEnum.Key] = ideEnum.Value;
}
HttpContext.Current.Cache.Add(strFileName, htResourceData, null, System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.High, null);
return htResourceData;
}
///
///This function is used to Extract the Data from an Assembly Resource File.Give the FileName and the key for which you want the value
///

/// FileName for which you want to access
/// Key for which you want to reteive the Value
/// and Object containing the Data for that Key
public Object getKey(string strFileName,string key)
{
Hashtable htResourceData = HttpContext.Current.Cache[strFileName] as Hashtable;
if (htResourceData == null)
{
htResourceData = putResourceInCache(strFileName);
}
if (htResourceData[key] == null)
{
throw new Exception("Invalid key for a the Resource File : " + strFileName);
}
return htResourceData[key];
}
}



-- The above code has two methods named : getKey(...) and putResourceInCache(...)

-- And Add reference for System.Windows.Forms to the Current project of your ASP.NET Application.


-- Now You can Create an RESX file and put some information in name and values fields to store the Key Value information. or have an Existing resx file ready for to use.