Aug
20
2009

ApplyState and ExtractState with RIA Services Contrib

UPDATE: There is a new version of the ApplyState and ExtractState at http://www.riaservicesblog.net/Blog/post/Updated-ApplyStateExtractState-Library.aspx

Tomorrow Soon  Some day I am going to updating RIA Services Contrib with some new features. The existing T4 templates, as fun as they are, are going to left alone for now. I am going to look at them again after the PDC version of RIA Services is released. In the meantime, I am going to release some new utility classes that I have been putting together. The release is attached to this blog post and Codeplex will be updated tomorrow. 

This new contrib release adds ApplyState and ExtractState methods to Enity objects, an Import method to EntityList<T>, and an Export method to all IEnumerable<T> where T : Entity collections. To use the new code simply reference the RIAServicesContrib.dll and import the RiaServicesContrib.Extensions namespace.

Here are some usage examples:

Entity cloning

Person newPerson = newPerson();
newPerson.ApplyState(Nothing, existingPerson.ExtractState(ExtractType.ModifiedState);
newPerson.PersonId = Guid.NewGuid();
context.Persons.Add(newPerson);

Partial Save (i.e. save only a single change instead of the whole DomainContext)

PersonDomainContext tempContext = new PersonDomainContext();
Person savePerson = newPerson();
tempContext.Persons.Add(savePerson);
savePerson.ApplyState(originalPerson.ExtractState(ExtractType.OriginalState, ExtractType.ModifiedState);
tempContext.SubmitChanges();

Export EntityList and save to Isolated Storage

using IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication()
{
    using IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(fileName, FileMode.OpenOrCreate, isf)
    {
        DataContractSerializer serializer = new DataContractSerializer(typeof(List<EntityStateSet>));
        serializer.WriteObject(isfs, context.Persons.Export());
        isfs.Close();
    }
}

Import information from Isolated Storage into EntityList

using IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication()
{
    using IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(fileName, FileMode.Open, isf)
    {
        DataContractSerializer serializer = new DataContractSerializer(typeof(List<EntityStateSet>));
        context.Persons.Import(serializer.ReadObject(isfs));
        isfs.Close();
    }
}

Some things which might not be obvious is that the Export functionality can also be done against a LINQ query, allowing partial exports of entities. When I update CodePlex I am going to include better documentation of the API.

RiaServicesContrib.zip (12.97 kb)

blog comments powered by Disqus

Month List