/// <summary> /// Validats the specified resources for common issues associated with this /// resource type /// </summary> /// <param name="context"></param> /// <param name="resource"></param> /// <param name="recurse"></param> /// <returns></returns> public ValidationIssue[] Validate(ResourceValidationContext context, IResource resource, bool recurse) { Check.ArgumentNotNull(context, nameof(context)); if (context.IsAlreadyValidated(resource.ResourceID)) { return(null); } if (resource.ResourceType != ResourceTypes.DrawingSource.ToString()) { return(null); } var issues = new List <ValidationIssue>(); IDrawingSource dws = (IDrawingSource)resource; if (string.IsNullOrEmpty(dws.SourceName)) { issues.Add(new ValidationIssue(resource, ValidationStatus.Error, ValidationStatusCode.Error_DrawingSource_NoSourceDwf, Strings.DS_NoSourceSpecified)); } if (string.IsNullOrEmpty(dws.CoordinateSpace)) { issues.Add(new ValidationIssue(resource, ValidationStatus.Information, ValidationStatusCode.Info_DrawingSource_NoCoordinateSpace, Strings.DS_NoCoordinateSpace)); } context.MarkValidated(resource.ResourceID); return(issues.ToArray()); }
public void DrawingSourceDeserializationWithFullContentModel() { IResource res = ObjectFactory.DeserializeXml(Properties.Resources.DrawingSource_1_0_0); Assert.NotNull(res); Assert.AreEqual(res.ResourceType, "DrawingSource"); Assert.AreEqual(res.ResourceVersion, new Version(1, 0, 0)); IDrawingSource ds = res as IDrawingSource; Assert.NotNull(ds); }
public void DrawingSourceDeserializationWithFullContentModel() { IResource res = ObjectFactory.DeserializeXml(Utils.ReadAllText($"Resources{System.IO.Path.DirectorySeparatorChar}DrawingSource_1_0_0.txt")); Assert.NotNull(res); Assert.Equal("DrawingSource", res.ResourceType); Assert.Equal(res.ResourceVersion, new Version(1, 0, 0)); IDrawingSource ds = res as IDrawingSource; Assert.NotNull(ds); }
public override void Bind(IEditorService service) { _edSvc = service; _edSvc.RegisterCustomNotifier(this); _dws = (IDrawingSource)service.GetEditedResource(); resDataCtrl.Init(service); resDataCtrl.DataListChanged += new EventHandler(OnResourceDataListChanged); resDataCtrl.ResourceDataMarked += new ResourceDataSelectionEventHandler(OnResourceDataMarked); TextBoxBinder.BindText(txtSourceCs, _dws, "CoordinateSpace"); //NOXLATE MarkSelected(); }
public override void Bind(IEditorService service) { _edSvc = service; _edSvc.RegisterCustomNotifier(this); _dws = (IDrawingSource)service.GetEditedResource(); resDataCtrl.Init(service); resDataCtrl.DataListChanged += new EventHandler(OnResourceDataListChanged); resDataCtrl.ResourceDataMarked += new ResourceDataSelectionEventHandler(OnResourceDataMarked); TextBoxBinder.BindText(txtSourceCs, _dws, nameof(_dws.CoordinateSpace)); MarkSelected(); }
private void ExtractSymbol(string targetFolder, IDrawingService drawSvc, IDrawingSource ds, ObjCommon.DrawingSectionListSection sect, ObjCommon.DrawingSectionResourceListSectionResource res) { using (var rs = drawSvc.GetSectionResource(ds.ResourceID, res.Href)) { using (Image img = Image.FromStream(rs)) { string targetId = targetFolder + sect.Title + "." + ResourceTypes.SymbolDefinition.ToString(); string dataName = sect.Title + "." + GetImageFormat(img.RawFormat); var symDef = Utility.CreateSimpleSymbol(_conn, sect.Title, "Image symbol definition extracted from a Symbol Library by Maestro"); //NOXLATE var imgGraphics = symDef.CreateImageGraphics(); symDef.AddGraphics(imgGraphics); imgGraphics.Item = symDef.CreateImageReference(string.Empty, Utility.FdoStringifiyLiteral(dataName)); //Empty resource id = self reference imgGraphics.SizeScalable = "True"; //NOXLATE imgGraphics.ResizeControl = Utility.FdoStringifiyLiteral("ResizeNone"); //NOXLATE imgGraphics.Angle = "0.0"; //NOXLATE imgGraphics.PositionX = "0.0"; //NOXLATE imgGraphics.PositionY = "4.0"; //NOXLATE imgGraphics.SizeX = PxToMillimeters(img.Width).ToString(CultureInfo.InvariantCulture); imgGraphics.SizeY = PxToMillimeters(img.Height).ToString(CultureInfo.InvariantCulture); symDef.PointUsage = symDef.CreatePointUsage(); symDef.PointUsage.Angle = "%ROTATION_ANGLE%"; //NOXLATE var rotParam = symDef.CreateParameter(); rotParam.DataType = "String"; //NOXLATE rotParam.Identifier = "ROTATION_ANGLE"; //NOXLATE rotParam.DisplayName = "Angle to rotate symbol"; //NOXLATE rotParam.DefaultValue = "0.0"; //NOXLATE symDef.ParameterDefinition.AddParameter(rotParam); _conn.ResourceService.SaveResourceAs(symDef, targetId); using (var ms = new MemoryStream()) { img.Save(ms, ImageFormat.Png); ms.Position = 0L; //Rewind _conn.ResourceService.SetResourceData(targetId, dataName, ObjCommon.ResourceDataType.File, ms); } Trace.TraceInformation("Extracted symbol: " + targetId); } } }
/// <summary> /// Extracts the specified symbols to the given folder /// </summary> /// <param name="targetFolder"></param> /// <param name="symbols"></param> /// <param name="progressCallback"></param> public void ExtractSymbols(string targetFolder, IEnumerable <string> symbols, Action <int, int> progressCallback) { Check.ArgumentNotEmpty(targetFolder, nameof(targetFolder)); Check.ThatArgumentIsFolder(targetFolder, nameof(targetFolder)); if (symbols == null) { ExtractSymbols(targetFolder); } else { IDrawingService drawSvc = (IDrawingService)_conn.GetService((int)ServiceType.Drawing); IDrawingSource ds = PrepareSymbolDrawingSource(_conn, _symbolLibId); //Each section in the symbols.dwf represents a symbol var sectionList = drawSvc.EnumerateDrawingSections(ds.ResourceID); var symbolNames = new HashSet <string>(symbols); int processed = 0; foreach (var sect in sectionList.Section) { var sectResources = drawSvc.EnumerateDrawingSectionResources(ds.ResourceID, sect.Name); if (!symbolNames.Contains(sect.Title)) { continue; } foreach (var res in sectResources.SectionResource) { if (res.Role.ToUpper() == StringConstants.Thumbnail.ToUpper()) { ExtractSymbol(targetFolder, drawSvc, ds, sect, res); processed++; if (progressCallback != null) { progressCallback(processed, symbolNames.Count); } } } } } }
/// <summary> /// Regenerates the sheet list in this drawing source. /// </summary> /// <param name="source">The drawing source</param> /// <param name="conn">The server connection</param> /// <returns>True if sheets were regenerated. False otherwise</returns> public static bool RegenerateSheetList(this IDrawingSource source, IServerConnection conn) { Check.ArgumentNotNull(source, nameof(source)); Check.ArgumentNotNull(conn, nameof(conn)); Check.ArgumentNotEmpty(source.ResourceID, $"{nameof(source)}.{nameof(source.ResourceID)}"); IDrawingService dwSvc = (IDrawingService)conn.GetService((int)ServiceType.Drawing); var sheets = dwSvc.EnumerateDrawingSections(source.ResourceID); bool bRegen = sheets.Section.Count > 0; source.RemoveAllSheets(); if (bRegen) { foreach (var sht in sheets.Section) { source.AddSheet(source.CreateSheet(sht.Name, 0, 0, 0, 0)); } } return(bRegen); }
/// <summary> /// Regenerates the sheet list in this drawing source. /// </summary> /// <param name="source"></param> /// <returns>True if sheets were regenerated. False otherwise</returns> public static bool RegenerateSheetList(this IDrawingSource source) { Check.NotNull(source, "source"); Check.NotNull(source.CurrentConnection, "source.CurrentConection"); //NOXLATE Check.NotEmpty(source.ResourceID, "source.ResourceID"); //NOXLATE IDrawingService dwSvc = (IDrawingService)source.CurrentConnection.GetService((int)ServiceType.Drawing); var sheets = dwSvc.EnumerateDrawingSections(source.ResourceID); bool bRegen = sheets.Section.Count > 0; source.RemoveAllSheets(); if (bRegen) { foreach (var sht in sheets.Section) { source.AddSheet(source.CreateSheet(sht.Name, 0, 0, 0, 0)); } } return(bRegen); }
/// <summary> /// Creates an image-based Symbol Definition in the specified folder for each image symbol in the Symbol Library. /// /// Any existing resource names are overwritten /// </summary> /// <param name="targetFolder"></param> public void ExtractSymbols(string targetFolder) { Check.ArgumentNotEmpty(targetFolder, nameof(targetFolder)); Check.ThatPreconditionIsMet(ResourceIdentifier.IsFolderResource(targetFolder), $"{nameof(ResourceIdentifier)}.{nameof(ResourceIdentifier.IsFolderResource)}({nameof(targetFolder)})"); IDrawingService drawSvc = (IDrawingService)_conn.GetService((int)ServiceType.Drawing); IDrawingSource ds = PrepareSymbolDrawingSource(_conn, _symbolLibId); //Each section in the symbols.dwf represents a symbol var sectionList = drawSvc.EnumerateDrawingSections(ds.ResourceID); foreach (var sect in sectionList.Section) { var sectResources = drawSvc.EnumerateDrawingSectionResources(ds.ResourceID, sect.Name); foreach (var res in sectResources.SectionResource) { if (res.Role.ToUpper() == StringConstants.Thumbnail.ToUpper()) { ExtractSymbol(targetFolder, drawSvc, ds, sect, res); } } } }
private void btnUpload_Click(object sender, EventArgs e) { if (!File.Exists(txtDwfPath.Text)) { MessageBox.Show("File does not exist"); return; } // Create a MapGuide Drawing Source and store it in the session repository // The DWF file we upload must be the same name as the SourceName property // in the DrawingSource and the resource data name that we are uploading as IDrawingSource ds = ObjectFactory.CreateDrawingSource(); ds.SourceName = Path.GetFileName(txtDwfPath.Text); string resId = "Session:" + _conn.SessionID + "//InspectedDwf.DrawingSource"; _conn.ResourceService.SaveResourceAs(ds, resId); _conn.ResourceService.SetResourceData(resId, ds.SourceName, OSGeo.MapGuide.ObjectModels.Common.ResourceDataType.File, File.OpenRead(txtDwfPath.Text)); txtDrawingSource.Text = resId; rdDrawingSource.Checked = true; }
/// <summary> /// Perform base validation logic /// </summary> /// <param name="context"></param> /// <param name="resource"></param> /// <param name="recurse"></param> /// <returns></returns> protected ValidationIssue[] ValidateBase(ResourceValidationContext context, IResource resource, bool recurse) { Check.ArgumentNotNull(context, nameof(context)); if (context.IsAlreadyValidated(resource.ResourceID)) { return(null); } var ldef = resource as ILayerDefinition; var vldef = ldef.SubLayer as IVectorLayerDefinition; var gldef = ldef.SubLayer as IRasterLayerDefinition; var dldef = ldef.SubLayer as IDrawingLayerDefinition; List <ValidationIssue> issues = new List <ValidationIssue>(); if (ldef.SubLayer == null) { issues.Add(new ValidationIssue(resource, ValidationStatus.Error, ValidationStatusCode.Error_LayerDefinition_LayerNull, Strings.LDF_LayerNullError)); } ClassDefinition cls = null; if (vldef != null || gldef != null) { //Load referenced feature source IFeatureSource fs = null; try { fs = (IFeatureSource)context.GetResource(ldef.SubLayer.ResourceId); } catch (Exception) { issues.Add(new ValidationIssue(resource, ValidationStatus.Error, ValidationStatusCode.Error_LayerDefinition_FeatureSourceLoadError, string.Format(Strings.LDF_FeatureSourceLoadError))); } if (fs != null) { //Verify specified feature class and geometry check out try { string qualClassName = vldef == null ? gldef.FeatureName : vldef.FeatureName; string geometry = vldef == null ? gldef.Geometry : vldef.Geometry; bool foundSchema = false; bool foundGeometry = false; cls = this.Connection.FeatureService.GetClassDefinition(fs.ResourceID, qualClassName); if (cls != null) { foundSchema = true; foreach (PropertyDefinition col in cls.Properties) { if (col.Name == geometry) { foundGeometry = true; break; } } if (vldef != null && vldef.PropertyMapping != null) { foreach (INameStringPair s in vldef.PropertyMapping) { bool found = false; foreach (PropertyDefinition col in cls.Properties) { if (col.Name == s.Name) { found = true; break; } } if (!found) { issues.Add(new ValidationIssue(resource, ValidationStatus.Error, ValidationStatusCode.Error_LayerDefinition_InvalidPropertyMapping, string.Format(Strings.LDF_InvalidPropertyMapping, s.Name, qualClassName))); } } } } if (!foundSchema) { issues.Add(new ValidationIssue(resource, ValidationStatus.Error, ValidationStatusCode.Error_LayerDefinition_ClassNotFound, string.Format(Strings.LDF_SchemaMissingError, qualClassName, fs.ResourceID))); } else if (!foundGeometry) { issues.Add(new ValidationIssue(resource, ValidationStatus.Error, ValidationStatusCode.Error_LayerDefinition_GeometryNotFound, string.Format(Strings.LDF_GeometryMissingError, geometry, qualClassName, fs.ResourceID))); } } catch (Exception ex) { issues.Add(new ValidationIssue(fs, ValidationStatus.Error, ValidationStatusCode.Error_LayerDefinition_Generic, string.Format(Strings.LDF_SchemaAndColumnReadFailedError, ex.ToString()))); } if (recurse) { issues.AddRange(ResourceValidatorSet.Validate(context, fs, recurse)); } } } if (vldef != null) { if (string.IsNullOrEmpty(vldef.FeatureName)) { issues.Add(new ValidationIssue(resource, ValidationStatus.Error, ValidationStatusCode.Error_LayerDefinition_MissingFeatureName, Strings.LDF_MissingFeatureSourceError)); } if (string.IsNullOrEmpty(vldef.Geometry)) { issues.Add(new ValidationIssue(resource, ValidationStatus.Error, ValidationStatusCode.Error_LayerDefinition_MissingGeometry, Strings.LDF_MissingGeometryError)); } if (vldef.VectorScaleRange == null || !vldef.HasVectorScaleRanges()) { issues.Add(new ValidationIssue(resource, ValidationStatus.Error, ValidationStatusCode.Error_LayerDefinition_MissingScaleRanges, Strings.LDF_MissingScaleRangesError)); } else { //Test for overlapping scale ranges List <KeyValuePair <double, double> > ranges = new List <KeyValuePair <double, double> >(); foreach (IVectorScaleRange vsr in vldef.VectorScaleRange) { IVectorScaleRange2 vsr2 = vsr as IVectorScaleRange2; if (vsr2 != null) { var area = vsr2.AreaStyle; var line = vsr2.LineStyle; var point = vsr2.PointStyle; if (vsr2.CompositeStyleCount > 0 && (area != null || line != null || point != null)) { issues.Add(new ValidationIssue(resource, ValidationStatus.Warning, ValidationStatusCode.Warning_LayerDefinition_CompositeStyleDefinedAlongsideBasicStyle, string.Format( Strings.LDF_CompositeStyleDefinedAlongsideBasicStyle, vsr2.MinScale.HasValue ? vsr2.MinScale.Value : 0, vsr2.MaxScale.HasValue ? vsr2.MaxScale.Value.ToString() : Strings.Infinity))); } if (vsr2.CompositeStyleCount > 0) { foreach (var cs in vsr2.CompositeStyle) { foreach (var cr in cs.CompositeRule) { if (cr.CompositeSymbolization != null) { foreach (var si in cr.CompositeSymbolization.SymbolInstance) { //verify that symbol references point to valid symbol definitions if (si.Reference.Type == SymbolInstanceType.Reference) { var symRef = (ISymbolInstanceReferenceLibrary)si.Reference; if (!context.ResourceExists(symRef.ResourceId)) { issues.Add(new ValidationIssue(resource, ValidationStatus.Error, ValidationStatusCode.Error_LayerDefinition_SymbolDefintionReferenceNotFound, string.Format( Strings.LDF_SymbolDefintionReferenceNotFound, symRef.ResourceId))); } if (cls != null) { //warn if the symbol definition has usage contexts that are irrelevant against the layer's feature source var prop = cls.FindProperty(vldef.Geometry) as GeometricPropertyDefinition; if (prop != null) { var gtypes = new List <FeatureGeometricType>(prop.GetIndividualGeometricTypes()); var sym = context.GetResource(symRef.ResourceId) as ISimpleSymbolDefinition; if (sym != null) { if (sym.LineUsage != null && !gtypes.Contains(FeatureGeometricType.Curve)) { issues.Add(new ValidationIssue(resource, ValidationStatus.Information, ValidationStatusCode.Info_LayerDefinition_IrrelevantUsageContext, string.Format( Strings.LDF_IrrelevantUsageContext, symRef.ResourceId, FeatureGeometricType.Curve.ToString()))); } if (sym.AreaUsage != null && !gtypes.Contains(FeatureGeometricType.Surface)) { issues.Add(new ValidationIssue(resource, ValidationStatus.Information, ValidationStatusCode.Info_LayerDefinition_IrrelevantUsageContext, string.Format( Strings.LDF_IrrelevantUsageContext, symRef.ResourceId, FeatureGeometricType.Surface.ToString()))); } if (sym.PointUsage != null && !gtypes.Contains(FeatureGeometricType.Point)) { issues.Add(new ValidationIssue(resource, ValidationStatus.Information, ValidationStatusCode.Info_LayerDefinition_IrrelevantUsageContext, string.Format( Strings.LDF_IrrelevantUsageContext, symRef.ResourceId, FeatureGeometricType.Point.ToString()))); } } } } } //verify that the overrides specified are for symbol parameters that actually exist if (si.ParameterOverrides.Count > 0) { if (si.Reference.Type == SymbolInstanceType.Reference) { var symRef = (ISymbolInstanceReferenceLibrary)si.Reference; var sym = (ISymbolDefinitionBase)context.GetResource(symRef.ResourceId); var paramList = new Dictionary <string, IParameter>(); foreach (var p in sym.GetParameters()) { paramList[p.Identifier] = p; } foreach (var ov in si.ParameterOverrides.Override) { if (!paramList.ContainsKey(ov.ParameterIdentifier)) { issues.Add(new ValidationIssue(resource, ValidationStatus.Warning, ValidationStatusCode.Warning_LayerDefinition_SymbolParameterOverrideToNonExistentParameter, string.Format( Strings.LDF_SymbolParameterOverrideToNonExistentParameter, symRef.ResourceId, ov.ParameterIdentifier))); } } } } } } } } } } ranges.Add(new KeyValuePair <double, double>( vsr.MaxScale.HasValue ? vsr.MaxScale.Value : double.PositiveInfinity, vsr.MinScale.HasValue ? vsr.MinScale.Value : double.NegativeInfinity)); } double min = double.PositiveInfinity; double max = double.NegativeInfinity; foreach (KeyValuePair <double, double> sr in ranges) { min = Math.Min(min, sr.Value); max = Math.Max(max, sr.Key); if (sr.Key < sr.Value) { issues.Add(new ValidationIssue(resource, ValidationStatus.Error, ValidationStatusCode.Error_LayerDefinition_MinMaxScaleSwapped, string.Format(Strings.LDF_MinAndMaxScaleSwappedError, sr.Value, sr.Key))); } } ranges.Sort(CompareScales); //TODO: Detect gaps in scale ranges for (int i = 0; i < ranges.Count; i++) { for (int j = i + 1; j < ranges.Count; j++) { if (ranges[i].Key > ranges[j].Value || ranges[i].Value > ranges[j].Value) { issues.Add(new ValidationIssue(resource, ValidationStatus.Information, ValidationStatusCode.Info_LayerDefinition_ScaleRangeOverlap, string.Format(Strings.LDF_ScaleRangesOverlapInformation, ranges[i].Value, ranges[i].Key, ranges[j].Value, ranges[j].Key))); } } } } } else if (gldef != null) { if (string.IsNullOrEmpty(gldef.FeatureName)) { issues.Add(new ValidationIssue(resource, ValidationStatus.Error, ValidationStatusCode.Error_LayerDefinition_MissingFeatureName, Strings.LDF_MissingFeatureSourceError)); } if (string.IsNullOrEmpty(gldef.Geometry)) { issues.Add(new ValidationIssue(resource, ValidationStatus.Error, ValidationStatusCode.Error_LayerDefinition_MissingGeometry, Strings.LDF_MissingGeometryError)); } if (gldef.GridScaleRange == null || gldef.GridScaleRangeCount == 0) { issues.Add(new ValidationIssue(resource, ValidationStatus.Error, ValidationStatusCode.Error_LayerDefinition_NoGridScaleRanges, Strings.LDF_MissingScaleRangesError)); } else if (gldef.GridScaleRangeCount != 1) { issues.Add(new ValidationIssue(resource, ValidationStatus.Warning, ValidationStatusCode.Warning_LayerDefinition_MultipleGridScaleRanges, Strings.LDF_MultipleScaleRangesWarning)); } } else if (dldef != null) { IDrawingSource dws = null; try { dws = (IDrawingSource)context.GetResource(dldef.ResourceId); } catch (Exception) { issues.Add(new ValidationIssue(resource, ValidationStatus.Error, ValidationStatusCode.Error_LayerDefinition_DrawingSourceError, Strings.LDF_DrawingSourceError)); } if (dws != null) { if (Array.IndexOf(this.Connection.Capabilities.SupportedServices, (int)ServiceType.Drawing) >= 0) { var dwSvc = (IDrawingService)this.Connection.GetService((int)ServiceType.Drawing); //Check if specified section exists var shtList = dwSvc.EnumerateDrawingSections(dws.ResourceID); DrawingSectionListSection sheet = null; foreach (var sht in shtList.Section) { if (sht.Name.Equals(dldef.Sheet)) { sheet = sht; break; } } if (sheet == null) { issues.Add(new ValidationIssue(resource, ValidationStatus.Error, ValidationStatusCode.Error_LayerDefinition_DrawingSourceSheetNotFound, string.Format(Strings.LDF_SheetNotFound, dldef.Sheet))); } else { //null or empty filter means all layers, in that case do nothing if (!string.IsNullOrEmpty(dldef.LayerFilter)) { //Check if specified layers all exist in specified section var specifiedLayers = dldef.LayerFilter.Split(','); //NOXLATE var dwLayers = new Dictionary <string, string>(); var shtLayers = dwSvc.EnumerateDrawingLayers(dws.ResourceID, sheet.Name); foreach (var sl in shtLayers) { dwLayers.Add(sl, sl); } foreach (var sl in specifiedLayers) { if (!dwLayers.ContainsKey(sl.Trim())) { issues.Add(new ValidationIssue(resource, ValidationStatus.Error, ValidationStatusCode.Error_LayerDefinition_DrawingSourceSheetLayerNotFound, string.Format(Strings.LDF_SheetLayerNotFound, sl.Trim(), sheet.Name))); } } } } } if (recurse) { issues.AddRange(ResourceValidatorSet.Validate(context, dws, recurse)); } } } else { issues.Add(new ValidationIssue(resource, ValidationStatus.Warning, ValidationStatusCode.Warning_LayerDefinition_UnsupportedLayerType, Strings.LDF_UnsupportedLayerTypeWarning)); } context.MarkValidated(resource.ResourceID); return(issues.ToArray()); }
/// <summary> /// Updates the extents of all sheets based on their respective AutoCAD Viewport Data in the embedded PIA resource /// </summary> /// <param name="source">The drawing source</param> /// <param name="conn">The server connection</param> public static void UpdateExtents(this IDrawingSource source, IServerConnection conn) { Check.ArgumentNotNull(source, nameof(source)); Check.ArgumentNotNull(conn, nameof(conn)); Check.ArgumentNotEmpty(source.ResourceID, $"{nameof(source)}.{nameof(source.ResourceID)}"); //Need drawing service if (Array.IndexOf(conn.Capabilities.SupportedServices, (int)ServiceType.Drawing) < 0) { throw new NotSupportedException(string.Format(OSGeo.MapGuide.MaestroAPI.Strings.ERR_SERVICE_NOT_SUPPORTED, ServiceType.Drawing.ToString())); } var drawSvc = (IDrawingService)conn.GetService((int)ServiceType.Drawing); foreach (var sht in source.Sheet) { var list = drawSvc.EnumerateDrawingSectionResources(source.ResourceID, sht.Name); foreach (var res in list.SectionResource) { if (res.Role == "AutoCAD Viewport Data") //NOXLATE { using (var stream = drawSvc.GetSectionResource(source.ResourceID, res.Href)) { //This is text content using (var sr = new StreamReader(stream)) { try { string content = sr.ReadToEnd(); //Viewport parameters are: // // llx // lly // urx // ury // //A the first space after each number of each parameter marks the end of that value // 4 - length of "llx=" int idx = content.IndexOf("llx") + 4; //NOXLATE string sllx = content.Substring(idx, content.IndexOf(" ", idx) - idx); //NOXLATE // 4 - length of "lly=" idx = content.IndexOf("lly") + 4; //NOXLATE string slly = content.Substring(idx, content.IndexOf(" ", idx) - idx); //NOXLATE // 4 - length of "urx=" idx = content.IndexOf("urx") + 4; //NOXLATE string surx = content.Substring(idx, content.IndexOf(" ", idx) - idx); //NOXLATE // 4 - length of "ury=" idx = content.IndexOf("ury") + 4; //NOXLATE string sury = content.Substring(idx, content.IndexOf(" ", idx) - idx); //NOXLATE //Update extents sht.Extent = ObjectFactory.CreateEnvelope( Convert.ToDouble(sllx), Convert.ToDouble(slly), Convert.ToDouble(surx), Convert.ToDouble(sury)); } catch { } } } } } } }
private string[] ExecuteBaseProcedure(LengthyOperationProgressCallBack cb, IBaseLoadProcedure proc, ref bool firstExecution) { List <string> resCreatedOrUpdated = new List <string>(); var files = proc.SourceFile; int pcPerFile = (int)(100 / files.Count); int current = 0; string root = proc.RootPath; if (!root.EndsWith("/")) //NOXLATE { root += "/"; //NOXLATE } string sdp = proc.SpatialDataSourcesPath; string lp = proc.LayersPath; if (!string.IsNullOrEmpty(sdp)) { if (!sdp.EndsWith("/")) //NOXLATE { sdp += "/"; //NOXLATE } } if (!string.IsNullOrEmpty(lp)) { if (!lp.EndsWith("/")) //NOXLATE { lp += "/"; //NOXLATE } } string fsRoot = (string.IsNullOrEmpty(sdp) ? root : sdp) + proc.SpatialDataSourcesFolder; string layerRoot = (string.IsNullOrEmpty(lp) ? root : lp) + proc.LayersFolder; if (!fsRoot.EndsWith("/")) //NOXLATE { fsRoot += "/"; //NOXLATE } if (!layerRoot.EndsWith("/")) //NOXLATE { layerRoot += "/"; //NOXLATE } List <string> resToUpdate = new List <string>(); if (proc.ResourceId != null && proc.ResourceId.Count > 0) { resToUpdate.AddRange(proc.ResourceId); firstExecution = false; } else { firstExecution = true; } foreach (string file in files) { bool success = false; if (System.IO.File.Exists(file)) { //GOTCHA: We are assuming these SDF files are not SDF2 files. This is //because there is no multi-platform solution to convert SDF2 files to SDF3 string resName = System.IO.Path.GetFileNameWithoutExtension(file); string dataName = System.IO.Path.GetFileName(file); string dsId = fsRoot + resName + ".DrawingSource"; //NOXLATE string fsId = fsRoot + resName + ".FeatureSource"; //NOXLATE string lyrId = layerRoot + resName + ".LayerDefinition"; //NOXLATE if (proc.GenerateSpatialDataSources) { //Skip only if we have an update list and this resource id is not in it bool skip = (resToUpdate.Count > 0 && !resToUpdate.Contains(fsId)); if (!skip) { if (proc.Type == LoadType.Dwf) { //Process is as follows: // // 1. Create and save drawing source document. // 2. Upload dwf file as resource data for this document. //Step 1: Create and save drawing source document. IDrawingSource ds = ObjectFactory.CreateDrawingSource(); ds.SourceName = dataName; ds.CoordinateSpace = proc.CoordinateSystem; ds.ResourceID = dsId; this.Parent.ResourceService.SaveResource(ds); resCreatedOrUpdated.Add(dsId); cb(this, new LengthyOperationProgressArgs(string.Format(Strings.TemplateCreated, dsId), current)); //Step 2: Load resource data for document this.Parent.ResourceService.SetResourceData(dsId, dataName, ResourceDataType.File, System.IO.File.OpenRead(file)); cb(this, new LengthyOperationProgressArgs(string.Format(Strings.TemplateLoaded, file), current)); ds.RegenerateSheetList(this.Parent); this.Parent.ResourceService.SaveResource(ds); ds.UpdateExtents(this.Parent); this.Parent.ResourceService.SaveResource(ds); } else { //Process is as follows: // // 1. Create and save feature source document. // 2. Upload sdf file as resource data for this document. // 3. Test the connection, it should check out. // 4. If no spatial contexts are detected, assign a default one from the load procedure and save the modified feature source. //Step 1: Create feature source document string provider = "OSGeo.SDF"; //NOXLATE switch (proc.Type) { case LoadType.Sqlite: provider = "OSGeo.SQLite"; //NOXLATE break; } var conp = new NameValueCollection(); conp["File"] = StringConstants.MgDataFilePath + dataName; var fs = ObjectFactory.CreateFeatureSource(provider, conp); fs.ResourceID = fsId; this.Parent.ResourceService.SaveResource(fs); resCreatedOrUpdated.Add(fsId); cb(this, new LengthyOperationProgressArgs(string.Format(Strings.TemplateCreated, fsId), current)); //TODO: When the infrastructure is available to us (ie. A portable .net FDO/MG Feature Service API wrapper) //Maybe then we can actually implement the generalization and duplicate record handling properties. Until then, we skip //these options //Step 2: Load resource data for document this.Parent.ResourceService.SetResourceData(fsId, dataName, ResourceDataType.File, System.IO.File.OpenRead(file)); cb(this, new LengthyOperationProgressArgs(string.Format(Strings.TemplateCreated, file), current)); //Step 3: Test to make sure we're all good so far string result = this.Parent.FeatureService.TestConnection(fsId); //LocalNativeConnection returns this string, so I'm assuming this is the "success" result if (result == "No errors" || result.ToLower() == "true") //NOXLATE { //Step 4: Test to see if default cs needs to be specified FdoSpatialContextList spatialContexts = this.Parent.FeatureService.GetSpatialContextInfo(fsId, false); if (!string.IsNullOrEmpty(proc.CoordinateSystem)) { //Case 1: No spatial contexts. Register one using SupplementalContextInfo if (spatialContexts.SpatialContext.Count == 0) { //Register the default CS from the load procedure fs.AddSpatialContextOverride(new OSGeo.MapGuide.ObjectModels.FeatureSource.v1_0_0.SpatialContextType() { Name = "Default", //NOXLATE CoordinateSystem = proc.CoordinateSystem }); //Update this feature source this.Parent.ResourceService.SaveResource(fs); cb(this, new LengthyOperationProgressArgs(string.Format(Strings.TemplateSetSpatialContext, fsId), current)); } else if (spatialContexts.SpatialContext.Count == 1) //Case 2: One spatial context, but its WKT is blank. Override using SupplementalContextInfo { var sc = spatialContexts.SpatialContext[0]; if (string.IsNullOrEmpty(sc.CoordinateSystemWkt)) { //Register the default CS from the load procedure fs.AddSpatialContextOverride(new OSGeo.MapGuide.ObjectModels.FeatureSource.v1_0_0.SpatialContextType() { Name = sc.Name, CoordinateSystem = proc.CoordinateSystem }); //Update this feature source this.Parent.ResourceService.SaveResource(fs); cb(this, new LengthyOperationProgressArgs(string.Format(Strings.TemplateSetSpatialContext, fsId), current)); } } } } } } } if (proc.GenerateLayers) { //Skip only if we have an update list and this resource id is not in it bool skip = (resToUpdate.Count > 0 && !resToUpdate.Contains(lyrId)); if (!skip) { if (proc.Type == LoadType.Dwf) { //Process is as follows // // 1. Enumerate the sheets on the drawing source // 2. Set the referenced sheet to the first known sheet var dwSvc = (IDrawingService)Parent.GetService((int)ServiceType.Drawing); var list = dwSvc.EnumerateDrawingSections(dsId); if (list.Section.Count > 0) { //Create drawing layer var ld = ObjectFactory.CreateDefaultLayer(LayerType.Drawing, new Version(1, 0, 0)); var dl = ld.SubLayer as IDrawingLayerDefinition; dl.ResourceId = dsId; //Use the first one dl.Sheet = list.Section[0].Name; ld.ResourceID = lyrId; this.Parent.ResourceService.SaveResource(ld); resCreatedOrUpdated.Add(lyrId); cb(this, new LengthyOperationProgressArgs(string.Format(Strings.TemplateCreated, lyrId), current)); } } else { //NOTE: Because we are working against 1.0.0 object types this will always create 1.0.0 Layer Definition //resources //Process is as follows // // 1. Describe the schema of the feature source // 2. If it contains at least one feature class, create a layer definition // 3. Set the following layer definition properties: // - Feature Source: the feature source id // - Feature Class: the first feature class in the schema // - Geometry: the first geometry property in the first feature class // 4. Infer the supported geometry types for this feature class. Toggle supported styles accordingly. //Step 1: Describe the schema // //NOTE: I think we can get away with the full schema walk here. It's very unlikely we will be uploading a flat //file with hundreds of classes. Even then, flat-file schema walk performance blows RDBMS walking performance //out of the water anyway. FeatureSourceDescription desc = this.Parent.FeatureService.DescribeFeatureSource(fsId); if (desc.HasClasses()) { //Step 2: Find the first feature class with a geometry property ClassDefinition clsDef = null; GeometricPropertyDefinition geom = null; bool done = false; foreach (ClassDefinition cls in desc.AllClasses) { if (done) { break; } foreach (PropertyDefinition prop in cls.Properties) { if (done) { break; } if (prop.Type == OSGeo.MapGuide.MaestroAPI.Schema.PropertyDefinitionType.Geometry) { clsDef = cls; geom = (GeometricPropertyDefinition)prop; done = true; } } } if (clsDef != null && geom != null) { var ld = ObjectFactory.CreateDefaultLayer(LayerType.Vector, new Version(1, 0, 0)); //Step 3: Assign default properties ld.ResourceID = lyrId; var vld = ld.SubLayer as IVectorLayerDefinition; vld.ResourceId = fsId; vld.FeatureName = clsDef.QualifiedName; vld.Geometry = geom.Name; //Step 4: Infer geometry storage support and remove unsupported styles var geomTypes = geom.GetIndividualGeometricTypes(); var scale = vld.GetScaleRangeAt(0); var remove = new List <string>(); if (Array.IndexOf(geomTypes, FeatureGeometricType.Point) < 0) { remove.Add(FeatureGeometricType.Point.ToString().ToLower()); } if (Array.IndexOf(geomTypes, FeatureGeometricType.Curve) < 0) { remove.Add(FeatureGeometricType.Curve.ToString().ToLower()); } if (Array.IndexOf(geomTypes, FeatureGeometricType.Surface) < 0) { remove.Add(FeatureGeometricType.Surface.ToString().ToLower()); } scale.RemoveStyles(remove); this.Parent.ResourceService.SaveResource(ld); resCreatedOrUpdated.Add(lyrId); cb(this, new LengthyOperationProgressArgs(string.Format(Strings.TemplateCreated, lyrId), current)); } } } } } success = true; } else { cb(this, new LengthyOperationProgressArgs(string.Format(Strings.TemplateFileNotFound, file), current)); } //This file is now fully processed, so increment progress current += pcPerFile; if (success) { cb(this, new LengthyOperationProgressArgs(string.Format(Strings.TemplateFileProcessed, file), current)); } } return(resCreatedOrUpdated.ToArray()); }