WCF Service - Using Datasets

There are a lot of articles out there on why it is not a good practice to use "Dataset" type in WCF. Basically, it is platform dependent and if the web service were to be consumed from another platform other than Windows, there could be an issue of data compatibility.

There are two possible ways of getting around this - serializing and compressing the dataset using the WriteToXML method and then compressing with gzip or using a collection of a data class made up of primitive data types.

For strictly Windows based platform, you could use Dataset type and have something liek this :
[ServiceContract]
public interface IContactManager
{
[OperationContract]
DataSet GetContacts();
[OperationContract]
void UpdateContact(int id, string name, string phone);
}
public class ContactManager: IContactManager
{
public DataSet GetContacts()
{
return _contacts;
}
public void UpdateContact(int id, string name, string phone)
{
var row = _contacts.ContactTable.FindById(id);
if (row != null)
{
row.Name = name;
row.Phone = phone;
}
_contacts.AcceptChanges();
}
}

To be in compliant with platform independence, you will need to implement the WCF service like so : [ServiceContract]
public interface IContactManager
{
[OperationContract]
List<Contact> GetContacts();
[OperationContract]
void UpdateContact(Contact c );
}
[DataContract]
public class Contact
{
[DataMember]
public int ID;
[DataMember]
public string Name;
[DataMember]
public string Phone;
}
public class ContactManager: IContactManager
{
public List<Contact> GetContacts()
{
List<Contact> retVal = new List<Contact>();
foreach (var row in _contacts.ContactTable)
{
var c = new Contact()
{
ID = row.ID,
Name = row.Name,
Phone = row.Phone
};
retVal.Add(c);
}
return retVal;
}
public void UpdateContact(Contact c )
{
var row = _contacts.ContactTable.FindById(c.ID);
if (row != null)
{
row.Name = c.Name;
row.Phone = c.Phone;
}
_contacts.AcceptChanges();
}

Comments

Popular posts from this blog

Decompiling Delphi - 3

Decompiling Delphi - 2

Artificial Intelligence, Oxymoron and Natural Intelligence