public void Initialize(InstallScript script) { _log.Length = 0; _script = script; _lines = _script.Lines.Where(l => l.Script != null && l.Type != InstallType.Warning).ToList(); _currLine = -1; }
/// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { var hashCode = 41; // Suitable nullity checks etc, of course :) if (Id != null) { hashCode = hashCode * 59 + Id.GetHashCode(); } if (FixedConfig != null) { hashCode = hashCode * 59 + FixedConfig.GetHashCode(); } if (InstallScript != null) { hashCode = hashCode * 59 + InstallScript.GetHashCode(); } if (StartScript != null) { hashCode = hashCode * 59 + StartScript.GetHashCode(); } return(hashCode); } }
/// <summary> /// Returns true if ModelFlowChartExtension instances are equal /// </summary> /// <param name="other">Instance of ModelFlowChartExtension to be compared</param> /// <returns>Boolean</returns> public bool Equals(ModelFlowChartExtension other) { if (ReferenceEquals(null, other)) { return(false); } if (ReferenceEquals(this, other)) { return(true); } return (( Id == other.Id || Id != null && Id.Equals(other.Id) ) && ( FixedConfig == other.FixedConfig || FixedConfig != null && FixedConfig.Equals(other.FixedConfig) ) && ( InstallScript == other.InstallScript || InstallScript != null && InstallScript.Equals(other.InstallScript) ) && ( StartScript == other.StartScript || StartScript != null && StartScript.Equals(other.StartScript) )); }
private void GetPatchPackage(InstallScript start, InstallScript dest) { var docs = new List <Tuple <XmlDocument, string> >(); ProgressDialog.Display(this, d => { start.WriteAmlMergeScripts(dest, (path, prog) => { d.SetProgress(prog); var doc = new XmlDocument(); docs.Add(Tuple.Create(doc, path)); return(new XmlNodeWriter(doc)); }); }); var items = docs .Where(d => d.Item1.DocumentElement != null) .SelectMany(d => XmlUtils.RootItems(d.Item1.DocumentElement) .Select(i => InstallItem.FromScript(i, d.Item2))) .ToArray(); _wizard.InstallScript = new InstallScript() { Lines = items }; _wizard.GoToStep(new ExportOptions()); }
private void btnDbPackage_Click(object sender, EventArgs e) { try { var items = _conn.Apply(@"<Item type='PackageDefinition' action='get' select='id' />").Items(); var refs = new List <ItemReference>(); foreach (var item in items) { refs.Add(ItemReference.FromFullItem(item, true)); } using (var dialog = new FilterSelect <ItemReference>()) { dialog.DataSource = refs; dialog.DisplayMember = "KeyedName"; dialog.Message = resources.Messages.PackageSelect; if (dialog.ShowDialog(this, btnDbPackage.RectangleToScreen(btnDbPackage.Bounds)) == DialogResult.OK && dialog.SelectedItem != null) { txtFind.Text = ""; _findAction = DefaultFindAction; items = _conn.Apply(@"<Item type='PackageElement' action='get' select='element_id,element_type,name' orderBy='element_type,name,element_id'> <source_id condition='in'>(select id from innovator.PACKAGEGROUP where SOURCE_ID = @0)</source_id> </Item>", dialog.SelectedItem.Unique).Items(); _availableRefs.Clear(); ItemReference newRef; foreach (var item in items) { newRef = new ItemReference() { Type = item.Property("element_type").AsString(""), Unique = item.Property("element_id").AsString(""), KeyedName = item.Property("name").AsString("") }; if (!_selectedRefs.Contains(newRef)) { _selectedRefs.Add(newRef); } } _existingScript = _existingScript ?? new InstallScript(); _existingScript.Title = dialog.SelectedItem.KeyedName; EnsureResultsTab(); tbcSearch.SelectedTab = pgResults; txtFind.Focus(); } } } catch (Exception ex) { Utils.HandleError(ex); } }
private void btnPackageFile_Click(object sender, EventArgs e) { try { using (var dialog = new OpenFileDialog()) { dialog.Filter = "Innovator Package (.innpkg)|*.innpkg|Manifest (.mf)|*.mf"; if (dialog.ShowDialog() == DialogResult.OK) { if (Path.GetExtension(dialog.FileName) == ".innpkg") { using (var pkg = InnovatorPackage.Load(dialog.FileName)) { var installScript = pkg.Read(); _availableRefs.Clear(); foreach (var item in installScript.Lines.Where(l => l.Type == InstallType.Create).Select(l => l.Reference)) { if (!_selectedRefs.Contains(item)) { _selectedRefs.Add(item); } } _existingScript = installScript; _existingScript.Lines = null; } } else { var pkg = new ManifestFolder(dialog.FileName); string title; var doc = pkg.Read(out title); foreach (var item in ItemReference.FromFullItems(doc.DocumentElement, true)) { if (!_selectedRefs.Contains(item)) { _selectedRefs.Add(item); } } _existingScript = _existingScript ?? new InstallScript(); _existingScript.Title = title; } EnsureResultsTab(); tbcSearch.SelectedTab = pgResults; txtFind.Focus(); } } } catch (Exception ex) { Utils.HandleError(ex); } }
public virtual InstallScript Read() { var result = new InstallScript(); XmlDocument doc; var scripts = new List<InstallItem>(); var manifest = new XmlDocument(); string path; manifest.Load(GetExistingStream(null)); if (manifest.DocumentElement.HasAttribute("created")) result.Created = DateTime.Parse(manifest.DocumentElement.GetAttribute("created")); result.Creator = manifest.DocumentElement.GetAttribute("creator"); result.Description = manifest.DocumentElement.GetAttribute("description"); if (manifest.DocumentElement.HasAttribute("modified")) result.Modified = DateTime.Parse(manifest.DocumentElement.GetAttribute("modified")); result.Version = manifest.DocumentElement.GetAttribute("revision"); result.Title = manifest.DocumentElement.GetAttribute("title"); if (manifest.DocumentElement.HasAttribute("website")) result.Website = new Uri(manifest.DocumentElement.GetAttribute("website")); foreach (var child in manifest.DocumentElement.ChildNodes.OfType<XmlElement>()) { if (child.LocalName == "Item") { scripts.Add(InstallItem.FromScript(child)); } else { path = child.GetAttribute("path"); if (!string.IsNullOrEmpty(path)) { if (path.EndsWith(".xslt", StringComparison.OrdinalIgnoreCase)) { doc = ReadReport(path); } else { doc = new XmlDocument(); doc.Load(GetExistingStream(path)); } foreach (var item in doc.DocumentElement.Elements("Item")) { scripts.Add(InstallItem.FromScript(item)); } } } } result.Lines = scripts; return result; }
private void btnDbPackage_Click(object sender, EventArgs e) { try { var items = _conn.GetItems("ApplyAML", Properties.Resources.Aml_Packages); var refs = new List <ItemReference>(); foreach (var item in items) { refs.Add(ItemReference.FromFullItem(item, true)); } using (var dialog = new FilterSelect <ItemReference>()) { dialog.DataSource = refs; dialog.DisplayMember = "KeyedName"; dialog.Message = resources.Messages.PackageSelect; if (dialog.ShowDialog(this) == DialogResult.OK && dialog.SelectedItem != null) { txtFind.Text = ""; _findAction = DefaultFindAction; items = _conn.GetItems("ApplyAML", string.Format(Properties.Resources.Aml_PackageElements, dialog.SelectedItem.Unique)); _availableRefs.Clear(); ItemReference newRef; foreach (var item in items) { newRef = new ItemReference() { Type = item.Element("element_type", ""), Unique = item.Element("element_id", ""), KeyedName = item.Element("name", "") }; if (!_selectedRefs.Contains(newRef)) { _selectedRefs.Add(newRef); } } _existingScript = _existingScript ?? new InstallScript(); _existingScript.Title = dialog.SelectedItem.KeyedName; EnsureResultsTab(); tbcSearch.SelectedTab = pgResults; txtFind.Focus(); } } } catch (Exception ex) { Utils.HandleError(ex); } }
public override void Write(InstallScript script) { _package.PackageProperties.Created = script.Created; _package.PackageProperties.Creator = script.Creator; _package.PackageProperties.Description = script.Description; _package.PackageProperties.Modified = script.Modified; _package.PackageProperties.Revision = script.Version; _package.PackageProperties.Title = script.Title; if (script.Website != null) _package.PackageProperties.Identifier = script.Website.ToString(); base.Write(script); }
public BuildConfiguration ToBuildConfiguration() { return(new BuildConfiguration( Version, InitializationScript?.ToScriptBlock(), CloneFolder, InstallScript?.ToScriptBlock(), AssemblyVersion?.ToAssemblyInfo(), OperatingSystems, EnvironmentVariables?.ToEnvironmentVariables(), Matrix?.ToMatrix(), Platforms, Configurations, Build?.ToBuild(), BeforeBuildScript?.ToScriptBlock(), BuildScript?.ToScriptBlock(), AfterBuildScript?.ToScriptBlock(), TestScript?.ToScriptBlock(), OnSuccessScript?.ToScriptBlock(), OnFailureScript?.ToScriptBlock(), OnFinishScript?.ToScriptBlock())); }
public InstallScript ConvertManifestXml(XmlDocument doc, string name) { ExportProcessor.EnsureSystemData(_conn, ref _itemTypes); foreach (var elem in doc.ElementsByXPath("//Item[@action='add']").ToList()) { elem.SetAttribute("action", "merge"); } ItemType itemType; foreach (var elem in doc.ElementsByXPath("//Item[@type and @id]").ToList()) { if (_itemTypes.TryGetValue(elem.Attribute("type", "").ToLowerInvariant(), out itemType) && itemType.IsVersionable) { elem.SetAttribute(XmlFlags.Attr_ConfigId, elem.Attribute("id")); elem.SetAttribute("where", string.Format("[{0}].[config_id] = '{1}'", itemType.Name.Replace(' ', '_'), elem.Attribute("id"))); elem.RemoveAttribute("id"); } } var result = new InstallScript(); result.Title = name; _exportTools.Export(result, doc); return result; }
public static void WritePackage(ConsoleTask console, InstallScript script, string output, bool multipleDirectories, bool cleanOutput) { multipleDirectories = multipleDirectories || string.Equals(Path.GetExtension(output), ".mf", StringComparison.OrdinalIgnoreCase); if (cleanOutput) { console.Write("Cleaning output... "); if (multipleDirectories) { var dir = new DirectoryInfo(Path.GetDirectoryName(output)); if (dir.Exists) { Parallel.ForEach(dir.EnumerateFileSystemInfos(), fs => { if (fs is DirectoryInfo di) { di.Delete(true); } else { fs.Delete(); } }); } else { dir.Create(); } } else { File.Delete(output); } console.WriteLine("Done."); } console.Write("Writing package... "); var outputDir = Path.GetDirectoryName(output); if (!Directory.Exists(outputDir)) { Directory.CreateDirectory(outputDir); } switch (Path.GetExtension(output).ToLowerInvariant()) { case ".mf": var manifest = new ManifestFolder(output); manifest.Write(script); break; case ".innpkg": if (multipleDirectories) { using (var pkgFolder = new InnovatorPackageFolder(output)) pkgFolder.Write(script); } else { if (File.Exists(output)) { File.Delete(output); } using (var pkgFile = new InnovatorPackageFile(output)) pkgFile.Write(script); } break; default: throw new NotSupportedException("Output file type is not supported"); } console.WriteLine("Done."); }
public void Write(InstallScript script) { using (var xml = XmlTextWriter.Create(_path, _settings)) { xml.WriteStartElement("imports"); xml.WriteStartElement("package"); xml.WriteAttributeString("name", script.Title); if (script.Title.StartsWith("com.aras.innovator")) { if (script.Title.StartsWith("com.aras.innovator.solution.")) { _baseFolderPath = InnovatorPackage.CleanFileName(script.Title).Substring(28).Replace('.', '\\') + "\\Import"; xml.WriteAttributeString("path", _baseFolderPath); } else { _baseFolderPath = InnovatorPackage.CleanFileName(script.Title).Replace('.', '\\'); xml.WriteAttributeString("path", ".\\"); } } else { _baseFolderPath = InnovatorPackage.CleanFileName(script.Title) + "\\Import"; xml.WriteAttributeString("path", _baseFolderPath); } xml.WriteEndElement(); xml.WriteEndElement(); } _baseFolderPath = Path.Combine(Path.GetDirectoryName(_path), _baseFolderPath); XmlWriter writer; InstallItem first; var existingPaths = new HashSet<string>(); string newPath; foreach (var group in script.GroupLines(i => i.Type != InstallType.DependencyCheck)) { first = group.First(); newPath = first.Reference.Type + "\\" + InnovatorPackage.CleanFileName(first.Reference.KeyedName ?? first.Reference.Unique) + ".xml"; if (existingPaths.Contains(newPath)) newPath = first.Reference.Type + "\\" + InnovatorPackage.CleanFileName((first.Reference.KeyedName ?? "") + "_" + first.Reference.Unique) + ".xml"; writer = GetWriter(newPath); try { writer.WriteStartElement("AML"); foreach (var line in group) { line.Script.WriteTo(writer); } writer.WriteEndElement(); writer.Flush(); } finally { writer.Close(); } existingPaths.Add(newPath); } }
private void btnDbPackage_Click(object sender, EventArgs e) { try { var items = _conn.GetItems("ApplyAML", Properties.Resources.Aml_Packages); var refs = new List<ItemReference>(); foreach (var item in items) { refs.Add(ItemReference.FromFullItem(item, true)); } using (var dialog = new FilterSelect<ItemReference>()) { dialog.DataSource = refs; dialog.DisplayMember = "KeyedName"; dialog.Message = resources.Messages.PackageSelect; if (dialog.ShowDialog(this) == DialogResult.OK && dialog.SelectedItem != null) { txtFind.Text = ""; _findAction = DefaultFindAction; items = _conn.GetItems("ApplyAML", string.Format(Properties.Resources.Aml_PackageElements, dialog.SelectedItem.Unique)); _availableRefs.Clear(); ItemReference newRef; foreach (var item in items) { newRef = new ItemReference() { Type = item.Element("element_type", ""), Unique = item.Element("element_id", ""), KeyedName = item.Element("name", "") }; if (!_selectedRefs.Contains(newRef)) _selectedRefs.Add(newRef); } _existingScript = _existingScript ?? new InstallScript(); _existingScript.Title = dialog.SelectedItem.KeyedName; EnsureResultsTab(); tbcSearch.SelectedTab = pgResults; txtFind.Focus(); } } } catch (Exception ex) { Utils.HandleError(ex); } }
public Task <int> Execute() { return(ConsoleTask.ExecuteAsync(this, async(console) => { console.WriteLine("Connecting to innovator..."); var conn = await this.GetConnection().ConfigureAwait(false); var processor = new ExportProcessor(conn); var refsToExport = default(List <ItemReference>); var checkDependencies = true; console.Write("Identifying items to export... "); if (this.InputFile?.EndsWith(".innpkg", StringComparison.OrdinalIgnoreCase) == true || this.InputFile?.EndsWith(".mf", StringComparison.OrdinalIgnoreCase) == true) { var exportScript = InnovatorPackage.Load(this.InputFile).Read(); refsToExport = exportScript.Lines .Where(l => l.Type == InstallType.Create) .Select(l => l.Reference) .Distinct() .ToList(); } else { var exportQuery = XElement.Parse("<AML><Item type='*' /></AML>"); if (!string.IsNullOrEmpty(this.InputFile)) { exportQuery = XElement.Load(this.InputFile); } var firstItem = exportQuery.XPathSelectElement("//Item[1]"); if (firstItem == null) { throw new Exception("No item nodes could be found"); } var items = default(IEnumerable <XElement>); if (firstItem.Parent == null) { items = new[] { firstItem } } ; else { items = firstItem.Parent.Elements("Item"); } var version = await conn.FetchVersion(true).ConfigureAwait(false); var types = ExportAllType.Types.Where(t => t.Applies(version)).ToList(); var queries = GetQueryies(items, types).ToList(); checkDependencies = items.All(e => e.Attribute("type")?.Value != "*"); using (var prog = console.Progress()) { var toExport = await SharedUtils.TaskPool(30, (l, m) => prog.Report(l / 100.0), queries .Select(q => { var aml = new XElement(q); var levels = aml.Attribute("levels"); if (levels != null) { levels.Remove(); } return (Func <Task <QueryAndResult> >)(() => conn.ApplyAsync(aml, true, false) .ToTask() .ContinueWith(t => new QueryAndResult() { Query = q, Result = t.Result })); }) .ToArray()); refsToExport = toExport.SelectMany(r => { var refs = r.Result.Items() .Select(i => ItemReference.FromFullItem(i, true)) .ToList(); var levels = (int?)r.Query.Attribute("levels"); if (levels.HasValue) { foreach (var iRef in refs) { iRef.Levels = levels.Value; } } return refs; }) .ToList(); } } console.WriteLine("Done."); var script = new InstallScript { ExportUri = new Uri(Url), ExportDb = Database, Lines = Enumerable.Empty <InstallItem>(), Title = Title ?? System.IO.Path.GetFileNameWithoutExtension(Output), Creator = Author ?? Username, Website = string.IsNullOrEmpty(Website) ? null : new Uri(Website), Description = Description, Created = DateTime.Now, Modified = DateTime.Now }; console.Write("Exporting metadata... "); using (var prog = console.Progress()) { processor.ProgressChanged += (s, e) => prog.Report(e.Progress / 100.0); processor.ActionComplete += (s, e) => { if (e.Exception != null) { throw new AggregateException(e.Exception); } }; await processor.Export(script, refsToExport, checkDependencies); } console.WriteLine("Done."); WritePackage(console, script, Output, MultipleDirectories, CleanOutput); })); }
public bool Write(InstallScript script, Func<string, DatabasePackageAction> errorHandler = null, Action<int, string> reportProgress = null) { var cont = true; var typeGroups = from l in script.Lines where l.Type == InstallType.Create group l by l.Reference.Type into typeGroup select typeGroup; var cnt = typeGroups.Count(); var idx = 0; var packageGroups = new HashSet<string>(); string currPackageId = null; while (cont) { IEnumerable<XmlElement> elements; foreach (var typeGroup in typeGroups) { if (reportProgress != null) reportProgress((int)(idx * 50.0 / cnt), string.Format("Checking for existing package elements ({0} of {1}) ", idx + 1, cnt)); if (typeGroup.First().Reference.Unique.IsGuid()) { elements = _conn.GetItems("ApplyItem", "<Item type=\"PackageElement\" action=\"get\" select=\"element_id,name,source_id\"><element_type>" + typeGroup.Key + "</element_type><element_id condition=\"in\">'" + typeGroup.Select(i => i.Reference.Unique).Aggregate((p, c) => p + "','" + c) + "'</element_id></Item>"); } else { elements = _conn.GetItems("ApplyItem", "<Item type=\"PackageElement\" action=\"get\" select=\"element_id,name,source_id\"><element_type>" + typeGroup.Key + "</element_type><element_id condition=\"in\">(select id from innovator.[" + typeGroup.Key.Replace(' ', '_') + "] where " + typeGroup.Select(i => i.Reference.Unique).Aggregate((p, c) => p + " or " + c) + ")</element_id></Item>"); } packageGroups.UnionWith(elements.Select(e => e.Element("source_id", ""))); idx++; } var packages = _conn.GetItems("ApplyItem", "<Item type=\"PackageDefinition\" action=\"get\" select=\"name\"><id condition=\"in\">(select SOURCE_ID FROM innovator.PACKAGEGROUP where id in ('" + packageGroups.Aggregate((p, c) => p + "','" + c) + "'))</id></Item>"); currPackageId = packages.Where(p => p.Element("name", "") == script.Title).SingleOrDefault().Attribute("id"); cont = false; if (packages.Any(p => p.Element("name", "") != script.Title)) { if (errorHandler != null) { var packageList = (from p in packages where p.Element("name", "") != script.Title select p.Element("name", "")) .Aggregate((p, c) => p + ", " + c); switch (errorHandler("The package cannot be created because one or more elements exist in the packages: " + packageList)) { case DatabasePackageAction.TryAgain: cont = true; break; case DatabasePackageAction.RemoveElementsFromPackages: foreach (var typeGroup in typeGroups) { if (reportProgress != null) reportProgress((int)(idx * 50.0 / cnt), string.Format("Removing package elements ({0} of {1}) ", idx + 1, cnt)); if (typeGroup.First().Reference.Unique.IsGuid()) { elements = _conn.GetItems("ApplyItem", "<Item type=\"PackageElement\" action=\"purge\" where=\"[PackageElement].[element_type] = '" + typeGroup.Key + "' and [PackageElement].[element_id] in ('" + typeGroup.Select(i => i.Reference.Unique).Aggregate((p, c) => p + "','" + c) + "')\" />"); } else { elements = _conn.GetItems("ApplyItem", "<Item type=\"PackageElement\" action=\"purge\" where=\"[PackageElement].[element_type] = '" + typeGroup.Key + "' and [PackageElement].[element_id] in (select id from innovator.[" + typeGroup.Key.Replace(' ', '_') + "] where " + typeGroup.Select(i => i.Reference.Unique).Aggregate((p, c) => p + " or " + c) + ")\" />"); } idx++; } break; default: return false; } } else { return false; } } } // Try one more time to get the package if (string.IsNullOrEmpty(currPackageId)) { var packages = _conn.GetItems("ApplyItem", "<Item type=\"PackageDefinition\" action=\"get\" select=\"name\"><name>" + script.Title + "</name></Item>"); currPackageId = packages.SingleOrDefault().Attribute("id"); } // Add the package if (string.IsNullOrEmpty(currPackageId)) { var packages = _conn.GetItems("ApplyItem", "<Item type=\"PackageDefinition\" action=\"add\" ><name>" + script.Title + "</name></Item>", true); currPackageId = packages.SingleOrDefault().Attribute("id"); } string groupId; foreach (var typeGroup in typeGroups) { if (reportProgress != null) reportProgress((int)(50 + idx * 50.0 / cnt), string.Format("Adding package elements of type ({0} of {1}) ", idx + 1, cnt)); groupId = _conn.GetItems("ApplyItem", "<Item type=\"PackageGroup\" action=\"merge\" where=\"[PackageGroup].[source_id] = '" + currPackageId + "' and [PackageGroup].[name] = '" + typeGroup.Key + "'\"><name>" + typeGroup.Key + "</name></Item>", true).SingleOrDefault().Attribute("id"); foreach (var elem in typeGroup) { _conn.GetItems("ApplyItem", "<Item type=\"PackageElement\" action=\"merge\" where=\"[PackageElement].[source_id] = '" + groupId + "' and [PackageElement].[element_id] = '" + (elem.InstalledId ?? elem.Reference.Unique) + "'\">" + "<element_type>" + typeGroup.Key + "</element_type>" + "<element_id>" + (elem.InstalledId ?? elem.Reference.Unique) + "</element_id>" + "<source_id>" + groupId + "</source_id>" + "<name>" + elem.Reference.KeyedName + "</name></Item>", true); } idx++; } return true; }
public IEnumerable<IEditorScript> GetScripts() { var items = (Items ?? Enumerable.Empty<IItemData>()) .Where(i => !string.IsNullOrEmpty(i.Id) && !string.IsNullOrEmpty(i.Type)) .ToArray(); if (!items.Any()) yield break; if (items.Skip(1).Any()) // There is more than one { if (items.OfType<DataRowItemData>().Any()) { yield return new EditorScriptExecute() { Name = "Delete", Execute = () => { foreach (var row in items.OfType<DataRowItemData>()) { row.Delete(); } return Task.FromResult(true); } }; } else { var builder = new StringBuilder("<AML>"); foreach (var item in items) { builder.AppendLine().AppendFormat(" <Item type='{0}' {1} action='delete'></Item>", item.Type, GetCriteria(item.Id)); } builder.AppendLine().Append("</AML>"); yield return new EditorScript() { Name = "Delete", Action = "ApplyAML", Script = builder.ToString() }; } var dataRows = items.OfType<DataRowItemData>() .OrderBy(r => r.Property("generation")).ThenBy(r => r.Id) .ToArray(); if (dataRows.Length == 2) // There are exactly two items { yield return new EditorScript() { Name = "------" }; yield return new EditorScriptExecute() { Name = "Compare", Execute = async () => { try { await Settings.Current.PerformDiff(dataRows[0].Id, dataRows[0].ToAml , dataRows[1].Id, dataRows[1].ToAml); } catch (Exception ex) { Utils.HandleError(ex); } } }; } yield return new EditorScript() { Name = "------" }; yield return new EditorScriptExecute() { Name = "Export", Execute = () => { var refs = items.OfType<ItemRefData>().Select(i => i.Ref); if (!refs.Any()) refs = items.Select(i => new ItemReference(i.Type, i.Id)); StartExport(refs); return Task.FromResult(true); } }; } else { var item = items.Single(); var rowItem = item as DataRowItemData; ArasMetadataProvider metadata = null; ItemType itemType = null; if (Conn != null) { metadata = ArasMetadataProvider.Cached(Conn); if (!metadata.ItemTypeByName(item.Type, out itemType)) metadata = null; } if (Conn != null) { yield return ArasEditorProxy.ItemTypeAddScript(Conn, itemType); } yield return new EditorScript() { Name = "------" }; if (rowItem == null) { var script = string.Format("<Item type='{0}' {1} action='edit'></Item>", item.Type, GetCriteria(item.Id)); if (item.Property("config_id") != null && itemType != null && itemType.IsVersionable) { script = string.Format("<Item type='{0}' where=\"[{1}].[config_id] = '{2}'\" action='edit'></Item>" , item.Type, item.Type.Replace(' ', '_'), item.Property("config_id")); } yield return new EditorScript() { Name = "Edit", Action = "ApplyItem", Script = script }; } else { if (!string.IsNullOrEmpty(Column)) { var prop = metadata.GetProperty(itemType, Column.Split('/')[0]).Wait(); switch (prop.Type) { case PropertyType.item: yield return new EditorScriptExecute() { Name = "Edit Value", Execute = () => { var query = string.Format("<Item type='{0}' action='get'><keyed_name condition='like'>**</keyed_name></Item>", prop.Restrictions.First()); var values = EditorWindow.GetItems(Conn, query, query.Length - 21); var results = values.Where(i => prop.Restrictions.Contains(i.Type)).ToArray(); if (results.Length == 1) { rowItem.SetProperty(prop.Name, results[0].Unique); rowItem.SetProperty(prop.Name + "/keyed_name", results[0].KeyedName); rowItem.SetProperty(prop.Name + "/type", results[0].Type); } return Task.FromResult(true); } }; break; } } } if (metadata != null) { yield return new EditorScript() { Name = "View \"" + (itemType.Label ?? itemType.Name) + "\"", Action = "ApplyItem", Script = string.Format("<Item type='{0}' {1} action='get' levels='1'></Item>", item.Type, GetCriteria(item.Id)), AutoRun = true, PreferredOutput = OutputType.Table }; if (item.Property("related_id") != null && itemType.Related != null) { yield return new EditorScript() { Name = "View \"" + (itemType.Related.Label ?? itemType.Related.Name) + "\"", Action = "ApplyItem", Script = string.Format("<Item type='{0}' id='{1}' action='get' levels='1'></Item>", itemType.Related.Name, item.Property("related_id")), AutoRun = true, PreferredOutput = OutputType.Table }; } } yield return new EditorScript() { Name = "------" }; if (rowItem == null) { yield return new EditorScript() { Name = "Delete", Action = "ApplyItem", Script = string.Format("<Item type='{0}' {1} action='delete'></Item>", item.Type, GetCriteria(item.Id)) }; } else { yield return new EditorScriptExecute() { Name = "Delete", Execute = () => { rowItem.Delete(); return Task.FromResult(true); } }; } if (item.Id.IsGuid()) { yield return new EditorScript() { Name = "Replace Item", Action = "ApplySql", ScriptGetter = async () => { var aml = string.Format("<Item type='{0}' action='get'><keyed_name condition='like'>**</keyed_name></Item>", item.Type); var replace = EditorWindow.GetItems(Conn, aml, aml.Length - 21); if (replace.Count() == 1) { var sqlItem = Conn.AmlContext.FromXml(_whereUsedSqlAml).AssertItem(); var export = new ExportProcessor(Conn); var script = new InstallScript(); var itemRef = ItemReference.FromFullItem(sqlItem, true); await export.Export(script, new[] { itemRef }); var existing = script.Lines.FirstOrDefault(i => i.Reference.Equals(itemRef)); var needsSql = true; if (existing != null) { var merge = AmlDiff.GetMergeScript(XmlReader.Create(new StringReader(_whereUsedSqlAml)), new XmlNodeReader(existing.Script)); needsSql = merge.Elements().Any(); } if (needsSql) { if (Dialog.MessageDialog.Show("To run this action, InnovatorAdmin needs to install the SQL WhereUsed_General into the database. Do you want to install this?", "Install SQL", "Install", "Cancel") == System.Windows.Forms.DialogResult.OK) { await Conn.ApplyAsync(_whereUsedSqlAml, true, false).ToTask(); } else { return null; } } var result = await Conn.ApplyAsync(@"<AML> <Item type='SQL' action='SQL PROCESS'> <name>WhereUsed_General</name> <PROCESS>CALL</PROCESS> <ARG1>@0</ARG1> <ARG2>@1</ARG2> </Item> </AML>", true, false, item.Type, item.Id).ToTask(); var sql = new StringBuilder("<sql>"); var whereUsed = result.Items().Where(i => !i.Property("type").HasValue() || i.Property("type").Value == i.Property("parent_type").Value); var replaceId = replace.First().Unique; sql.AppendLine(); foreach (var i in whereUsed) { var props = (from p in i.Elements().OfType<IReadOnlyProperty>() where p.Name.Length == 2 && p.Name[0] == 'p' && char.IsNumber(p.Name[1]) select p.Value).GroupConcat(" = '" + replaceId + "',"); sql.Append("update innovator.[").Append(i.Property("main_type").Value.Replace(' ', '_')).Append("] set "); sql.Append(props).Append(" = '").Append(replaceId).Append("'"); sql.Append(" where id ='").Append(i.Property("main_id").Value).Append("';"); sql.AppendLine(); } sql.Append("</sql>"); return sql.ToString(); } return null; } }; } yield return new EditorScript() { Name = "------" }; yield return new EditorScriptExecute() { Name = "Export", Execute = () => { var refs = new[] { new ItemReference(item.Type, item.Id) }; StartExport(refs); return Task.FromResult(true); } }; yield return new EditorScript() { Name = "------" }; yield return new EditorScript() { Name = "Lock", Action = "ApplyItem", Script = string.Format("<Item type='{0}' {1} action='lock'></Item>", item.Type, GetCriteria(item.Id)) }; yield return new EditorScript() { Name = "------" }; if (itemType != null && itemType.IsVersionable) { var whereClause = "id='" + item.Id + "'"; if (!item.Id.IsGuid()) whereClause = item.Id; yield return new EditorScript() { Name = "Revisions", AutoRun = true, Action = "ApplyItem", PreferredOutput = OutputType.Table, Script = string.Format(@"<Item type='{0}' action='get' orderBy='generation'> <config_id condition='in'>(select config_id from innovator.[{1}] where {2})</config_id> <generation condition='gt'>0</generation> </Item>", item.Type, item.Type.Replace(' ', '_'), whereClause) }; yield return new EditorScript() { Name = "------" }; } yield return new EditorScript() { Name = "Promote", Action = "ApplyItem", Script = string.Format("<Item type='{0}' {1} action='promoteItem'></Item>", item.Type, GetCriteria(item.Id)) }; yield return new EditorScript() { Name = "------" }; yield return new EditorScript() { Name = "Where Used", AutoRun = true, Action = "ApplyItem", Script = string.Format("<Item type='{0}' {1} action='getItemWhereUsed'></Item>", item.Type, GetCriteria(item.Id)) }; yield return new EditorScript() { Name = "Structure Browser", Action = "ApplyItem", AutoRun = true, Script = string.Format(@"<Item type='Method' action='GetItemsForStructureBrowser'> <Item type='{0}' {1} action='GetItemsForStructureBrowser' levels='2' /> </Item>", item.Type, GetCriteria(item.Id)) }; yield return new EditorScript() { Name = "------" }; if (metadata != null) { var actions = new EditorScript() { Name = "Actions" }; var serverActions = metadata.ServerItemActions(item.Type) .OrderBy(l => l.Label ?? l.Value, StringComparer.CurrentCultureIgnoreCase) .ToArray(); foreach (var action in serverActions) { actions.Add(new EditorScript() { Name = (action.Label ?? action.Value), Action = "ApplyItem", Script = string.Format("<Item type='{0}' {1} action='{2}'></Item>", item.Type, GetCriteria(item.Id), action.Value), AutoRun = true }); } if (serverActions.Any()) yield return actions; var reports = new EditorScript() { Name = "Reports" }; var serverReports = metadata.ServerReports(item.Type) .OrderBy(l => l.Label ?? l.Value, StringComparer.CurrentCultureIgnoreCase) .ToArray(); foreach (var report in serverReports) { reports.Add(new EditorScript() { Name = (report.Label ?? report.Value), Action = "ApplyItem", Script = @"<Item type='Method' action='Run Report'> <report_name>" + report.Value + @"</report_name> <AML> <Item type='" + itemType.Name + "' typeId='" + itemType.Id + "' " + GetCriteria(item.Id) + @" /> </AML> </Item>", AutoRun = true }); } if (serverReports.Any()) yield return reports; } if (item.Id.IsGuid()) { yield return new EditorScriptExecute() { Name = "Copy ID", Execute = () => { System.Windows.Clipboard.SetText(item.Id); return Task.FromResult(true); } }; } } }
public virtual void Write(InstallScript script) { string newPath; var existingPaths = new HashSet<string>(); // Record the import order var settings = new XmlWriterSettings(); settings.OmitXmlDeclaration = true; settings.Indent = true; settings.IndentChars = " "; using (var manifestStream = GetNewStream(null)) { using (var manifestWriter = XmlWriter.Create(manifestStream, settings)) { manifestWriter.WriteStartElement("Import"); if (script.Created.HasValue) manifestWriter.WriteAttributeString("created", script.Created.Value.ToString("s")); manifestWriter.WriteAttributeString("creator", script.Creator); manifestWriter.WriteAttributeString("description", script.Description); if (script.Modified.HasValue) manifestWriter.WriteAttributeString("modified", script.Modified.Value.ToString("s")); manifestWriter.WriteAttributeString("revision", script.Version); manifestWriter.WriteAttributeString("title", script.Title); if (script.Website != null) manifestWriter.WriteAttributeString("website", script.Website.ToString()); InstallItem first; foreach (var group in script.GroupLines()) { first = group.First(); if (first.Type == InstallType.DependencyCheck) { foreach (var line in group) { line.Script.WriteTo(manifestWriter); } } else { switch (first.Reference.Type) { case "Report": newPath = first.Reference.Type + "\\" + CleanFileName(first.Reference.KeyedName ?? first.Reference.Unique) + ".xslt"; if (existingPaths.Contains(newPath)) newPath = first.Reference.Type + "\\" + CleanFileName((first.Reference.KeyedName ?? "") + "_" + first.Reference.Unique) + ".xslt"; WriteReport(group, newPath); break; default: newPath = first.Reference.Type + "\\" + CleanFileName(first.Reference.KeyedName ?? first.Reference.Unique) + ".xml"; if (existingPaths.Contains(newPath)) newPath = first.Reference.Type + "\\" + CleanFileName((first.Reference.KeyedName ?? "") + "_" + first.Reference.Unique) + ".xml"; using (var stream = GetNewStream(newPath)) { using (var writer = GetWriter(stream)) { writer.WriteStartElement("AML"); foreach (var line in group) { line.Script.WriteTo(writer); } writer.WriteEndElement(); } } break; } existingPaths.Add(newPath); manifestWriter.WriteStartElement("Path"); manifestWriter.WriteAttributeString("path", newPath); manifestWriter.WriteEndElement(); } } manifestWriter.WriteEndElement(); } } }
private void btnPackageFile_Click(object sender, EventArgs e) { try { using (var dialog = new OpenFileDialog()) { dialog.Filter = "Innovator Package (.innpkg)|*.innpkg|Manifest (.mf)|*.mf"; if (dialog.ShowDialog() == DialogResult.OK) { if (Path.GetExtension(dialog.FileName) == ".innpkg") { using (var pkg = InnovatorPackage.Load(dialog.FileName)) { var installScript = pkg.Read(); _availableRefs.Clear(); foreach (var item in installScript.Lines.Where(l => l.Type == InstallType.Create).Select(l => l.Reference)) { if (!_selectedRefs.Contains(item)) _selectedRefs.Add(item); } _existingScript = installScript; _existingScript.Lines = null; } } else { var pkg = new ManifestFolder(dialog.FileName); string title; var doc = pkg.Read(out title); foreach (var item in ItemReference.FromFullItems(doc.DocumentElement, true)) { if (!_selectedRefs.Contains(item)) _selectedRefs.Add(item); } _existingScript = _existingScript ?? new InstallScript(); _existingScript.Title = title; } EnsureResultsTab(); tbcSearch.SelectedTab = pgResults; txtFind.Focus(); } } } catch (Exception ex) { Utils.HandleError(ex); } }
public static IEnumerable<InstallItemDiff> GetDiffs(InstallScript left, InstallScript right) { return GetDiffs(left.Lines, right.Lines); }
private void GetPatchPackage(InstallScript start, InstallScript dest) { var docs = new List<Tuple<XmlDocument, string>>(); ProgressDialog.Display(this, d => { start.WriteAmlMergeScripts(dest, (path, prog) => { d.SetProgress(prog); var doc = new XmlDocument(); docs.Add(Tuple.Create(doc, path)); return new XmlNodeWriter(doc); }); }); var items = (from d in docs where d.Item1.DocumentElement != null select InstallItem.FromScript(GetFirstItem(d.Item1.DocumentElement), d.Item2)) .ToArray(); _wizard.InstallScript = new InstallScript() { Lines = items }; _wizard.GoToStep(new ExportOptions()); }
private void btnDbPackage_Click(object sender, EventArgs e) { try { var items = _conn.Apply(@"<Item type='PackageDefinition' action='get' select='id' />").Items(); var refs = new List<ItemReference>(); foreach (var item in items) { refs.Add(ItemReference.FromFullItem(item, true)); } using (var dialog = new FilterSelect<ItemReference>()) { dialog.DataSource = refs; dialog.DisplayMember = "KeyedName"; dialog.Message = resources.Messages.PackageSelect; if (dialog.ShowDialog(this, btnDbPackage.RectangleToScreen(btnDbPackage.Bounds)) == DialogResult.OK && dialog.SelectedItem != null) { txtFind.Text = ""; _findAction = DefaultFindAction; items = _conn.Apply(@"<Item type='PackageElement' action='get' select='element_id,element_type,name' orderBy='element_type,name,element_id'> <source_id condition='in'>(select id from innovator.PACKAGEGROUP where SOURCE_ID = @0)</source_id> </Item>", dialog.SelectedItem.Unique).Items(); _availableRefs.Clear(); ItemReference newRef; foreach (var item in items) { newRef = new ItemReference() { Type = item.Property("element_type").AsString(""), Unique = item.Property("element_id").AsString(""), KeyedName = item.Property("name").AsString("") }; if (!_selectedRefs.Contains(newRef)) _selectedRefs.Add(newRef); } _existingScript = _existingScript ?? new InstallScript(); _existingScript.Title = dialog.SelectedItem.KeyedName; EnsureResultsTab(); tbcSearch.SelectedTab = pgResults; txtFind.Focus(); } } } catch (Exception ex) { Utils.HandleError(ex); } }
public void Export(InstallScript script, XmlDocument doc, HashSet<ItemReference> warnings = null) { try { EnsureSystemData(); FixPolyItemReferences(doc); FixForeignProperties(doc); FixCyclicalWorkflowLifeCycleRefs(doc); FixCyclicalWorkflowItemTypeRefs(doc); MoveFormRefsInline(doc, (script.Lines ?? Enumerable.Empty<InstallItem>()).Where(l => l.Type == InstallType.Create || l.Type == InstallType.Script)); // Sort the resulting nodes as appropriate ReportProgress(98, "Sorting the results"); XmlNode itemNode = doc.DocumentElement; while (itemNode != null && itemNode.LocalName != "Item") itemNode = itemNode.Elements().FirstOrDefault(); if (itemNode == null) throw new InvalidOperationException(); //TODO: Give better error information here (e.g. interpret an error item if present) int loops = 0; CycleState state = CycleState.ResolvedCycle; IEnumerable<InstallItem> results = null; while (loops < 10 && state == CycleState.ResolvedCycle) { // Only reset if this is not a rescan if (script.Lines != null) { _dependAnalyzer.Reset(from l in script.Lines where l.Type == InstallType.Create || l.Type == InstallType.Script select l.Reference); } else { _dependAnalyzer.Reset(); } var newInstallItems = (from e in itemNode.ParentNode.Elements() where e.LocalName == "Item" && e.HasAttribute("type") select InstallItem.FromScript(e)).ToList(); foreach (var newInstallItem in newInstallItems) { _dependAnalyzer.GatherDependencies(newInstallItem.Script, newInstallItem.Reference, newInstallItem.CoreDependencies); } _dependAnalyzer.CleanDependencies(); results = GetDependencyList((script.Lines ?? Enumerable.Empty<InstallItem>()) .Concat(newInstallItems), out state).ToList(); loops++; } if (warnings == null) warnings = new HashSet<ItemReference>(); warnings.ExceptWith(results.Select(r => r.Reference)); script.Lines = warnings.Select(w => InstallItem.FromWarning(w, w.KeyedName)) .Concat(results.Where(r => r.Type == InstallType.DependencyCheck || r.Type == InstallType.Warning)) .OrderBy(r => r.Name) .ToList() .Concat(results.Where(r => r.Type != InstallType.DependencyCheck && r.Type != InstallType.Warning)) .ToList(); RemoveInjectedDependencies(doc); this.OnActionComplete(new ActionCompleteEventArgs()); } catch (Exception ex) { this.OnActionComplete(new ActionCompleteEventArgs() { Exception = ex }); } }
public void RemoveReferencingItems(InstallScript script, ItemReference itemRef) { var nodes = _dependAnalyzer.RemoveDependencyContexts(itemRef); script.Lines = script.Lines.Where(l => !(l.Type == InstallType.Create || l.Type == InstallType.Script) || !nodes.Contains(l.Script)).ToList(); }
public void Export(InstallScript script, IEnumerable<ItemReference> items) { ReportProgress(0, "Loading system data"); EnsureSystemData(); var uniqueItems = new HashSet<ItemReference>(items); if (script.Lines != null) uniqueItems.ExceptWith(script.Lines.Select(l => l.Reference)); var itemList = uniqueItems.ToList(); ItemType metaData; var outputDoc = new XmlDocument(); outputDoc.AppendChild(outputDoc.CreateElement("AML")); XmlElement queryElem; var whereClause = new StringBuilder(); ConvertPolyItemReferencesToActualType(itemList); string itemType; foreach (var typeItems in (from i in itemList group i by new { Type = i.Type, Levels = i.Levels } into typeGroup select typeGroup)) { whereClause.Length = 0; itemType = typeItems.Key.Type; // For versionable item types, get the latest generation if (_itemTypesByName.TryGetValue(typeItems.Key.Type.ToLowerInvariant(), out metaData) && metaData.IsVersionable) { queryElem = outputDoc.CreateElement("Item") .Attr("action", "get") .Attr("type", typeItems.Key.Type); if (typeItems.Any(i => i.Unique.IsGuid())) { whereClause.Append("[") .Append(typeItems.Key.Type.Replace(' ', '_')) .Append("].[config_id] in (select config_id from innovator.[") .Append(typeItems.Key.Type.Replace(' ', '_')) .Append("] where id in ('") .Append(typeItems.Where(i => i.Unique.IsGuid()).Select(i => i.Unique).Aggregate((p, c) => p + "','" + c)) .Append("'))"); } if (typeItems.Any(i => !i.Unique.IsGuid())) { whereClause.AppendSeparator(" or ", typeItems.Where(i => !i.Unique.IsGuid()).Select(i => i.Unique).Aggregate((p, c) => p + " or " + c)); } queryElem.SetAttribute("where", whereClause.ToString()); } else if (typeItems.Key.Type == "ItemType") { // Make sure relationship item types aren't accidentally added queryElem = outputDoc.CreateElement("Item").Attr("action", "get").Attr("type", typeItems.Key.Type); if (typeItems.Any(i => i.Unique.IsGuid())) { whereClause.Append("[ItemType].[id] in ('") .Append(typeItems.Where(i => i.Unique.IsGuid()).Select(i => i.Unique).Aggregate((p, c) => p + "','" + c)) .Append("')"); } if (typeItems.Any(i => !i.Unique.IsGuid())) { whereClause.AppendSeparator(" or ", typeItems.Where(i => !i.Unique.IsGuid()).Select(i => i.Unique).Aggregate((p, c) => p + " or " + c)); } queryElem.SetAttribute("where", "(" + whereClause.ToString() + ") and [ItemType].[is_relationship] = '0'"); SetQueryAttributes(queryElem, typeItems.Key.Type, typeItems.Key.Levels, typeItems); outputDoc.DocumentElement.AppendChild(queryElem); queryElem = outputDoc.CreateElement("Item") .Attr("action", "get") .Attr("type", "RelationshipType") .Attr("where", "[RelationshipType].[relationship_id] in (select id from innovator.[ItemType] where " + whereClause.ToString() + ")"); itemType = "RelationshipType"; } else if (typeItems.Key.Type == "List") { // Filter out auto-generated lists for polymorphic item types queryElem = outputDoc.CreateElement("Item") .Attr("action", "get") .Attr("type", typeItems.Key.Type); if (typeItems.Any(i => i.Unique.IsGuid())) { whereClause.Append("[List].[id] in ('") .Append(typeItems.Where(i => i.Unique.IsGuid()).Select(i => i.Unique).Aggregate((p, c) => p + "','" + c)) .Append("')"); } if (typeItems.Any(i => !i.Unique.IsGuid())) { whereClause.AppendSeparator(" or ", typeItems.Where(i => !i.Unique.IsGuid()).Select(i => i.Unique).Aggregate((p, c) => p + " or " + c)); } queryElem.SetAttribute("where", "(" + whereClause.ToString() + ") " + Properties.Resources.ListSqlCriteria); } else { queryElem = outputDoc.CreateElement("Item") .Attr("action", "get") .Attr("type", typeItems.Key.Type); if (typeItems.Any(i => i.Unique.IsGuid())) { whereClause.Append("[") .Append(typeItems.Key.Type.Replace(' ', '_')) .Append("].[id] in ('") .Append(typeItems.Where(i => i.Unique.IsGuid()).Select(i => i.Unique).Aggregate((p, c) => p + "','" + c)) .Append("')"); } if (typeItems.Any(i => !i.Unique.IsGuid())) { whereClause.AppendSeparator(" or ", typeItems.Where(i => !i.Unique.IsGuid()).Select(i => i.Unique).Aggregate((p, c) => p + " or " + c)); } queryElem.SetAttribute("where", whereClause.ToString()); } SetQueryAttributes(queryElem, typeItems.Key.Type, typeItems.Key.Levels, typeItems); outputDoc.DocumentElement.AppendChild(queryElem); } try { ReportProgress(0, "Loading system data"); EnsureSystemData(); FixFederatedRelationships(outputDoc.DocumentElement); var result = ExecuteExportQuery(outputDoc.DocumentElement); // Add warnings for embedded relationships var warnings = new HashSet<ItemReference>(); ItemReference warning; foreach (var relType in result.ElementsByXPath("/Result/Item[@type='ItemType']/Relationships/Item[@type='RelationshipType']")) { warning = ItemReference.FromFullItem(relType as XmlElement, true); warning.KeyedName = "* Possible missing relationship: " + warning.KeyedName; warnings.Add(warning); } RemoveRelatedItems(result, items); CleanUpSystemProps(result, items, false); FixPolyItemReferences(result); FloatVersionableRefs(result); var doc = TransformResults(result.DocumentElement); NormalizeClassStructure(doc); RemoveKeyedNameAttributes(doc); ExpandSystemIdentities(doc); FixFormFieldsPointingToSystemProperties(doc); //TODO: Replace references to poly item lists Export(script, doc, warnings); CleanUpSystemProps(doc, items, true); ConvertFloatProps(doc); if (string.IsNullOrWhiteSpace(script.Title)) { if (script.Lines.Count(l => l.Type == InstallType.Create) == 1) { script.Title = script.Lines.Single(l => l.Type == InstallType.Create).Reference.ToString(); } else if (items.Count() == 1) { script.Title = items.First().ToString(); } } } catch (Exception ex) { this.OnActionComplete(new ActionCompleteEventArgs() { Exception = ex }); } }
public IEnumerable <IEditorScript> GetScripts() { var items = (Items ?? Enumerable.Empty <IItemData>()) .Where(i => !string.IsNullOrEmpty(i.Id) && !string.IsNullOrEmpty(i.Type)) .ToArray(); if (!items.Any()) { yield break; } if (items.Skip(1).Any()) // There is more than one { if (items.OfType <DataRowItemData>().Any()) { yield return(new EditorScriptExecute() { Name = "Delete", Execute = () => { foreach (var row in items.OfType <DataRowItemData>()) { row.Delete(); } return Task.FromResult(true); } }); } else { var builder = new StringBuilder("<AML>"); foreach (var item in items) { builder.AppendLine().AppendFormat(" <Item type='{0}' {1} action='delete'></Item>", item.Type, GetCriteria(item.Id)); } builder.AppendLine().Append("</AML>"); yield return(new EditorScript() { Name = "Delete", Action = "ApplyAML", Script = builder.ToString() }); } var dataRows = items.OfType <DataRowItemData>() .OrderBy(r => r.Property("generation")).ThenBy(r => r.Id) .ToArray(); if (dataRows.Length == 2) // There are exactly two items { yield return(new EditorScript() { Name = "------" }); yield return(new EditorScriptExecute() { Name = "Compare", Execute = async() => { try { await Settings.Current.PerformDiff(dataRows[0].Id, dataRows[0].ToAml , dataRows[1].Id, dataRows[1].ToAml); } catch (Exception ex) { Utils.HandleError(ex); } } }); } yield return(new EditorScript() { Name = "------" }); yield return(new EditorScriptExecute() { Name = "Export", Execute = () => { var refs = items.OfType <ItemRefData>().Select(i => i.Ref); if (!refs.Any()) { refs = items.Select(i => new ItemReference(i.Type, i.Id)); } StartExport(refs); return Task.FromResult(true); } }); } else { var item = items.Single(); var rowItem = item as DataRowItemData; ArasMetadataProvider metadata = null; ItemType itemType = null; if (Conn != null) { metadata = ArasMetadataProvider.Cached(Conn); if (!metadata.ItemTypeByName(item.Type, out itemType)) { metadata = null; } } if (Conn != null) { yield return(ArasEditorProxy.ItemTypeAddScript(Conn, itemType)); } if (item is EditorItemData data) { yield return(new EditorScript() { Name = "Clone as New", Action = "ApplyItem", ScriptGetter = () => { var aml = data.ToItem(Conn.AmlContext).CloneAsNew().ToAml(); return Task.FromResult(XElement.Parse(aml).ToString()); } }); } yield return(new EditorScript() { Name = "------" }); if (rowItem == null) { var script = string.Format("<Item type='{0}' {1} action='edit'></Item>", item.Type, GetCriteria(item.Id)); if (item.Property("config_id") != null && itemType != null && itemType.IsVersionable) { script = string.Format("<Item type='{0}' where=\"[{1}].[config_id] = '{2}'\" action='edit'></Item>" , item.Type, item.Type.Replace(' ', '_'), item.Property("config_id")); } yield return(new EditorScript() { Name = "Edit", Action = "ApplyItem", Script = script }); } else { if (!string.IsNullOrEmpty(Column)) { var prop = metadata.GetProperty(itemType, Column.Split('/')[0]).Wait(); switch (prop.Type) { case PropertyType.item: yield return(new EditorScriptExecute() { Name = "Edit Value", Execute = () => { var query = string.Format("<Item type='{0}' action='get'><keyed_name condition='like'>**</keyed_name></Item>", prop.Restrictions.First()); var values = EditorWindow.GetItems(Conn, query, query.Length - 21); var results = values.Where(i => prop.Restrictions.Contains(i.Type)).ToArray(); if (results.Length == 1) { rowItem.SetProperty(prop.Name, results[0].Unique); rowItem.SetProperty(prop.Name + "/keyed_name", results[0].KeyedName); rowItem.SetProperty(prop.Name + "/type", results[0].Type); } return Task.FromResult(true); } }); break; } } } if (metadata != null) { yield return(new EditorScript() { Name = "View \"" + (itemType.Label ?? itemType.Name) + "\"", Action = "ApplyItem", Script = string.Format("<Item type='{0}' {1} action='get' levels='1'></Item>", item.Type, GetCriteria(item.Id)), AutoRun = true, PreferredOutput = OutputType.Table }); if (item.Property("related_id") != null && itemType.Related != null) { yield return(new EditorScript() { Name = "View \"" + (itemType.Related.Label ?? itemType.Related.Name) + "\"", Action = "ApplyItem", Script = string.Format("<Item type='{0}' id='{1}' action='get' levels='1'></Item>", itemType.Related.Name, item.Property("related_id")), AutoRun = true, PreferredOutput = OutputType.Table }); } } yield return(new EditorScript() { Name = "------" }); if (rowItem == null) { yield return(new EditorScript() { Name = "Delete", Action = "ApplyItem", Script = string.Format("<Item type='{0}' {1} action='delete'></Item>", item.Type, GetCriteria(item.Id)) }); } else { yield return(new EditorScriptExecute() { Name = "Delete", Execute = () => { rowItem.Delete(); return Task.FromResult(true); } }); } if (item.Id.IsGuid()) { yield return(new EditorScript() { Name = "Replace Item", Action = "ApplySql", ScriptGetter = async() => { var aml = string.Format("<Item type='{0}' action='get'><keyed_name condition='like'>**</keyed_name></Item>", item.Type); var replace = EditorWindow.GetItems(Conn, aml, aml.Length - 21); if (replace.Count() == 1) { var sqlItem = Conn.AmlContext.FromXml(_whereUsedSqlAml).AssertItem(); var export = new ExportProcessor(Conn); var script = new InstallScript(); var itemRef = ItemReference.FromFullItem(sqlItem, true); await export.Export(script, new[] { itemRef }); var existing = script.Lines.FirstOrDefault(i => i.Reference.Equals(itemRef)); var needsSql = true; if (existing != null) { var merge = AmlDiff.GetMergeScript(XmlReader.Create(new StringReader(_whereUsedSqlAml)), new XmlNodeReader(existing.Script)); needsSql = merge.Elements().Any(); } if (needsSql) { if (Dialog.MessageDialog.Show("To run this action, InnovatorAdmin needs to install the SQL WhereUsed_General into the database. Do you want to install this?", "Install SQL", "Install", "Cancel") == System.Windows.Forms.DialogResult.OK) { await Conn.ApplyAsync(_whereUsedSqlAml, true, false).ToTask(); } else { return null; } } var result = await Conn.ApplyAsync(@"<AML> <Item type='SQL' action='SQL PROCESS'> <name>WhereUsed_General</name> <PROCESS>CALL</PROCESS> <ARG1>@0</ARG1> <ARG2>@1</ARG2> </Item> </AML>", true, false, item.Type, item.Id).ToTask(); var sql = new StringBuilder("<sql>"); var whereUsed = result.Items().Where(i => !i.Property("type").HasValue() || i.Property("type").Value == i.Property("parent_type").Value); var replaceId = replace.First().Unique; sql.AppendLine(); foreach (var i in whereUsed) { var props = (from p in i.Elements().OfType <IReadOnlyProperty>() where p.Name.Length == 2 && p.Name[0] == 'p' && char.IsNumber(p.Name[1]) select p.Value).GroupConcat(" = '" + replaceId + "',"); sql.Append("update innovator.[").Append(i.Property("main_type").Value.Replace(' ', '_')).Append("] set "); sql.Append(props).Append(" = '").Append(replaceId).Append("'"); sql.Append(" where id ='").Append(i.Property("main_id").Value).Append("';"); sql.AppendLine(); } sql.Append("</sql>"); return sql.ToString(); } return null; } }); } yield return(new EditorScript() { Name = "------" }); yield return(new EditorScriptExecute() { Name = "Export", Execute = () => { var refs = new[] { new ItemReference(item.Type, item.Id) }; StartExport(refs); return Task.FromResult(true); } }); yield return(new EditorScript() { Name = "------" }); yield return(new EditorScript() { Name = "Lock", Action = "ApplyItem", Script = string.Format("<Item type='{0}' {1} action='lock'></Item>", item.Type, GetCriteria(item.Id)) }); yield return(new EditorScript() { Name = "------" }); if (itemType != null && itemType.IsVersionable) { var whereClause = "id='" + item.Id + "'"; if (!item.Id.IsGuid()) { whereClause = item.Id; } yield return(new EditorScript() { Name = "Revisions", AutoRun = true, Action = "ApplyItem", PreferredOutput = OutputType.Table, Script = string.Format(@"<Item type='{0}' action='get' orderBy='generation'> <config_id condition='in'>(select config_id from innovator.[{1}] where {2})</config_id> <generation condition='gt'>0</generation> </Item>", item.Type, item.Type.Replace(' ', '_'), whereClause) }); yield return(new EditorScript() { Name = "------" }); } yield return(new EditorScript() { Name = "Promote", Action = "ApplyItem", Script = string.Format("<Item type='{0}' {1} action='promoteItem'></Item>", item.Type, GetCriteria(item.Id)) }); yield return(new EditorScript() { Name = "------" }); yield return(new EditorScript() { Name = "Where Used", AutoRun = true, Action = "ApplyItem", Script = string.Format("<Item type='{0}' {1} action='getItemWhereUsed'></Item>", item.Type, GetCriteria(item.Id)) }); yield return(new EditorScript() { Name = "Structure Browser", Action = "ApplyItem", AutoRun = true, Script = string.Format(@"<Item type='Method' action='GetItemsForStructureBrowser'> <Item type='{0}' {1} action='GetItemsForStructureBrowser' levels='2' /> </Item>", item.Type, GetCriteria(item.Id)) }); yield return(new EditorScript() { Name = "------" }); if (metadata != null) { var actions = new EditorScript() { Name = "Actions" }; var serverActions = metadata.ServerItemActions(item.Type) .OrderBy(l => l.Label ?? l.Value, StringComparer.CurrentCultureIgnoreCase) .ToArray(); foreach (var action in serverActions) { actions.Add(new EditorScript() { Name = (action.Label ?? action.Value), Action = "ApplyItem", Script = string.Format("<Item type='{0}' {1} action='{2}'></Item>", item.Type, GetCriteria(item.Id), action.Value), AutoRun = true }); } if (serverActions.Any()) { yield return(actions); } var reports = new EditorScript() { Name = "Reports" }; var serverReports = metadata.ServerReports(item.Type) .OrderBy(l => l.Label ?? l.Value, StringComparer.CurrentCultureIgnoreCase) .ToArray(); foreach (var report in serverReports) { reports.Add(new EditorScript() { Name = (report.Label ?? report.Value), Action = "ApplyItem", Script = @"<Item type='Method' action='Run Report'> <report_name>" + report.Value + @"</report_name> <AML> <Item type='" + itemType.Name + "' typeId='" + itemType.Id + "' " + GetCriteria(item.Id) + @" /> </AML> </Item>", AutoRun = true }); } if (serverReports.Any()) { yield return(reports); } } if (item.Id.IsGuid()) { yield return(new EditorScriptExecute() { Name = "Copy ID", Execute = () => { System.Windows.Clipboard.SetText(item.Id); return Task.FromResult(true); } }); } } }
public Task <int> Execute() { return(ConsoleTask.ExecuteAsync(this, async(console) => { console.WriteLine("Connecting to innovator..."); var conn = await this.GetConnection().ConfigureAwait(false); var processor = new ExportProcessor(conn); var refsToExport = default(List <ItemReference>); var checkDependencies = true; if (string.IsNullOrEmpty(this.InputFile)) { var version = await conn.FetchVersion(true).ConfigureAwait(false); var types = ExportAllType.Types.Where(t => t.Applies(version)).ToList(); console.Write("Identifying all metadata items... "); using (var prog = console.Progress()) { var toExport = await SharedUtils.TaskPool(30, (l, m) => prog.Report(l / 100.0), types .Select(t => (Func <Task <IReadOnlyResult> >)(() => conn.ApplyAsync(t.ToString(), true, false).ToTask())) .ToArray()); refsToExport = toExport.SelectMany(r => r.Items()) .Select(i => ItemReference.FromFullItem(i, true)) .ToList(); } console.WriteLine("Done."); checkDependencies = false; } else { throw new NotSupportedException("Input package is not supported"); } var script = new InstallScript { ExportUri = new Uri(Url), ExportDb = Database, Lines = Enumerable.Empty <InstallItem>(), Title = Title ?? System.IO.Path.GetFileNameWithoutExtension(Output), Creator = Author ?? Username, Website = string.IsNullOrEmpty(Website) ? null : new Uri(Website), Description = Description, Created = DateTime.Now, Modified = DateTime.Now }; console.Write("Exporting metadata... "); using (var prog = console.Progress()) { processor.ProgressChanged += (s, e) => prog.Report(e.Progress / 100.0); processor.ActionComplete += (s, e) => { if (e.Exception != null) { throw new AggregateException(e.Exception); } }; await processor.Export(script, refsToExport, checkDependencies); } console.WriteLine("Done."); WritePackage(console, script, Output, MultipleDirectories, CleanOutput); })); }