#region Disclaimer / License // Copyright (C) 2009, Kenneth Skovhede // http://www.hexad.dk, opensource@hexad.dk // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // #endregion using System; using OSGeo.MapGuide; using System.Collections.Specialized; namespace OSGeo.MapGuide.MaestroAPI { /// /// A connection to the server, using the Native API. /// Only works locally, or with special firewall rules for the server. /// public class LocalNativeConnection : ServerConnectionBase, ServerConnectionI, IDisposable { private OSGeo.MapGuide.MgSiteConnection m_con; private string m_locale; private string m_sessionId; private Version m_siteVersion = null; public const string PARAM_SESSION = "SessionId"; public const string PARAM_CONFIG = "ConfigFile"; public const string PARAM_USERNAME = "Username"; public const string PARAM_PASSWORD = "Password"; public const string PARAM_LOCALE = "Locale"; private LocalNativeConnection() : base() { } //This is the constructor used by ConnectionProviderRegistry.CreateConnection internal LocalNativeConnection(NameValueCollection initParams) : this() { if (initParams[PARAM_SESSION] != null) { string sessionid = initParams[PARAM_SESSION]; InitConnection(sessionid); } else { if (initParams[PARAM_CONFIG] == null) throw new ArgumentException("Missing connection parameter: " + PARAM_CONFIG); if (initParams[PARAM_USERNAME] == null) throw new ArgumentException("Missing connection parameter: " + PARAM_USERNAME); string configFile = initParams[PARAM_CONFIG]; string password = initParams[PARAM_PASSWORD] ?? string.Empty; string username = initParams[PARAM_USERNAME]; string locale = null; if (initParams[PARAM_LOCALE] != null) locale = initParams[PARAM_LOCALE]; InitConnection(configFile, username, password, locale); } } private void InitConnection(string sessionid) { MgUserInformation mgui = new MgUserInformation(sessionid); m_con = new MgSiteConnection(); m_con.Open(mgui); m_sessionId = sessionid; } private void InitConnection(string configFile, string username, string password, string locale) { m_username = username; m_password = password; m_locale = locale; OSGeo.MapGuide.MapGuideApi.MgInitializeWebTier(configFile); //Throws an exception if it fails RestartSession(); } [Obsolete("This will be removed in the future. Use ConnectionProviderRegistry.CreateLocalNativeConnection() instead")] public LocalNativeConnection(string sessionid) : this() { InitConnection(sessionid); } [Obsolete("This will be removed in the future. Use ConnectionProviderRegistry.CreateLocalNativeConnection() instead")] public LocalNativeConnection(string configFile, string username, string password, string locale) : this() { InitConnection(configFile, username, password, locale); } /// /// Returns a working copy of the site connection. /// private MgSiteConnection Con { get { //It seems that the connection 'forgets' that it is logged in. if (string.IsNullOrEmpty(m_con.GetSite().GetCurrentSession())) m_con.Open(new MgUserInformation(this.SessionID)); return m_con; } } #region ServerConnectionI Members public override string SessionID { get { return m_sessionId; } } public ResourceList RepositoryResources { get { return GetRepositoryResources(); } } public override ResourceList GetRepositoryResources(string startingpoint, string type, int depth, bool computeChildren) { if (type == null) type = ""; MgResourceService res = this.Con.CreateService(MgServiceType.ResourceService) as MgResourceService; System.Reflection.MethodInfo mi = res.GetType().GetMethod("EnumerateResources", new Type[] { typeof(MgResourceIdentifier), typeof(int), typeof(string), typeof(bool) }); return (ResourceList) base.DeserializeObject(typeof(ResourceList), Utility.MgStreamToNetStream(res, mi, new object[] {new MgResourceIdentifier(startingpoint), depth, type, computeChildren })); } public override FeatureProviderRegistryFeatureProviderCollection FeatureProviders { get { MgFeatureService fes = this.Con.CreateService(MgServiceType.FeatureService) as MgFeatureService; var reg = (FeatureProviderRegistry)base.DeserializeObject(typeof(FeatureProviderRegistry), Utility.MgStreamToNetStream(fes, fes.GetType().GetMethod("GetFeatureProviders"), new object[] { })); return reg.FeatureProvider; } } public string TestConnection(string providername, System.Collections.Specialized.NameValueCollection parameters) { MgFeatureService fes = this.Con.CreateService(MgServiceType.FeatureService) as MgFeatureService; System.Text.StringBuilder sb = new System.Text.StringBuilder(); if (parameters != null) { foreach(System.Collections.DictionaryEntry de in parameters) sb.Append((string)de.Key + "=" + (string)de.Value + "\t"); if (sb.Length > 0) sb.Length--; } return fes.TestConnection(providername, sb.ToString()) ? "True" : "Unspecified errors"; } public override string TestConnection(string featuresource) { MgFeatureService fes = this.Con.CreateService(MgServiceType.FeatureService) as MgFeatureService; return fes.TestConnection(new MgResourceIdentifier(featuresource)) ? "True" : "Unspecified errors"; } public void DescribeSchema() { throw new MissingMethodException(); } public FdoProviderCapabilities GetProviderCapabilities(string provider) { MgFeatureService fes = this.Con.CreateService(MgServiceType.FeatureService) as MgFeatureService; return (FdoProviderCapabilities) base.DeserializeObject(typeof(FdoProviderCapabilities), Utility.MgStreamToNetStream(fes, fes.GetType().GetMethod("GetCapabilities"), new object[] { provider })); } public override System.IO.MemoryStream GetResourceData(string resourceID, string dataname) { MgResourceService res = this.Con.CreateService(MgServiceType.ResourceService) as MgResourceService; return Utility.MgStreamToNetStream(res, res.GetType().GetMethod("GetResourceData"), new object[] { new MgResourceIdentifier(resourceID), dataname }); } public override byte[] GetResourceXmlData(string resourceID) { MgResourceService res = this.Con.CreateService(MgServiceType.ResourceService) as MgResourceService; return Utility.MgStreamToNetStream(res, res.GetType().GetMethod("GetResourceContent"), new object[] { new MgResourceIdentifier(resourceID) }).ToArray(); } //public override FeatureProviderRegistryFeatureProvider GetFeatureProvider(string providername) //{ // MgFeatureService fes = this.Con.CreateService(MgServiceType.FeatureService) as MgFeatureService; // System.IO.MemoryStream ms = Utility.MgStreamToNetStream(fes, fes.GetType().GetMethod("GetCapabilities"), new object[] { providername }); // return (FeatureProviderRegistryFeatureProvider)DeserializeObject(typeof(FeatureProviderRegistryFeatureProvider), ms); //} public System.IO.Stream GetMapDWF(string resourceID) { throw new MissingMethodException(); } public override void SetResourceData(string resourceid, string dataname, OSGeo.MapGuide.MaestroAPI.ResourceDataType datatype, System.IO.Stream stream, Utility.StreamCopyProgressDelegate callback) { byte[] data = Utility.StreamAsArray(stream); if (callback != null) callback(0, data.Length, data.Length); MgResourceService res = this.Con.CreateService(MgServiceType.ResourceService) as MgResourceService; MgByteReader reader = new MgByteReader(data, data.Length, "binary/octet-stream"); res.SetResourceData(new MgResourceIdentifier(resourceid), dataname, datatype.ToString(), reader); if (callback != null) callback(data.Length, 0, data.Length); } public override void SetResourceXmlData(string resourceid, System.IO.Stream content, System.IO.Stream header) { MgResourceService res = this.Con.CreateService(MgServiceType.ResourceService) as MgResourceService; byte[] bufHeader = header == null ? new byte[0] : Utility.StreamAsArray(header); byte[] bufContent = content == null ? new byte[0] : Utility.StreamAsArray(content); MgByteReader rH = bufHeader.Length == 0 ? null : new MgByteReader(bufHeader, bufHeader.Length, "text/xml"); MgByteReader rC = bufContent.Length == 0 ? null : new MgByteReader(bufContent, bufContent.Length, "text/xml"); res.SetResource(new MgResourceIdentifier(resourceid), rC, rH); } public FeatureSetReader ExecuteSqlQuery(string featureSourceID, string sql) { MgFeatureService fes = this.Con.CreateService(MgServiceType.FeatureService) as MgFeatureService; MgSqlDataReader reader = fes.ExecuteSqlQuery(new MgResourceIdentifier(featureSourceID), sql); return new MgFeatureSetReader(reader); } public FeatureSetReader QueryFeatureSource(string resourceID, string schema, string query) { return QueryFeatureSource(resourceID, schema, query, null); } public FeatureSetReader QueryFeatureSource(string resourceID, string schema) { return QueryFeatureSource(resourceID, schema, null, null); } public FeatureSetReader QueryFeatureSource(string resourceID, string schema, string query, string[] columns) { return QueryFeatureSource(resourceID, schema, query, columns, null); } public FeatureSetReader QueryFeatureSource(string resourceID, string schema, string query, string[] columns, System.Collections.Specialized.NameValueCollection computedProperties) { MgFeatureService fes = this.Con.CreateService(MgServiceType.FeatureService) as MgFeatureService; MgFeatureQueryOptions mgf = new MgFeatureQueryOptions(); if (query != null) mgf.SetFilter(query); if (columns != null && columns.Length != 0) foreach(string s in columns) mgf.AddFeatureProperty(s); if (computedProperties != null && computedProperties.Count > 0) foreach (string s in computedProperties.Keys) mgf.AddComputedProperty(s, computedProperties[s]); MgReader mr = fes.SelectFeatures(new MgResourceIdentifier(resourceID), schema, mgf); return new MgFeatureSetReader(mr); } private FeatureSetReader AggregateQueryFeatureSourceCore(string resourceID, string schema, string query, string[] columns, System.Collections.Specialized.NameValueCollection computedProperties) { MgFeatureService fes = this.Con.CreateService(MgServiceType.FeatureService) as MgFeatureService; MgFeatureAggregateOptions mgf = new MgFeatureAggregateOptions(); if (query != null) mgf.SetFilter(query); if (columns != null && columns.Length != 0) foreach (string s in columns) mgf.AddFeatureProperty(s); if (computedProperties != null && computedProperties.Count > 0) foreach (string s in computedProperties.Keys) mgf.AddComputedProperty(s, computedProperties[s]); return new MgFeatureSetReader(fes.SelectAggregate(new MgResourceIdentifier(resourceID), schema, mgf)); } public override FeatureSetReader AggregateQueryFeatureSource(string resourceID, string schema, string filter, string[] columns) { return AggregateQueryFeatureSourceCore(resourceID, schema, filter, columns, null); } public override FeatureSetReader AggregateQueryFeatureSource(string resourceID, string schema, string filter, System.Collections.Specialized.NameValueCollection aggregateFunctions) { return AggregateQueryFeatureSourceCore(resourceID, schema, filter, null, aggregateFunctions); } public override FeatureSourceDescription DescribeFeatureSource(string resourceID) { MgFeatureService fes = this.Con.CreateService(MgServiceType.FeatureService) as MgFeatureService; System.IO.MemoryStream ms = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(fes.DescribeSchemaAsXml(new MgResourceIdentifier(resourceID), ""))); return new FeatureSourceDescription(ms); } public override FeatureSourceDescription DescribeFeatureSource(string resourceID, string schema) { MgFeatureService fes = this.Con.CreateService(MgServiceType.FeatureService) as MgFeatureService; if (schema != null && schema.IndexOf(":") > 0) schema = schema.Split(':')[0]; System.IO.MemoryStream ms = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(fes.DescribeSchemaAsXml(new MgResourceIdentifier(resourceID), schema))); return new FeatureSourceDescription(ms); } public override void CreateRuntimeMap(string resourceID, string mapdefinition) { string mapname = new ResourceIdentifier(resourceID).Path; MgResourceService res = this.Con.CreateService(MgServiceType.ResourceService) as MgResourceService; MgMap map = new MgMap(); map.Create(res, new MgResourceIdentifier(mapdefinition), mapname); map.Save(res, new MgResourceIdentifier(resourceID)); //Grrr... This does not happen automatically, even though it is required! MgSelection sel = new MgSelection(map); sel.Save(res, mapname); } void OSGeo.MapGuide.MaestroAPI.ServerConnectionI.CreateRuntimeMap(string resourceID, MapDefinition map) { ResourceIdentifier guid = new ResourceIdentifier(Guid.NewGuid().ToString(), ResourceTypes.MapDefinition, this.SessionID); try { SaveResourceAs(map, guid); CreateRuntimeMap(resourceID, guid); } finally { try { DeleteResource(guid); } catch { } } } void OSGeo.MapGuide.MaestroAPI.ServerConnectionI.CreateRuntimeMap(string resourceID, OSGeo.MapGuide.MaestroAPI.RuntimeClasses.RuntimeMap map) { if (!ResourceIdentifier.Validate(resourceID, ResourceTypes.RuntimeMap)) throw new ArgumentException("Invalid resourceId", "resourceID"); string selectionID = resourceID.Substring(0, resourceID.LastIndexOf(".")) + ".Selection"; SetResourceXmlData(resourceID, new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(HttpServerConnection.RUNTIMEMAP_XML))); SetResourceXmlData(selectionID, new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(HttpServerConnection.RUNTIMEMAP_SELECTION_XML))); System.IO.MemoryStream ms = new System.IO.MemoryStream(); BinarySerializer.MgBinarySerializer serializer = new BinarySerializer.MgBinarySerializer(ms, this.SiteVersion); RuntimeClasses.Selection sel = new RuntimeClasses.Selection(); sel.Serialize(serializer); ms.Position = 0; SetResourceData(selectionID, "RuntimeData", ResourceDataType.Stream, ms); SaveRuntimeMap(resourceID, map); } public void SaveRuntimeMap(string resourceID, RuntimeClasses.RuntimeMap map) { System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.IO.MemoryStream ms2 = null; //Apparently the name is used to reconstruct the resourceId rather than pass it around //inside the map server string r = map.Name; string t = map.ResourceID; string mapname = resourceID.Substring(resourceID.IndexOf("//") + 2); mapname = mapname.Substring(0, mapname.LastIndexOf(".")); map.Name = mapname; map.ResourceID = resourceID; try { map.Serialize(new BinarySerializer.MgBinarySerializer(ms, this.SiteVersion)); if (this.SiteVersion >= SiteVersions.GetVersion(KnownSiteVersions.MapGuideOS1_2)) { ms2 = new System.IO.MemoryStream(); map.SerializeLayerData(new BinarySerializer.MgBinarySerializer(ms2, this.SiteVersion)); } SetResourceData(resourceID, "RuntimeData", ResourceDataType.Stream, ms); if (ms2 != null) SetResourceData(resourceID, "LayerGroupData", ResourceDataType.Stream, ms2); if (map.HasLoadedSelectionXml) SetSelectionXml(resourceID, map.Selection.ToXml()); } finally { map.Name = r; map.ResourceID = t; } } public void DeleteResourceData(string resourceID, string dataname) { MgResourceService res = this.Con.CreateService(MgServiceType.ResourceService) as MgResourceService; res.DeleteResourceData(new MgResourceIdentifier(resourceID), dataname); } public ResourceDataList EnumerateResourceData(string resourceID) { MgResourceService res = this.Con.CreateService(MgServiceType.ResourceService) as MgResourceService; System.IO.MemoryStream ms = Utility.MgStreamToNetStream(res, res.GetType().GetMethod("EnumerateResourceData"), new object[] { new MgResourceIdentifier(resourceID) }); return (ResourceDataList)DeserializeObject(typeof(ResourceDataList), ms); } public override void DeleteResource(string resourceID) { MgResourceService res = this.Con.CreateService(MgServiceType.ResourceService) as MgResourceService; res.DeleteResource(new MgResourceIdentifier(resourceID)); } public void DeleteFolder(string folderPath) { if (!folderPath.EndsWith("/")) folderPath += "/"; MgResourceService res = this.Con.CreateService(MgServiceType.ResourceService) as MgResourceService; res.DeleteResource(new MgResourceIdentifier(folderPath)); } public RuntimeClasses.RuntimeMap GetRuntimeMap(string resourceID) { RuntimeClasses.RuntimeMap m = new RuntimeClasses.RuntimeMap(); m.Deserialize(new BinarySerializer.MgBinaryDeserializer(this.GetResourceData(resourceID, "RuntimeData"), this.SiteVersion)); if (this.SiteVersion >= SiteVersions.GetVersion(KnownSiteVersions.MapGuideOS1_2)) m.DeserializeLayerData(new BinarySerializer.MgBinaryDeserializer(this.GetResourceData(resourceID, "LayerGroupData"), this.SiteVersion)); m.CurrentConnection = this; return m; } public override Version SiteVersion { get { if (m_siteVersion != null) return m_siteVersion; try { MgSite site = m_con.GetSite(); MgServerAdmin amd = new MgServerAdmin(); amd.Open(new MgUserInformation(m_sessionId)); MgPropertyCollection col = amd.GetInformationProperties(); for (int i = 0; i < col.Count; i++) if (col[i].Name == "ServerVersion") { m_siteVersion = new Version(((MgStringProperty)col[i]).GetValue()); break; } } catch { } //Default if (m_siteVersion == null) m_siteVersion = SiteVersions.GetVersion(KnownSiteVersions.MapGuideOS1_2); return m_siteVersion; } } private ICoordinateSystemCatalog m_coordsys = null; //TODO: Figure out a strategy for cache invalidation public ICoordinateSystemCatalog CoordinateSystemCatalog { get { if (this.SiteVersion < OSGeo.MapGuide.MaestroAPI.SiteVersions.GetVersion(OSGeo.MapGuide.MaestroAPI.KnownSiteVersions.MapGuideOS1_2)) return null; else { if (m_coordsys == null) m_coordsys = new LocalNativeCoordinateSystemCatalog(this); return m_coordsys; } } } public string DisplayName { get { return this.Con.GetSite().GetCurrentSiteAddress(); } } public override ResourceReferenceList EnumerateResourceReferences(string resourceid) { MgResourceService res = this.Con.CreateService(MgServiceType.ResourceService) as MgResourceService; System.IO.MemoryStream ms = Utility.MgStreamToNetStream(res, res.GetType().GetMethod("EnumerateReferences"), new object[] { new MgResourceIdentifier(resourceid) }); return (ResourceReferenceList)DeserializeObject(typeof(ResourceReferenceList), ms); } public override void CopyResource(string oldpath, string newpath, bool overwrite) { MgResourceService res = this.Con.CreateService(MgServiceType.ResourceService) as MgResourceService; res.CopyResource(new MgResourceIdentifier(oldpath), new MgResourceIdentifier(newpath), overwrite); } public override void CopyFolder(string oldpath, string newpath, bool overwrite) { if (!oldpath.EndsWith("/")) oldpath += "/"; if (!newpath.EndsWith("/")) newpath += "/"; MgResourceService res = this.Con.CreateService(MgServiceType.ResourceService) as MgResourceService; res.CopyResource(new MgResourceIdentifier(oldpath), new MgResourceIdentifier(newpath), overwrite); } public override void MoveResource(string oldpath, string newpath, bool overwrite) { MgResourceService res = this.Con.CreateService(MgServiceType.ResourceService) as MgResourceService; res.MoveResource(new MgResourceIdentifier(oldpath), new MgResourceIdentifier(newpath), overwrite); } public override void MoveFolder(string oldpath, string newpath, bool overwrite) { if (!oldpath.EndsWith("/")) oldpath += "/"; if (!newpath.EndsWith("/")) newpath += "/"; MgResourceService res = this.Con.CreateService(MgServiceType.ResourceService) as MgResourceService; res.MoveResource(new MgResourceIdentifier(oldpath), new MgResourceIdentifier(newpath), overwrite); } public override System.IO.Stream RenderRuntimeMap(string resourceId, double x, double y, double scale, int width, int height, int dpi, string format, bool clip) { MgRenderingService rnd = this.Con.CreateService(MgServiceType.RenderingService) as MgRenderingService; MgResourceService res = this.Con.CreateService(MgServiceType.ResourceService) as MgResourceService; MgGeometryFactory gf = new MgGeometryFactory(); string mapname = new ResourceIdentifier(resourceId).Path; MgMap map = new MgMap(); map.Open(res, mapname); MgSelection sel = new MgSelection(map); //The color accepted by MgColor has alpha as the last value, but the returned has alpha first MgColor color = new MgColor(Utility.ParseHTMLColor(map.GetBackgroundColor())); //TODO: The render method is missing the overload for the Clip parameter object[] args = new object[] { map, sel, gf.CreateCoordinateXY(x, y), scale, width, height, color, format, true }; Type[] types = new Type[] { args[0].GetType(), args[1].GetType(), args[2].GetType(), args[3].GetType(), args[4].GetType(), args[5].GetType(), args[6].GetType(), args[7].GetType(), args[8].GetType() }; return Utility.MgStreamToNetStream(rnd, rnd.GetType().GetMethod("RenderMap", types), args); } public override System.IO.Stream RenderRuntimeMap(string resourceId, double x1, double y1, double x2, double y2, int width, int height, int dpi, string format, bool clip) { MgRenderingService rnd = this.Con.CreateService(MgServiceType.RenderingService) as MgRenderingService; MgResourceService res = this.Con.CreateService(MgServiceType.ResourceService) as MgResourceService; MgGeometryFactory gf = new MgGeometryFactory(); string mapname = new ResourceIdentifier(resourceId).Path; MgMap map = new MgMap(); map.Open(res, mapname); MgSelection sel = new MgSelection(map); //The color accepted by MgColor has alpha as the last value, but the returned has alpha first MgColor color = new MgColor(Utility.ParseHTMLColor(map.GetBackgroundColor())); MgEnvelope env = new MgEnvelope(gf.CreateCoordinateXY(x1, y1), gf.CreateCoordinateXY(x2, y2)); //TODO: The render is missing the clip param for the extent override method object[] args = new object[] { map, sel, env, width, height, color, format }; Type[] types = new Type[] { args[0].GetType(), args[1].GetType(), args[2].GetType(), args[3].GetType(), args[4].GetType(), args[5].GetType(), args[6].GetType() }; return Utility.MgStreamToNetStream(rnd, rnd.GetType().GetMethod("RenderMap", types), args); } public override bool IsSessionExpiredException(Exception ex) { return ex != null && ex.GetType() == typeof(OSGeo.MapGuide.MgSessionExpiredException) || ex.GetType() == typeof(OSGeo.MapGuide.MgSessionNotFoundException); } /// /// Returns the avalible application templates on the server /// /// The avalible application templates on the server public override ApplicationDefinitionTemplateInfoSet GetApplicationTemplates() { throw new MissingMethodException(); } /// /// Returns the avalible application widgets on the server /// /// The avalible application widgets on the server public override ApplicationDefinitionWidgetInfoSet GetApplicationWidgets() { throw new MissingMethodException(); } /// /// Returns the avalible widget containers on the server /// /// The avalible widget containers on the server public override ApplicationDefinitionContainerInfoSet GetApplicationContainers() { throw new MissingMethodException(); } /// /// Returns the spatial info for a given featuresource /// /// The ID of the resource to query /// Query only active items /// A list of spatial contexts public override FdoSpatialContextList GetSpatialContextInfo(string resourceID, bool activeOnly) { MgFeatureService fes = this.Con.CreateService(MgServiceType.FeatureService) as MgFeatureService; MgSpatialContextReader rd = fes.GetSpatialContexts(new MgResourceIdentifier(resourceID), activeOnly); return this.DeserializeObject(typeof(FdoSpatialContextList), Utility.MgStreamToNetStream(rd, rd.GetType().GetMethod("ToXml"), null)) as FdoSpatialContextList; } /// /// Gets the names of the identity properties from a feature /// /// The resourceID for the FeatureSource /// The classname of the feature, including schema /// A string array with the found identities public override string[] GetIdentityProperties(string resourceID, string classname) { MgFeatureService fes = this.Con.CreateService(MgServiceType.FeatureService) as MgFeatureService; string[] parts = classname.Split(':'); MgResourceIdentifier resId = new MgResourceIdentifier(resourceID); MgPropertyDefinitionCollection props; if (parts.Length == 1) parts = new string[] { classname }; else if (parts.Length != 2) throw new Exception("Unable to parse classname into class and schema: " + classname); foreach(MgClassDefinition cdef in fes.DescribeSchema(resId, parts[0])[0].GetClasses()) if (parts.Length == 1 || cdef.Name.ToLower().Trim().Equals(parts[1].ToLower().Trim())) { props = cdef.GetIdentityProperties(); string[] res = new string[props.Count]; for (int i = 0; i < props.Count; i++) res[i] = (props[i] as MgProperty).Name; return res; } throw new Exception("Unable to find class: " + parts[1] + " in schema " + parts[0]); } /// /// Restarts the server session, and creates a new session ID /// /// If set to true, the call throws an exception if the call failed /// True if the creation succeed, false otherwise public override bool RestartSession(bool throwException) { if (m_username == null || m_password == null) if (throwException) throw new Exception("Cannot recreate session, because connection was not opened with username and password"); else return false; try { MgUserInformation mgui = new MgUserInformation(m_username, m_password); if (m_locale != null) mgui.SetLocale(m_locale); else mgui.SetLocale("en"); MgSiteConnection con = new MgSiteConnection(); con.Open(mgui); string s = con.GetSite().CreateSession(); if (s == null || s.Trim().Length == 0) throw new Exception("Failed to retrieve new session identifier"); m_sessionId = s; m_con = con; return true; } catch { if (throwException) throw; else return false; } } /// /// Sets the selection of a map /// /// The resourceID of the runtime map /// The selection xml public override void SetSelectionXml(string runtimeMap, string selectionXml) { ResourceIdentifier.Validate(runtimeMap, ResourceTypes.RuntimeMap); MgResourceService res = this.Con.CreateService(MgServiceType.ResourceService) as MgResourceService; MgMap map = new MgMap(); string mapname = new ResourceIdentifier(runtimeMap).Path; map.Open(res, mapname); MgSelection sel = string.IsNullOrEmpty(selectionXml) ? new MgSelection(map) : new MgSelection(map, selectionXml); sel.Save(res, mapname); } /// /// Gets the selection from a map /// /// The resourceID of the runtime map /// The selection xml public override string GetSelectionXml(string runtimeMap) { MgResourceService res = this.Con.CreateService(MgServiceType.ResourceService) as MgResourceService; MgMap map = new MgMap(); string mapname = new ResourceIdentifier(runtimeMap).Path; map.Open(res, mapname); MgSelection sel = new MgSelection(map); return sel.ToXml(); } /// /// Enumerates all unmanaged folders, meaning alias'ed folders /// /// The type of data to return /// A filter applied to the items /// True if the list should contains recursive results /// The path to retrieve the data from /// A list of unmanaged data public override UnmanagedDataList EnumerateUnmanagedData(string startpath, string filter, bool recursive, UnmanagedDataTypes type) { throw new MissingMethodException(); } public override string QueryMapFeatures(string runtimemap, string wkt, bool persist, QueryMapFeaturesLayerAttributes attributes, bool raw) { MgRenderingService rs = this.Con.CreateService(MgServiceType.RenderingService) as MgRenderingService; MgResourceService res = this.Con.CreateService(MgServiceType.ResourceService) as MgResourceService; MgMap map = new MgMap(); string mapname = runtimemap.IndexOf(":") > 0 ? new ResourceIdentifier(runtimemap).Path : runtimemap; map.Open(res, mapname); MgWktReaderWriter r = new MgWktReaderWriter(); MgFeatureInformation info = rs.QueryFeatures(map, null, r.Read(wkt), (int)MgFeatureSpatialOperations.Intersects, "", -1, (int)attributes); string xml = System.Text.Encoding.UTF8.GetString(Utility.MgStreamToNetStream(info, info.GetType().GetMethod("ToXml"), null).ToArray()).Trim(); if (persist) { MgSelection sel = new MgSelection(map, xml); sel.Save(res, mapname); } return xml; } /// /// Upload a MapGuide Package file to the server /// /// Name of the file to upload /// A callback argument used to display progress. May be null. public override void UploadPackage(string filename, Utility.StreamCopyProgressDelegate callback) { System.IO.FileInfo fi = new System.IO.FileInfo(filename); if (callback != null) callback(0, fi.Length, fi.Length); MgResourceService res = this.Con.CreateService(MgServiceType.ResourceService) as MgResourceService; MgByteSource pkgSource = new MgByteSource(filename); MgByteReader rd = pkgSource.GetReader(); res.ApplyResourcePackage(rd); rd.Dispose(); if (callback != null) callback(fi.Length, 0, fi.Length); } public override void UpdateRepository(string resourceId, ResourceFolderHeaderType header) { MgResourceService res = this.Con.CreateService(MgServiceType.ResourceService) as MgResourceService; if (header == null) res.UpdateRepository(new MgResourceIdentifier(resourceId), null, null); else { byte[] data = this.SerializeObject(header).ToArray(); MgByteReader rd = new MgByteReader(data, data.Length, "text/xml"); res.UpdateRepository(new MgResourceIdentifier(resourceId), null, rd); } } public override object GetFolderOrResourceHeader(string resourceID) { MgResourceService res = this.Con.CreateService(MgServiceType.ResourceService) as MgResourceService; if (ResourceIdentifier.IsFolderResource(resourceID)) return this.DeserializeObject(Utility.MgStreamToNetStream(res, res.GetType().GetMethod("GetResourceHeader"), new object[] { new MgResourceIdentifier(resourceID) })); else return this.DeserializeObject(Utility.MgStreamToNetStream(res, res.GetType().GetMethod("GetResourceHeader"), new object[] { new MgResourceIdentifier(resourceID) })); } /// /// Gets a list of users in a group /// /// The group to retrieve the users from /// The list of users public override UserList EnumerateUsers(string group) { if (m_cachedUserList == null) m_cachedUserList = this.DeserializeObject(Utility.MgStreamToNetStream(this.Con.GetSite(), this.Con.GetSite().GetType().GetMethod("EnumerateUsers"), new object[] { group })); return m_cachedUserList; } /// /// Gets a list of all groups on the server /// /// The list of groups public override GroupList EnumerateGroups() { if (m_cachedGroupList == null) m_cachedGroupList = this.DeserializeObject(Utility.MgStreamToNetStream(this.Con.GetSite(), this.Con.GetSite().GetType().GetMethod("EnumerateGroups"), null)); return m_cachedGroupList; } public override System.IO.Stream GetTile(string mapdefinition, string baselayergroup, int col, int row, int scaleindex, string format) { MgTileService ts = this.Con.CreateService(MgServiceType.TileService) as MgTileService; Type[] types = new Type[] { typeof(MgResourceIdentifier), typeof(string), typeof(int), typeof(int), typeof(int) }; return Utility.MgStreamToNetStream(ts, ts.GetType().GetMethod("GetTile", types), new object[] { new MgResourceIdentifier(mapdefinition), baselayergroup, col, row, scaleindex }); //ts.GetTile(new MgResourceIdentifier(mapdefinition), baselayergroup, col, row, scaleindex) } public override bool ResourceExists(string resourceid) { try { MgResourceService res = this.Con.CreateService(MgServiceType.ResourceService) as MgResourceService; return res.ResourceExists(new MgResourceIdentifier(resourceid)); } catch (Exception ex) { try { return base.ResourceExists(resourceid); } catch { throw ex; } //Throw original error } } public string[] GetConnectionPropertyValues(string providerName, string propertyName, string partialConnectionString) { MgFeatureService featSvc = this.Con.CreateService(MgServiceType.FeatureService) as MgFeatureService; MgStringCollection result = featSvc.GetConnectionPropertyValues(providerName, propertyName, partialConnectionString); string[] values = new string[result.GetCount()]; for (int i = 0; i < result.GetCount(); i++) { values[i] = result.GetItem(i); } return values; } #endregion public bool SupportsResourcePreviews { get { return false; } } #region IDisposable Members public override void Dispose() { if (m_con != null) { m_con.Dispose(); m_con = null; } } /// /// Renders a minature bitmap of the layers style /// /// The scale for the bitmap to match /// The layer the image should represent /// If the layer is themed, this gives the theme index, otherwise set to 0 /// The geometry type, 1 for point, 2 for line, 3 for area, 4 for composite /// The minature bitmap public override System.Drawing.Image GetLegendImage(double scale, string layerdefinition, int themeIndex, int type) { MgMappingService ms = this.Con.CreateService(MgServiceType.MappingService) as MgMappingService; MgResourceIdentifier ldef = new MgResourceIdentifier(layerdefinition); return new System.Drawing.Bitmap(Utility.MgStreamToNetStream(ms, ms.GetType().GetMethod("GenerateLegendImage"), new object[] { ldef, scale, 16, 16, "PNG", type, themeIndex })); } #endregion } }