Exemplo n.º 1
0
        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);
        }
Exemplo n.º 2
0
        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);
                        }
                    });
                }
            }
        }
Exemplo n.º 3
0
        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 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);
            }
          };
        }
      }
    }
Exemplo n.º 5
0
        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);
            }));
        }