public override void Run() { var wb = Workbench.Instance; var exp = wb.ActiveSiteExplorer; var connMgr = ServiceRegistry.GetService<ServerConnectionManager>(); var conn = connMgr.GetConnection(exp.ConnectionName); if (!IsValid(conn)) { MessageService.ShowError(Strings.ConnectionDoesNotSupportRequiredInterfaces); return; } if (exp.SelectedItems.Length == 1) { var selected = exp.SelectedItems[0]; var resId = new ResourceIdentifier(selected.ResourceId); if (resId.ResourceType != ResourceTypes.WebLayout && resId.ResourceType != ResourceTypes.ApplicationDefinition && resId.ResourceType != ResourceTypes.LoadProcedure) { DoRepointResource(wb, conn, resId); } else { MessageService.ShowMessage(Strings.ResourceNotRepointable); } } }
/// <summary> /// Constructor /// </summary> /// <param name="resId">The given resource, whose dependencies we want to re-point</param> /// <param name="resSvc">The resource service</param> public RepointerDialog(ResourceIdentifier resId, IResourceService resSvc) : this() { _resSvc = resSvc; txtSource.Text = resId.ToString(); this.ResourceType = resId.ResourceType; var dependents = resSvc.EnumerateResourceReferences(resId.ToString()); lstAffectedResources.DataSource = dependents.ResourceId; }
protected object BackgroundValidate(BackgroundWorker worker, DoWorkEventArgs e, params object[] args) { //Collect all documents to be validated. Some of these selected items //may be folders. var documents = new List<string>(); var conn = (IServerConnection)args[0]; foreach (object a in args.Skip(1)) { string rid = a.ToString(); if (ResourceIdentifier.Validate(rid)) { var resId = new ResourceIdentifier(rid); if (resId.IsFolder) { foreach (IRepositoryItem o in conn.ResourceService.GetRepositoryResources(rid).Children) { if (!o.IsFolder) { documents.Add(o.ResourceId); } } } else { documents.Add(rid); } } } worker.ReportProgress(0); var context = new ResourceValidationContext(conn.ResourceService, conn.FeatureService); var set = new ValidationResultSet(); int i = 0; foreach (string s in documents) { worker.ReportProgress((int)((i / (double)documents.Count) * 100), s); IResource item = null; try { item = conn.ResourceService.GetResource(s); set.AddIssues(ResourceValidatorSet.Validate(context, item, true)); } catch (Exception ex) { string msg = NestedExceptionMessageProcessor.GetFullMessage(ex); set.AddIssue(new ValidationIssue(item, ValidationStatus.Error, ValidationStatusCode.Error_General_ValidationError, string.Format("Failed to validate resource: {0}", msg))); } i++; worker.ReportProgress((int)((i / (double)documents.Count) * 100), s); } return set.GetAllIssues(); }
public override void Run() { var wb = Workbench.Instance; var exp = wb.ActiveSiteExplorer; var connMgr = ServiceRegistry.GetService<ServerConnectionManager>(); var conn = connMgr.GetConnection(exp.ConnectionName); if (exp.SelectedItems.Length > 0) { List<RepositoryItem> toDuplicate = new List<RepositoryItem>(); foreach (var item in exp.SelectedItems) { if (!item.IsFolder) toDuplicate.Add(item); } //They all have the same parent var folder = exp.SelectedItems[0].Parent; foreach (var item in toDuplicate) { //Keep testing until we find a target resource identifier that //doesn't already exists. Note this would automatically guard against any resources in this folder //that may already be open in an editor var rid = new ResourceIdentifier(item.ResourceId); var name = rid.IsFolder ? (rid.Name + "/") : (rid.Name + "." + rid.ResourceType.ToString()); //NOXLATE var resId = folder.ResourceId + name; int counter = 0; while (conn.ResourceService.ResourceExists(resId)) { counter++; if (rid.IsFolder) { resId = folder.ResourceId + rid.Name + " (" + counter + ")/"; //NOXLATE } else { var rname = name.Substring(0, name.IndexOf(".")); //NOXLATE var type = name.Substring(name.IndexOf(".")); //NOXLATE rname += " (" + counter + ")"; //NOXLATE resId = folder.ResourceId + rname + type; } } conn.ResourceService.CopyResource(item.ResourceId, resId, false); LoggingService.Info(string.Format(Strings.ResourceDuplicated, item.ResourceId, resId)); } exp.RefreshModel(conn.DisplayName, folder.ResourceId); } }
public override void Run() { var wb = Workbench.Instance; var exp = wb.ActiveSiteExplorer; var omgr = ServiceRegistry.GetService<OpenResourceManager>(); var ed = wb.ActiveDocumentView as IEditorViewContent; var conn = ed.EditorService.GetEditedResource().CurrentConnection; if (ed != null) { using (var picker = new ResourcePicker(conn.ResourceService, ed.Resource.ResourceType, ResourcePickerMode.SaveResource)) { if (!string.IsNullOrEmpty(ed.EditorService.SuggestedSaveFolder)) picker.SetStartingPoint(ed.EditorService.SuggestedSaveFolder); if (picker.ShowDialog() == System.Windows.Forms.DialogResult.OK) { if (omgr.IsOpen(picker.ResourceID, conn)) { MessageService.ShowMessage(string.Format(Strings.CannotSaveToResourceAlreadyOpened, picker.ResourceID)); return; } using (new WaitCursor(wb)) { var oldId = ed.EditorService.ResourceID; ed.EditorService.SaveAs(picker.ResourceID); if (oldId != ed.EditorService.ResourceID) omgr.RenameResourceId(oldId, ed.EditorService.ResourceID, conn, exp); try { var rid = new ResourceIdentifier(picker.ResourceID); exp.RefreshModel(conn.DisplayName, rid.ParentFolder); } catch (NullReferenceException) { //HACK/FIXME: This can NRE if we created a new resource and //we haven't expanded the Site Explorer for the first //time. Muffling this NRE will just mean that the Site //Explorer won't auto-expand to the folder where this //resource was created. So nothing major. } } } } } }
protected override void OnBeforeSave(object sender, CancelEventArgs e) { List<string> affectedMapDefinitions = new List<string>(); var refs = _edsvc.ResourceService.EnumerateResourceReferences(_edsvc.ResourceID); foreach (var r in refs.ResourceId) { ResourceIdentifier rid = new ResourceIdentifier(r); if (rid.ResourceType == OSGeo.MapGuide.MaestroAPI.ResourceTypes.LayerDefinition) { var lrefs = _edsvc.ResourceService.EnumerateResourceReferences(r); foreach (var lr in lrefs.ResourceId) { ResourceIdentifier rid2 = new ResourceIdentifier(lr); if (rid2.ResourceType == OSGeo.MapGuide.MaestroAPI.ResourceTypes.MapDefinition) { var mdf = (IMapDefinition)_edsvc.ResourceService.GetResource(lr); if (mdf.BaseMap != null) { foreach (var blg in mdf.BaseMap.BaseMapLayerGroup) { foreach (var bl in blg.BaseMapLayer) { if (bl.ResourceId.Equals(r)) { affectedMapDefinitions.Add(r); } } } } } } } } if (affectedMapDefinitions.Count > 0) { if (!MessageService.AskQuestionFormatted(Strings.Confirm, Strings.ConfirmBaseMapInvalidationFeatureSourceSave, string.Join(Environment.NewLine, affectedMapDefinitions.ToArray()) + Environment.NewLine)) { e.Cancel = true; return; } } base.OnBeforeSave(sender, e); }
private static void DoRepointResource(Workbench wb, IServerConnection conn, ResourceIdentifier resId) { var diag = new RepointerDialog(resId, conn.ResourceService); if (diag.ShowDialog() == System.Windows.Forms.DialogResult.OK) { string srcId = diag.Source; string dstId = diag.Target; var deps = diag.Dependents; ProgressDialog.DoBackgroundWork worker = (wk, e, args) => { int updated = 0; int total = deps.Count; wk.ReportProgress(0, Strings.ProgressUpdatingReferences); foreach (var dep in deps) { using (var stream = conn.ResourceService.GetResourceXmlData(dep)) { XmlDocument doc = new XmlDocument(); doc.Load(stream); bool changed = Utility.ReplaceResourceIds(doc, srcId, dstId); if (changed) { using (var ms = new MemoryStream()) { doc.Save(ms); ms.Position = 0L; //Rewind conn.ResourceService.SetResourceXmlData(dep, ms); } updated++; wk.ReportProgress((updated / total) * 100); } } } return updated; }; var prd = new ProgressDialog(); int result = (int)prd.RunOperationAsync(wb, worker); MessageService.ShowMessage(string.Format(Strings.ResourcesRepointed, result, dstId)); } }
object UpdateConfigurationDocument(BackgroundWorker worker, DoWorkEventArgs e, params object[] args) { GdalConfigurationDocument conf = (GdalConfigurationDocument)args[0]; IServerConnection conn = (IServerConnection)args[1]; string [] toAdd = args[2] as string[]; string [] toRemove = args[3] as string[]; bool isAlias = (bool)args[4]; worker.ReportProgress(0, Strings.UpdatingConfiguration); int total = toAdd.Length + toRemove.Length; int unit = (total / 100); int progress = 0; var result = new UpdateConfigResult() { Added = new List<string>(), Removed = new List<string>() }; //Remove first foreach (var remove in toRemove) { string dir = null; if (isAlias) { dir = remove.Substring(0, remove.LastIndexOf("\\")); //NOXLATE } else { dir = Path.GetDirectoryName(remove); } var loc = FindLocation(conf, dir); if (null != loc) { string f = isAlias ? remove.Substring(remove.LastIndexOf("\\") + 1) : Path.GetFileName(remove); //NOXLATE loc.RemoveItem(f); result.Removed.Add(remove); if (loc.Items.Length == 0) conf.RemoveLocation(loc); } progress += unit; worker.ReportProgress(progress, string.Format(Strings.ProcessedItem, remove)); } //Then add foreach (var add in toAdd) { string dir = null; if (isAlias) { int idx = add.LastIndexOf("/"); //NOXLATE if (idx >= 0) dir = add.Substring(0, idx); else dir = add.Substring(0, add.LastIndexOf("%") + 1); //NOXLATE } else { dir = Path.GetDirectoryName(add); } var loc = conf.AddLocation(dir); //Create a temp feature source to attempt interrogation of extents var values = new NameValueCollection(); values["DefaultRasterFileLocation"] = add; //NOXLATE var fs = ObjectFactory.CreateFeatureSource(conn, "OSGeo.Gdal", values); //NOXLATE var resId = new ResourceIdentifier("Session:" + conn.SessionID + "//" + Guid.NewGuid() + ".FeatureSource"); //NOXLATE fs.ResourceID = resId.ToString(); conn.ResourceService.SaveResource(fs); var scList = fs.GetSpatialInfo(false); var raster = new GdalRasterItem(); if (isAlias) { int idx = add.LastIndexOf("/"); //NOXLATE if (idx >= 0) raster.FileName = add.Substring(add.LastIndexOf("/") + 1); //NOXLATE else raster.FileName = add.Substring(add.LastIndexOf("%") + 1); //NOXLATE } else { raster.FileName = Path.GetFileName(add); } if (scList.SpatialContext.Count > 0) { raster.MinX = Convert.ToDouble(scList.SpatialContext[0].Extent.LowerLeftCoordinate.X, CultureInfo.InvariantCulture); raster.MinY = Convert.ToDouble(scList.SpatialContext[0].Extent.LowerLeftCoordinate.Y, CultureInfo.InvariantCulture); raster.MaxX = Convert.ToDouble(scList.SpatialContext[0].Extent.UpperRightCoordinate.X, CultureInfo.InvariantCulture); raster.MaxY = Convert.ToDouble(scList.SpatialContext[0].Extent.UpperRightCoordinate.Y, CultureInfo.InvariantCulture); } else { raster.MinX = -10000000; raster.MinY = -10000000; raster.MaxX = 10000000; raster.MaxY = 10000000; } loc.AddItem(raster); result.Added.Add(Path.Combine(dir, raster.FileName)); progress += unit; worker.ReportProgress(progress, string.Format(Strings.ProcessedItem, add)); } //Re-calculate combined extent for spatial context var env = conf.CalculateExtent(); if (env != null) conf.SpatialContexts[0].Extent = env; return result; }
public virtual void TestMapManipulation4() { IServerConnection conn = CreateTestConnection(); IMappingService mapSvc = (IMappingService)conn.GetService((int)ServiceType.Mapping); string mapdefinition = "Library://UnitTests/Maps/Sheboygan.MapDefinition"; ResourceIdentifier rtmX = new ResourceIdentifier(mapdefinition); string rtmDef = "Library://UnitTests/Cache/" + rtmX.Fullpath.Replace(":", "_").Replace("/", "_"); string mapName = rtmX.Name; ResourceIdentifier mapid = new ResourceIdentifier(mapName, ResourceTypes.RuntimeMap, conn.SessionID); IMapDefinition mdef = (IMapDefinition)conn.ResourceService.GetResource(mapdefinition); RuntimeMap rtm = mapSvc.CreateMap(mdef); // Create new runtime map Assert.IsFalse(rtm.IsDirty); rtm.Save(); Assert.IsFalse(rtm.IsDirty); RuntimeMap tmprtm = mapSvc.CreateMap(mapid, mdef); // Create new map in data cache Assert.IsFalse(tmprtm.IsDirty); tmprtm.Save(); Assert.IsFalse(tmprtm.IsDirty); RuntimeMap mymap = mapSvc.OpenMap(mapid); }
private string[] MoveResourcesWithinConnection(string connectionName, ICollection<string> resIds, string folderId) { var wb = Workbench.Instance; var notMovedToTarget = new List<string>(); var notMovedFromSource = new List<string>(); var omgr = ServiceRegistry.GetService<OpenResourceManager>(); var conn = _connManager.GetConnection(connectionName); var dlg = new ProgressDialog(); var worker = new ProgressDialog.DoBackgroundWork((w, e, args) => { LengthyOperationProgressCallBack cb = (sender, cbe) => { w.ReportProgress(cbe.Progress, cbe.StatusMessage); }; var f = (string)args[0]; var resourceIds = (ICollection<string>)args[1]; foreach (var r in resourceIds) { if (ResourceIdentifier.IsFolderResource(r)) { //IMPORTANT: We need to tweak the target resource id //otherwise the content *inside* the source folder is //moved instead of the folder itself! var rid = new ResourceIdentifier(r); var target = folderId + rid.Name + "/"; //NOXLATE conn.ResourceService.MoveResourceWithReferences(r, target, null, cb); } else { var rid = new ResourceIdentifier(r); var target = folderId + rid.Name + "." + rid.Extension; //NOXLATE if (omgr.IsOpen(r, conn)) { notMovedFromSource.Add(r); continue; } if (!omgr.IsOpen(target, conn)) conn.ResourceService.MoveResourceWithReferences(r, target, null, cb); else notMovedToTarget.Add(r); } } //Collect affected folders and refresh them Dictionary<string, string> folders = new Dictionary<string, string>(); folders.Add(folderId, folderId); foreach (var n in resourceIds) { var ri = new ResourceIdentifier(n); var parent = ri.ParentFolder; if (parent != null && !folders.ContainsKey(parent)) folders.Add(parent, parent); } return folders.Keys; }); var affectedFolders = (IEnumerable<string>)dlg.RunOperationAsync(wb, worker, folderId, resIds); if (notMovedToTarget.Count > 0 || notMovedFromSource.Count > 0) { MessageService.ShowMessage(string.Format( Strings.NotCopiedOrMovedDueToOpenEditors, Environment.NewLine + string.Join(Environment.NewLine, notMovedToTarget.ToArray()) + Environment.NewLine, Environment.NewLine + string.Join(Environment.NewLine, notMovedFromSource.ToArray()) + Environment.NewLine)); } return new List<string>(affectedFolders).ToArray(); }
private void MakeTempMap() { if (m_tempmap == null) { IMapDefinition m = ObjectFactory.CreateMapDefinition(m_connection, string.Empty); m.CoordinateSystem = @"LOCAL_CS[""*XY-M*"", LOCAL_DATUM[""*X-Y*"", 10000], UNIT[""Meter"", 1], AXIS[""X"", EAST], AXIS[""Y"", NORTH]]"; //NOXLATE m.SetExtents(-1, -1, 1, 1); //AIMS 2012 demands this checks out. Can't flub it anymore m.ResourceID = "Session:" + m_connection.SessionID + "//non-existing.MapDefinition"; //NOXLATE var mpsvc = (IMappingService)m_connection.GetService((int)ServiceType.Mapping); var rid = new ResourceIdentifier(Guid.NewGuid().ToString(), ResourceTypes.RuntimeMap, m_connection.SessionID); m_tempmap = mpsvc.CreateMap(m); } }
public override System.IO.Stream RenderRuntimeMap(RuntimeMap rtmap, double x1, double y1, double x2, double y2, int width, int height, int dpi, string format, bool clip) { var resourceId = rtmap.ResourceID; MgRenderingService rnd = this.Connection.CreateService(MgServiceType.RenderingService) as MgRenderingService; MgResourceService res = this.Connection.CreateService(MgServiceType.ResourceService) as MgResourceService; MgGeometryFactory gf = new MgGeometryFactory(); string mapname = new ResourceIdentifier(resourceId).Path; //TODO: The render is missing the clip param for the extent override method GetByteReaderMethod fetch = () => { 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)); return rnd.RenderMap(map, sel, env, width, height, color, format); }; LogMethodCall("MgRenderingService::RenderMap", true, "MgMap", "MgSelection", "MgEnvelope", width.ToString(), height.ToString(), "MgColor", format); return new MgReadOnlyStream(fetch); }
public void RefreshModel(string connectionName, string resId) { if (!string.IsNullOrEmpty(resId)) { var rid = new ResourceIdentifier(resId); if (!rid.IsFolder) resId = rid.ParentFolder; //If this node is not initially expanded, we get NRE on refresh ExpandNode(connectionName, resId); var path = _model.GetPathFromResourceId(connectionName, resId); while (path == null) { resId = ResourceIdentifier.GetParentFolder(resId); path = _model.GetPathFromResourceId(connectionName, resId); } var node = trvResources.FindNode(path, true); if (node != null) { //Walk back up until node has children. We want to refresh from this node down while (node.Children.Count == 0 && node != trvResources.Root) node = node.Parent; } trvResources.SelectedNode = node; } _model.Refresh(); if (!string.IsNullOrEmpty(resId)) { SelectNode(connectionName, resId); } //trvResources.Root.Children[0].Expand(); }
/// <summary> /// Initializes a new instance of the <see cref="RepositoryHandle"/> class. /// </summary> /// <param name="resId">The res id.</param> /// <param name="conn">The conn.</param> public RepositoryHandle(ResourceIdentifier resId, IServerConnection conn) { this.ResourceId = resId; this.Connection = conn; }
public override System.IO.Stream RenderRuntimeMap(RuntimeMap rtmap, double x, double y, double scale, int width, int height, int dpi, string format, bool clip) { var resourceId = rtmap.ResourceID; MgRenderingService rnd = this.Connection.CreateService(MgServiceType.RenderingService) as MgRenderingService; MgResourceService res = this.Connection.CreateService(MgServiceType.ResourceService) as MgResourceService; MgGeometryFactory gf = new MgGeometryFactory(); string mapname = new ResourceIdentifier(resourceId).Path; GetByteReaderMethod fetch = () => { 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())); MgCoordinate coord = gf.CreateCoordinateXY(x, y); return rnd.RenderMap(map, sel, coord, scale, width, height, color, format, true); }; LogMethodCall("MgRenderingService::RenderMap", true, "MgMap", "MgSelection", "MgPoint("+ x + "," + y + ")", scale.ToString(), width.ToString(), height.ToString(), "MgColor", format, true.ToString()); return new MgReadOnlyStream(fetch); }
/// <summary> /// Constructs a new ResourceIdentifier, based on an existing one. /// </summary> /// <param name="id">The resource identifier to copy</param> public ResourceIdentifier(ResourceIdentifier id) { m_id = id.m_id; }
private void ProfileLayerDefinition(ILayerDefinition ldef) { //TODO: This was a line-by-line port from 2.x to match the 3.x APIs //we should find time to clean this up and ensure the profiling numbers are //truly reflective of actual performance metrics if (backgroundWorker.CancellationPending) return; string resourceId = ldef == m_item ? m_resourceId : ldef.ResourceID; MakeTempMap(); backgroundWorker.ReportProgress(0, (string.Format(Strings.Prof_LogMessageLayerDefinition, resourceId))); using (new Timer(Strings.Prof_LogMessageRuntimeLayer, backgroundWorker)) { try { IMapDefinition mdef = ObjectFactory.CreateMapDefinition(m_connection, string.Empty); //We cannot flub this anymore. AIMS 2012 demands the Map Definition id specified checks out mdef.ResourceID = "Session:" + m_connection.SessionID + "//ProfileTest.MapDefinition"; //NOXLATE m_connection.ResourceService.SaveResource(mdef); IMapLayer layer = mdef.AddLayer(null, "Test Layer", ldef.ResourceID); //NOXLATE layer.Visible = false; layer.Selectable = false; if (backgroundWorker.CancellationPending) return; var mpsvc = (IMappingService)m_connection.GetService((int)ServiceType.Mapping); var map = mpsvc.CreateMap(mdef); using (new Timer(Strings.Prof_LogMessageIdentifyFetching, backgroundWorker)) { var rtl = map.Layers["Test Layer"]; //NOXLATE rtl.Visible = true; rtl.Selectable = true; } map.Save(); } catch (Exception ex) { //string msg = NestedExceptionMessageProcessor.GetFullMessage(ex); backgroundWorker.ReportProgress(0, (string.Format(Strings.Prof_LayerDefinitionProfilingError, resourceId, ex.ToString(), Environment.NewLine))); } } if (backgroundWorker.CancellationPending) return; ILayerDefinition lx = (ILayerDefinition)ldef.Clone(); if (lx.SubLayer.LayerType == LayerType.Vector || lx.SubLayer.LayerType == LayerType.Raster) { using (new Timer(Strings.Prof_LogMessageRenderingScales, backgroundWorker)) { if (lx.SubLayer.LayerType == LayerType.Vector) { IVectorLayerDefinition vlx = lx.SubLayer as IVectorLayerDefinition; //VectorScaleRangeTypeCollection ranges = vlx.VectorScaleRange; List<IVectorScaleRange> ranges = new List<IVectorScaleRange>(vlx.VectorScaleRange); foreach (var vsr in ranges) { if (backgroundWorker.CancellationPending) return; string tmp1 = new ResourceIdentifier(Guid.NewGuid().ToString(), ResourceTypes.LayerDefinition, m_connection.SessionID); try { double minscale = vsr.MinScale.HasValue ? vsr.MinScale.Value : 0; double maxscale = vsr.MaxScale.HasValue ? vsr.MaxScale.Value : 10000000; vlx.RemoveAllScaleRanges(); vsr.MinScale = null; vsr.MaxScale = null; vlx.AddVectorScaleRange(vsr); m_connection.ResourceService.SaveResourceAs(lx, tmp1); if (backgroundWorker.CancellationPending) return; var lst = m_connection.FeatureService.GetSpatialContextInfo(vlx.ResourceId, false); //Create a runtime map just containing this particular layer at this particular scale range //We are profiling the stylization settings for this layer var mdf = ObjectFactory.CreateMapDefinition(m_connection, ""); if (lst.SpatialContext != null && lst.SpatialContext.Count >= 1) { mdf.CoordinateSystem = lst.SpatialContext[0].CoordinateSystemWkt; if (string.IsNullOrEmpty(m_tempmap.CoordinateSystem)) mdf.CoordinateSystem = @"LOCAL_CS[""*XY-M*"", LOCAL_DATUM[""*X-Y*"", 10000], UNIT[""Meter"", 1], AXIS[""X"", EAST], AXIS[""Y"", NORTH]]"; //NOXLATE double llx = double.Parse(lst.SpatialContext[0].Extent.LowerLeftCoordinate.X, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture); double lly = double.Parse(lst.SpatialContext[0].Extent.LowerLeftCoordinate.Y, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture); ; double urx = double.Parse(lst.SpatialContext[0].Extent.UpperRightCoordinate.X, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture); ; double ury = double.Parse(lst.SpatialContext[0].Extent.UpperRightCoordinate.Y, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture); ; m_tempmap.DataExtent = ObjectFactory.CreateEnvelope(llx, lly, urx, ury); } SetTempLayer(mdf, tmp1); var mpsvc = (IMappingService)m_connection.GetService((int)ServiceType.Mapping); //We cannot flub this anymore. AIMS 2012 demands the Map Definition id specified checks out mdf.ResourceID = "Session:" + m_connection.SessionID + "//ProfileTest.MapDefinition"; //NOXLATE m_connection.ResourceService.SaveResource(mdf); var rtmap = mpsvc.CreateMap(mdf); if (m_connection.ResourceService.ResourceExists(rtmap.ResourceID)) m_connection.ResourceService.DeleteResource(rtmap.ResourceID); rtmap.Save(); if (backgroundWorker.CancellationPending) return; using (new Timer(string.Format(Strings.Prof_LogMessageScaleRange, minscale, maxscale), backgroundWorker)) { //TODO: Use extents rather than scale //using (System.IO.Stream s = m_connection.RenderRuntimeMap(tmp2, m.Extents, 1024, 800, 96)) using (System.IO.Stream s = mpsvc.RenderRuntimeMap(rtmap, ((rtmap.DataExtent.MaxX - rtmap.DataExtent.MinX) / 2) + rtmap.DataExtent.MinX, ((rtmap.DataExtent.MaxY - rtmap.DataExtent.MinY) / 2) + rtmap.DataExtent.MinY, 50000, 1024, 800, 96)) { backgroundWorker.ReportProgress(0, (string.Format(Strings.Prof_MapRenderingImageSize, s.Length))); } } } finally { try { m_connection.ResourceService.DeleteResource(tmp1); } catch { } } } } } } if (backgroundWorker.CancellationPending) return; backgroundWorker.ReportProgress(0, ("\r\n")); //NOXLATE }
private object BackgroundCheckResources(BackgroundWorker worker, DoWorkEventArgs e, params object[] args) { var documents = new List<string>(); foreach (object a in args) { string rid = a.ToString(); if (ResourceIdentifier.Validate(rid)) { var resId = new ResourceIdentifier(rid); if (resId.IsFolder) { foreach (IRepositoryItem o in _conn.ResourceService.GetRepositoryResources((string)args[0]).Children) { if (!o.IsFolder) { documents.Add(o.ResourceId); } } } else { documents.Add(rid); } } } var items = new List<string>(); var test = new MockServerConnection() { SiteVersion = _checkVersion }; var caps = new TestCapabilities(test); if (documents.Count == 0) return items.ToArray(); var unit = 100 / documents.Count; var progress = 0.0; worker.ReportProgress(0); foreach (string resId in documents) { IResource res = _conn.ResourceService.GetResource(resId); Version ver = null; try { ver = caps.GetMaxSupportedResourceVersion(res.ResourceType); } catch { items.Add(resId); continue; } //The resource's version is greater than the maximum version supported by //the user's selected site version if (res.ResourceVersion > ver) { items.Add(resId); } progress += unit; worker.ReportProgress((int)progress); } worker.ReportProgress(100); return items.ToArray(); }
private void CreatePackageInternal(string folderResourceId, string zipfilename, IEnumerable<ResourceTypes> allowedExtensions, bool removeExistingFiles, string alternateTargetResourceId, IEnumerable<string> resourceIds) { ResourcePackageManifest manifest = new ResourcePackageManifest(); manifest.Description = "MapGuide Package created with Maestro"; //NOXLATE manifest.Operations = new ResourcePackageManifestOperations(); manifest.Operations.Operation = new System.ComponentModel.BindingList<ResourcePackageManifestOperationsOperation>(); var allowed = new List<ResourceTypes>(allowedExtensions); var files = new List<string>(); var folders = new List<string>(); var resourceData = new Dictionary<string, List<ResourceDataListResourceData>>(); foreach (var resId in resourceIds) { if (!ResourceIdentifier.Validate(resId)) continue; var r = new ResourceIdentifier(resId); if (r.IsFolder) { folders.Add(resId); } else { var extension = r.ResourceType; if (allowedExtensions == null || allowed.Count == 0) files.Add(resId); else if (m_connection.Capabilities.IsSupportedResourceType(extension) && allowed.Contains(extension)) files.Add(resId); } } if (Progress != null) { Progress(ProgressType.ReadingFileList, folderResourceId, 100, 100); Progress(ProgressType.PreparingFolder, string.Empty, files.Count + folders.Count + 1, 0); } string temppath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), System.IO.Path.GetRandomFileName()); //All files have random names on disk, but a full path in the zip file List<KeyValuePair<string, string>> filemap = new List<KeyValuePair<string, string>>(); try { System.IO.Directory.CreateDirectory(temppath); int opno = 1; foreach (var folder in folders) { if (Progress != null) Progress(ProgressType.PreparingFolder, folder, files.Count + folders.Count + 1, opno); AddFolderResource(manifest, temppath, folder, removeExistingFiles, m_connection, filemap); if (Progress != null) Progress(ProgressType.PreparingFolder, folder, files.Count + folders.Count + 1, opno++); } foreach (var doc in files) { if (Progress != null) Progress(ProgressType.PreparingFolder, doc, files.Count + folders.Count + 1, opno); string filebase = CreateFolderForResource(doc, temppath); resourceData[doc] = new List<ResourceDataListResourceData>(); ResourceDataList rdl = m_connection.ResourceService.EnumerateResourceData(doc); foreach (ResourceDataListResourceData rd in rdl.ResourceData) resourceData[doc].Add(rd); int itemCount = resourceData[doc].Count + 1; filemap.Add(new KeyValuePair<string, string>(filebase + "_CONTENT.xml", System.IO.Path.Combine(temppath, Guid.NewGuid().ToString()))); //NOXLATE using (System.IO.FileStream fs = new System.IO.FileStream(filemap[filemap.Count - 1].Value, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None)) { using (var s = m_connection.ResourceService.GetResourceXmlData(doc)) { var data = Utility.StreamAsArray(s); fs.Write(data, 0, data.Length); } } AddFileResource(manifest, temppath, doc, filemap[filemap.Count - 1].Key, removeExistingFiles, m_connection, filemap); foreach (ResourceDataListResourceData rd in rdl.ResourceData) { filemap.Add(new KeyValuePair<string, string>(filebase + "_DATA_" + EncodeFilename(rd.Name), System.IO.Path.Combine(temppath, Guid.NewGuid().ToString()))); System.IO.FileInfo fi = new System.IO.FileInfo(filemap[filemap.Count - 1].Value); using (System.IO.FileStream fs = new System.IO.FileStream(fi.FullName, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None)) { Utility.CopyStream(m_connection.ResourceService.GetResourceData(doc, rd.Name), fs); } AddResourceData(manifest, temppath, doc, fi, filemap[filemap.Count - 1].Key, rd, m_connection); } if (Progress != null) Progress(ProgressType.PreparingFolder, doc, files.Count + folders.Count + 1, opno++); } if (Progress != null) Progress(ProgressType.PreparingFolder, Strings.ProgressDone, files.Count + folders.Count + 1, files.Count + folders.Count + 1); if (!string.IsNullOrEmpty(alternateTargetResourceId)) { if (Progress != null) Progress(ProgressType.MovingResources, Strings.ProgressUpdatingReferences, 100, 0); RemapFiles(m_connection, manifest, temppath, folderResourceId, alternateTargetResourceId, filemap); if (Progress != null) Progress(ProgressType.MovingResources, Strings.ProgressUpdatedReferences, 100, 100); } filemap.Add(new KeyValuePair<string, string>(System.IO.Path.Combine(temppath, "MgResourcePackageManifest.xml"), System.IO.Path.Combine(temppath, Guid.NewGuid().ToString()))); //NOXLATE using (System.IO.FileStream fs = new System.IO.FileStream(filemap[filemap.Count - 1].Value, System.IO.FileMode.CreateNew, System.IO.FileAccess.Write, System.IO.FileShare.None)) m_connection.ResourceService.SerializeObject(manifest, fs); if (Progress != null) Progress(ProgressType.MovingResources, zipfilename, filemap.Count, 0); ZipDirectory(zipfilename, temppath, "MapGuide Package created by Maestro", filemap); //NOXLATE if (Progress != null) { Progress(ProgressType.MovingResources, zipfilename, filemap.Count, filemap.Count); Progress(ProgressType.Done, "", filemap.Count, filemap.Count); } } finally { try { if (System.IO.Directory.Exists(temppath)) System.IO.Directory.Delete(temppath, true); } catch { } } }
private string CreateFolderForResource(string resourceId, string temppath) { var rid = new ResourceIdentifier(resourceId); string filebase = EncodeFilename(rid.Name); string folder = "Library/" + EncodeFilename(rid.Path); //NOXLATE folder = folder.Substring(0, folder.Length - filebase.Length); filebase += resourceId.Substring(resourceId.LastIndexOf('.')); //NOXLATE folder = folder.Replace('/', System.IO.Path.DirectorySeparatorChar); //NOXLATE folder = System.IO.Path.Combine(temppath, folder); return System.IO.Path.Combine(folder, filebase); }
private static string GetCommonParent(ICollection<string> data) { if (data.Count > 0) { var firstResId = new ResourceIdentifier(data.ElementAt(0)); if (data.Count == 1) { if (firstResId.IsFolder) return firstResId.ResourceId.ToString(); else return firstResId.ParentFolder; } else { int matches = 0; string[] parts = firstResId.ResourceId.ToString() .Substring(StringConstants.RootIdentifier.Length) .Split('/'); //NOXLATE string test = StringConstants.RootIdentifier; string parent = test; int partIndex = 0; //Use first one as a sample to see how far we can go. Keep going until we have //a parent that doesn't match all of them. The one we recorded before then will //be the common parent while (matches == data.Count) { parent = test; partIndex++; if (partIndex < parts.Length) //Shouldn't happen, but just in case break; test = test + parts[partIndex]; matches = data.Where(x => x.StartsWith(test)).Count(); } return parent; } } else { return StringConstants.RootIdentifier; } }
public override void Run() { var wb = Workbench.Instance; var exp = wb.ActiveSiteExplorer; var clip = ServiceRegistry.GetService<ClipboardService>(); var omgr = ServiceRegistry.GetService<OpenResourceManager>(); var connMgr = ServiceRegistry.GetService<ServerConnectionManager>(); var targetConnName = exp.ConnectionName; var conn = connMgr.GetConnection(targetConnName); if (!clip.HasContent()) return; if (exp.SelectedItems.Length != 1) return; if (!exp.SelectedItems[0].IsFolder) return; var itemsToPaste = GetItems(clip); if (itemsToPaste.Length == 0) return; var folder = exp.SelectedItems[0]; var sourceItemsNotMoved = new List<string>(); //.net FX 2.0 hack to compensate for lack of set collection Dictionary<string, string> folders = new Dictionary<string, string>(); var notPasted = new List<RepositoryItem>(); //From same connection if (itemsToPaste.First().ConnectionName == targetConnName) { foreach (var item in itemsToPaste) { LoggingService.InfoFormatted(Strings.ClipboardAction, item.ClipboardState, item.ResourceId, folder.ResourceId); //Keep testing until we find a target resource identifier that //doesn't already exists. Note this would automatically guard against any resources in this folder //that may already be open in an editor var rid = new ResourceIdentifier(item.ResourceId); var name = rid.IsFolder ? (rid.Name + "/") : (rid.Name + "." + rid.ResourceType.ToString()); //NOXLATE var resId = folder.ResourceId + name; int counter = 0; while (conn.ResourceService.ResourceExists(resId)) { counter++; if (rid.IsFolder) { resId = folder.ResourceId + rid.Name + " (" + counter + ")/"; //NOXLATE } else { var rname = name.Substring(0, name.IndexOf(".")); //NOXLATE var type = name.Substring(name.IndexOf(".")); //NOXLATE rname += " (" + counter + ")"; //NOXLATE resId = folder.ResourceId + rname + type; } } if (item.ClipboardState == RepositoryItem.ClipboardAction.Copy) { if (item.IsFolder) { conn.ResourceService.CopyFolderWithReferences(item.ResourceId, resId, null, null); } else { conn.ResourceService.CopyResource(item.ResourceId, resId, false); } } else if (item.ClipboardState == RepositoryItem.ClipboardAction.Cut) { if (!item.IsFolder) { if (omgr.IsOpen(item.ResourceId, conn)) { sourceItemsNotMoved.Add(item.ResourceId); continue; } } //TODO: Should we prompt? That may be equivalent to saying //"Shall I break your resources because you're moving" isn't it? var res = conn.ResourceService.MoveResourceWithReferences(item.ResourceId, resId, null, null); if (!res) LoggingService.InfoFormatted(Strings.MoveFailure, item.ResourceId, resId); else folders[item.Parent.ResourceId] = item.Parent.ResourceId; } } } else { var copied = ((UI.SiteExplorer)exp).CopyResourcesToFolder( itemsToPaste.Select(x => new RepositoryHandle(new ResourceIdentifier(x.ResourceId), connMgr.GetConnection(x.ConnectionName))).ToArray(), targetConnName, folder.ResourceId); //Delete any originating items that were successfully cut/pasted foreach (var item in itemsToPaste) { if (item.ClipboardState == RepositoryItem.ClipboardAction.Cut) { var origConn = connMgr.GetConnection(item.ConnectionName); if (origConn.ResourceService.ResourceExists(item.ResourceId)) { origConn.ResourceService.DeleteResource(item.ResourceId); } } } var refreshFolder = UI.SiteExplorer.GetCommonParent(itemsToPaste); exp.RefreshModel(itemsToPaste.First().ConnectionName, refreshFolder); exp.ExpandNode(itemsToPaste.First().ConnectionName, refreshFolder); } if (sourceItemsNotMoved.Count > 0) MessageService.ShowMessage(string.Format(Strings.ItemsNotMovedDueToBeingOpen, Environment.NewLine + string.Join(Environment.NewLine, sourceItemsNotMoved.ToArray()))); ResetItems(omgr, itemsToPaste, connMgr); exp.RefreshModel(conn.DisplayName, folder.ResourceId); foreach (var f in folders.Keys) { exp.RefreshModel(conn.DisplayName, f); } }