Friday 5 August 2011

Maestro API: 3 ways to create and work with resources

As explained previously, the Maestro API allows you to work with MapGuide resources in an object-oriented manner, completely avoiding the need to work with raw XML content (although the Maestro API provides such facilities should you require them)

What I didn't fully explain was how one actually can create retrieve and work with these objects. In the Maestro API, there are 3 ways to do this.

First way: Using the ObjectFactory class

The ObjectFactory class allows you to create resource objects from scratch. This method was available in the previous version of the Maestro API, but because you were working with generated classes, there was a very high chance of NullReferenceExceptions and DBXML errors being thrown at your face because you forgot to instantiate one or more of its many child properties.

The ObjectFactory class insulates these concerns away for you. Any resource you create via this approach satisfies the minimum content model requirements of its respective XML schema.

Here's an example of creating a feature source object to a SQL Server 2008 Express database from scratch

IFeatureSource fs = (IFeatureSource)ObjectFactory.CreateFeatureSource(conn, "OSGeo.SQLServerSpatial");
fs.SetConnectionProperty("Service", "(local)\\SQLEXPRESS");
fs.SetConnectionProperty("DataStore", "MyDatabase");
fs.SetConnectionProperty("Username", "mapguide");
fs.SetConnectionProperty("Password", "maestro");

where conn is an instance of the IServerConnection interface

Second way: Using the IResourceService

The GetResource method of the IResourceService interface automatically fetches XML content for the specified resource id and returns a strongly-typed IResource object.

Here's an example of fetching a feature source object

IFeatureSource fs = (IFeatureSource)conn.ResourceService.GetResource("Library://Test/Data/SQLServer.FeatureSource");


where conn is an instance of the IServerConnection interface

Final way: Using ResourceTypeRegistry

The final way is to use the ResourceTypeRegistry class to go from raw XML content to IResource objects and vice versa.

Here's an example of creating a feature source object from an feature source XML document on disk.

string xml = File.ReadAllText("FeatureSource.xml");
IFeatureSource fs = (IFeatureSource)ResourceTypeRegistry.Deserialize(xml);
fs.CurrentConnection = conn; //Need to assign a connection if you want to use any extension methods
where conn is an instance of the IServerConnection interface

And here's one example of going the other way, from feature source object to file

IFeatureSource fs = ...;
using(Stream sr = ResourceTypeRegistry.Serialize(fs))
{
using(FileStream fs = File.OpenWrite("FeatureSource.xml"))
{
Utility.CopyStream(sr, fs); //Or if you use .net 4.0 use the new CopyTo() method
}
}


So there you have it, 3 simple ways of working with resources in the Maestro API

No comments: