public IEnumerable <IListValue> ServerReports(string typeName)
        {
            IEnumerable <IListValue> result;

            if (_serverReports.TryGetValue(typeName, out result))
            {
                return(result);
            }

            var items = _conn.Apply(@"<Item type='Item Report' action='get' select='related_id(name,label)'>
  <related_id>
    <Item type='Report' action='get'>
      <location>server</location>
      <type>item</type>
    </Item>
  </related_id>
  <source_id>
    <Item type='ItemType' action='get'>
      <name>@0</name>
    </Item>
  </source_id>
</Item>", typeName).Items();

            result = items.Select(r => new ListValue()
            {
                Label = r.RelatedItem().Property("label").Value,
                Value = r.RelatedItem().Property("name").Value
            }).ToArray();
            _serverReports[typeName] = result;
            return(result);
        }
Esempio n. 2
0
        private void FindByItem(string type)
        {
            if (!string.IsNullOrEmpty(_lastQuery) && !string.IsNullOrEmpty(txtFind.Text) && txtFind.Text.StartsWith(_lastQuery))
            {
                DefaultFindAction();
            }
            else
            {
                _availableRefs.Clear();

                var results = _conn.Apply(@"<Item type='@0' action='get' maxRecords='1000' orderBy='keyed_name' select='id,source_id,related_id'>
                                      <keyed_name condition='like'>@1</keyed_name>
                                    </Item>"
                                          , type, "*" + txtFind.Text + "*").Items();
                if (results.Count() >= 1000)
                {
                    _availableRefs.Add(_searchMessage);
                }
                else
                {
                    foreach (var result in results)
                    {
                        _availableRefs.Add(ItemReference.FromFullItem(result, true));
                    }
                    _lastQuery = txtFind.Text;
                }
            }
        }
        private void btnOk_Click(object sender, EventArgs e)
        {
            try
            {
                _results.Clear();
                IEnumerable <IReadOnlyItem> queryResults;
                foreach (var itemType in _selectedTypes)
                {
                    if (txtModifiedBy.Text == _currUserKeyedName)
                    {
                        queryResults = _conn.Apply(@"<Item type='@0' action='get'>
                                          <modified_by_id>@1</modified_by_id>
                                          <modified_on condition='gt'>@2</modified_on>
                                        </Item>"
                                                   , itemType.KeyedName
                                                   , _conn.UserId
                                                   , DateTime.Today.AddDays(-1 * (double)nudDays.Value)).Items();
                    }
                    else
                    {
                        queryResults = _conn.Apply(@"<Item type='@0' action='get'>
                                          <modified_by_id>
                                            <Item type='User' action='get'>
                                              <keyed_name condition='like'>@1</keyed_name>
                                            </Item>
                                          </modified_by_id>
                                          <modified_on condition='gt'>@2</modified_on>
                                        </Item>"
                                                   , itemType.KeyedName
                                                   , "*" + txtModifiedBy.Text + "*"
                                                   , DateTime.Today.AddDays(-1 * (double)nudDays.Value)).Items();
                    }

                    foreach (var qr in queryResults)
                    {
                        _results.Add(ItemReference.FromFullItem(qr, true));
                    }
                }
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
                this.Close();
            }
            catch (Exception ex)
            {
                Utils.HandleError(ex);
            }
        }
Esempio n. 4
0
        public void Install()
        {
            //_logger?.LogInformation();
            _currLine = 0;

            var exception = default(Exception);

            using (var activity = SharedUtils.StartActivity("InstallProcessor.Install"))
            {
                var upgradeId = Guid.NewGuid().ToArasId();
                try
                {
                    _conn.Apply(@"<Item type='DatabaseUpgrade' action='merge' id='@0'>
                          <upgrade_status>0</upgrade_status>
                          <is_latest>0</is_latest>
                          <type>1</type>
                          <os_user>@1</os_user>
                          <name>@2</name>
                          <description>@3</description>
                          <applied_on>__now()</applied_on>
                        </Item>"
                                , upgradeId
                                , Environment.UserDomainName + "\\" + Environment.UserName
                                , _script.Title.Left(64)
                                , _script.Description.Left(512)).AssertNoError();
                    InstallLines();
                    _conn.Apply("<Item type=\"DatabaseUpgrade\" action=\"merge\" id=\"@0\"><upgrade_status>1</upgrade_status></Item>", upgradeId).AssertNoError();
                }
                catch (Exception ex)
                {
                    if (!(ex is ServerException))
                    {
                        _logger?.LogError(ex, null);
                    }
                    _conn.Apply("<Item type=\"DatabaseUpgrade\" action=\"merge\" id=\"@0\"><upgrade_status>2</upgrade_status></Item>", upgradeId); //.AssertNoError();
                }
            }
            OnActionComplete(new ActionCompleteEventArgs()
            {
                Exception = exception
            });
        }
Esempio n. 5
0
        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 <IReadOnlyItem> 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.Apply("<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>").Items();
                    }
                    else
                    {
                        elements = _conn.Apply("<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>").Items();
                    }

                    packageGroups.UnionWith(elements.Select(e => e.SourceId().Value));
                    idx++;
                }

                var packages = _conn.Apply("<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>").Items();
                currPackageId = packages.Where(p => p.Property("name").Value == script.Title).SingleOrDefault().Id();

                cont = false;
                if (packages.Any(p => p.Property("name").Value != script.Title))
                {
                    if (errorHandler != null)
                    {
                        var packageList = (from p in packages
                                           where p.Property("name").Value != script.Title
                                           select p.Property("name").Value)
                                          .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.Apply("<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)
                                                           + "')\" />").Items();
                                }
                                else
                                {
                                    elements = _conn.Apply("<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)
                                                           + ")\" />").Items();
                                }

                                idx++;
                            }


                            break;

                        default:
                            return(false);
                        }
                    }
                    else
                    {
                        return(false);
                    }
                }
            }

            // Try one more time to get the package
            if (string.IsNullOrEmpty(currPackageId))
            {
                var packages = _conn.Apply("<Item type=\"PackageDefinition\" action=\"get\" select=\"name\"><name>" + script.Title + "</name></Item>");
                currPackageId = packages.AssertItem().Id();
            }

            // Add the package
            if (string.IsNullOrEmpty(currPackageId))
            {
                var packages = _conn.Apply("<Item type=\"PackageDefinition\" action=\"add\" ><name>" + script.Title + "</name></Item>", true);
                currPackageId = packages.AssertItem().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.Apply("<Item type=\"PackageGroup\" action=\"merge\" where=\"[PackageGroup].[source_id] = '"
                                      + currPackageId
                                      + "' and [PackageGroup].[name] = '"
                                      + typeGroup.Key
                                      + "'\"><name>"
                                      + typeGroup.Key
                                      + "</name></Item>", true).AssertItem().Id();

                foreach (var elem in typeGroup)
                {
                    _conn.Apply("<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>").AssertNoError();
                }

                idx++;
            }

            return(true);
        }
Esempio n. 6
0
        private void InstallLines()
        {
            string upgradeId = Guid.NewGuid().ToString("N").ToUpperInvariant();

            ExportProcessor.EnsureSystemData(_conn, ref _itemTypes);

            try
            {
                bool cont;
                RecoverableErrorEventArgs args;
                XmlNode    query;
                XmlElement newQuery;
                ItemType   itemType;
                string     configId;

                ReportProgress(0, "Starting install.");
                _conn.Apply(@"<Item type='DatabaseUpgrade' action='merge' id='@0'>
                        <upgrade_status>0</upgrade_status>
                        <is_latest>0</is_latest>
                        <type>1</type>
                        <os_user>@1</os_user>
                        <name>@2</name>
                        <description>@3</description>
                        <applied_on>__now()</applied_on>
                      </Item>"
                            , upgradeId
                            , Environment.UserDomainName + "\\" + Environment.UserName
                            , _script.Title.Left(64)
                            , _script.Description.Left(512)).AssertNoError();

                IEnumerable <IReadOnlyItem> items;
                foreach (var line in _lines.Skip(_currLine).ToList())
                {
                    cont = true;
                    ReportProgress((int)(_currLine * 80.0 / _lines.Count), string.Format("Performing {0} ({1} of {2})", line.ToString(), _currLine + 1, _lines.Count));
                    query = line.Script;

                    while (cont)
                    {
                        try
                        {
                            // If the original item uses a where clause or is versionable or the target item is versionable

                            if ((query.Attribute("action") == "merge" || query.Attribute("action") == "edit") && TryGetConfigId(query, out configId) &&
                                (query.Attribute("where") != null || (_itemTypes.TryGetValue(query.Attribute("type").ToLowerInvariant(), out itemType)) &&
                                 itemType.IsVersionable))
                            {
                                newQuery          = query.Clone() as XmlElement;
                                newQuery.InnerXml = "";
                                newQuery.SetAttribute("action", "get");
                                newQuery.SetAttribute("select", "id");

                                // The item type became versionable in the target database
                                if (newQuery.Attribute("where") == null)
                                {
                                    newQuery.RemoveAttribute("id");
                                    newQuery.SetAttribute("where", string.Format("[{0}].[config_id] = '{1}'", query.Attribute("type", "").Replace(' ', '_'), configId));
                                }

                                // If the item exists, get the id for use in the relationships
                                // If the item doesn't exist, make sure the id = config_id for the add
                                items = _conn.Apply(newQuery.OuterXml).Items();
                                string sourceId = items.Any() ? items.First().Attribute("id").Value : configId;
                                newQuery = query.Clone() as XmlElement;
                                newQuery.SetAttribute("id", sourceId);
                                newQuery.RemoveAttribute("where");
                                newQuery.RemoveAttribute(XmlFlags.Attr_ConfigId);
                                query = newQuery;

                                string relatedId;
                                string whereClause;
                                // Check relationships and match based on source_id and related_id where necessary
                                var rels = query.ElementsByXPath("Relationships/Item[related_id]").ToArray();
                                foreach (var rel in rels)
                                {
                                    if (rel.Element("related_id").Element("Item") == null)
                                    {
                                        relatedId = rel.InnerText;
                                    }
                                    else
                                    {
                                        relatedId = rel.Element("related_id").Element("Item").Attribute("id");
                                    }
                                    whereClause = string.Format("[{0}].[source_id]='{1}' and [{0}].[related_id]='{2}'"
                                                                , rel.Attribute("type", "").Replace(' ', '_'), sourceId, relatedId);

                                    if (!string.IsNullOrEmpty(relatedId))
                                    {
                                        newQuery = rel.OwnerDocument.CreateElement("Item");
                                        newQuery.SetAttribute("type", rel.Attribute("type"));
                                        newQuery.SetAttribute("where", whereClause);
                                        newQuery.SetAttribute("action", "get");

                                        items = _conn.Apply(newQuery.OuterXml).Items();
                                        rel.RemoveAttribute("id");
                                        if (items.Any())
                                        {
                                            rel.SetAttribute("where", whereClause);
                                            rel.SetAttribute("action", "edit");
                                        }
                                        else
                                        {
                                            rel.SetAttribute("action", "add");
                                        }
                                    }
                                }
                            }

                            //Fix Relationships on cmf generated ItemTypes
                            if ((query.Attribute("action") == "merge" || query.Attribute("action") == "edit") &&
                                query.Attribute("_cmf_generated") != null && query.Attribute("where") != null)
                            {
                                var sourceItem = _conn.Apply($"<Item action='get' type='ItemType'><name>{query.Element("name").InnerText}</name></Item>").AssertItem();
                                var sourceId   = sourceItem.Id();
                                var queryClone = query.Clone() as XmlElement;
                                queryClone.SetAttribute("id", sourceId);
                                queryClone.RemoveAttribute("where");
                                query = queryClone;

                                string relatedId = "";
                                string whereClause;
                                foreach (var rel in query.ElementsByXPath("Relationships/Item[related_id]").ToList())
                                {
                                    if (rel.Element("related_id").Element("Item") == null)
                                    {
                                        relatedId = rel.Element("related_id").InnerText;
                                    }
                                    else
                                    {
                                        var relatedQuery = rel.Element("related_id").Element("Item");
                                        relatedQuery.Attr("action", "get");
                                        relatedId = _conn.Apply(relatedQuery).AssertItem().Id();
                                        rel.Element("related_id").InnerText = relatedId;
                                    }
                                    whereClause = string.Format("[{0}].[source_id]='{1}' and [{0}].[related_id]='{2}'"
                                                                , rel.Attribute("type", "").Replace(' ', '_'), sourceId, relatedId);

                                    if (!string.IsNullOrEmpty(relatedId))
                                    {
                                        rel.RemoveAttribute("id");
                                        rel.SetAttribute("where", whereClause);
                                        rel.SetAttribute("action", "merge");
                                    }
                                }
                            }
                            var cmd = new Command(query.OuterXml);
                            cmd.Settings = x => x.Timeout = TimeSpan.FromMinutes(5);
                            items        = _conn.Apply(cmd).AssertItems();
                            if (line.Type == InstallType.Create)
                            {
                                line.InstalledId = items.First().Attribute("id").Value;
                            }

                            // Execute any sql scripts
                            var sqlScripts = line.Script
                                             .DescendantsAndSelf(e => e.Attribute(XmlFlags.Attr_SqlScript, "") != "")
                                             .Select(e => e.Attribute(XmlFlags.Attr_SqlScript, ""));
                            if (sqlScripts.Any())
                            {
                                _conn.ApplySql(sqlScripts.Aggregate((p, c) => p + Environment.NewLine + c)).AssertNoError();
                            }

                            cont = false;
                        }
                        catch (ServerException ex)
                        {
                            _log.Append(DateTime.Now.ToString("s")).AppendLine(": ERROR");
                            _log.AppendLine(ex.ToAml());
                            _log.AppendLine(" for query ");
                            _log.AppendLine(ex.Query);

                            if (ex.Message.Trim() == "No items of type ? found." &&
                                (query.Attribute("action") == "delete" || query.Attribute("action") == "purge"))
                            {
                                // Ignore errors with trying to delete something that isn't there.
                                _log.Append(DateTime.Now.ToString("s")).AppendLine(": Skipping install step");
                                cont = false;
                                break;
                            }
                            else
                            {
                                args = new RecoverableErrorEventArgs()
                                {
                                    Exception = ex
                                };
                                if (line.Type == InstallType.DependencyCheck && ex.FaultCode == "0")
                                {
                                    args.Message = "Unable to find required dependency " + line.Reference.Type + ": " + line.Reference.KeyedName;
                                }
                                OnErrorRaised(args);
                                switch (args.RecoveryOption)
                                {
                                case RecoveryOption.Abort:
                                    _log.Append(DateTime.Now.ToString("s")).AppendLine(": Install aborted.");
                                    throw;

                                case RecoveryOption.Retry:
                                    query = args.NewQuery ?? query;
                                    _log.Append(DateTime.Now.ToString("s")).AppendLine(": Retrying install step with query:");
                                    _log.AppendLine(query.OuterXml);
                                    break;

                                case RecoveryOption.Skip:
                                    _log.Append(DateTime.Now.ToString("s")).AppendLine(": Skipping install step.");
                                    cont = false;
                                    break;
                                }
                            }
                        }
                    }

                    _currLine++;
                }

                if (_script.AddPackage)
                {
                    var pkg = new DatabasePackage(_conn);
                    pkg.Write(_script, e =>
                    {
                        args = new RecoverableErrorEventArgs()
                        {
                            Message = e
                        };
                        OnErrorRaised(args);
                        switch (args.RecoveryOption)
                        {
                        case RecoveryOption.Skip:
                            return(DatabasePackageAction.RemoveElementsFromPackages);

                        case RecoveryOption.Retry:
                            return(DatabasePackageAction.TryAgain);

                        default:
                            return(DatabasePackageAction.Abort);
                        }
                    }, (i, m) =>
                    {
                        ReportProgress((int)(i * 0.2 + 80), m);
                    });
                }

                _conn.Apply("<Item type=\"DatabaseUpgrade\" action=\"merge\" id=\"@0\"><upgrade_status>1</upgrade_status></Item>", upgradeId).AssertNoError();
                OnActionComplete(new ActionCompleteEventArgs());
            }
            catch (Exception ex)
            {
                _conn.Apply("<Item type=\"DatabaseUpgrade\" action=\"merge\" id=\"@0\"><upgrade_status>2</upgrade_status></Item>", upgradeId); //.AssertNoError();
                OnActionComplete(new ActionCompleteEventArgs()
                {
                    Exception = ex
                });
            }
        }
    internal static void EnsureSystemData(IAsyncConnection _conn, ref Dictionary<string, ItemType> _itemTypes)
    {
      if (_itemTypes == null)
      {
        _itemTypes = new Dictionary<string, ItemType>();
        var itemTypes = _conn.Apply(@"<Item type='ItemType' action='get' select='is_versionable,is_dependent,implementation_type,core,name'></Item>").Items();
        ItemType result;
        foreach (var itemTypeData in itemTypes)
        {
          result = new ItemType();
          result.Id = itemTypeData.Id();
          result.IsCore = itemTypeData.Property("core").AsBoolean(false);
          result.IsDependent = itemTypeData.Property("is_dependent").AsBoolean(false);
          result.IsFederated = itemTypeData.Property("implementation_type").Value == "federated";
          result.IsPolymorphic = itemTypeData.Property("implementation_type").Value == "polymorphic";
          result.IsVersionable = itemTypeData.Property("is_versionable").AsBoolean(false);
          result.Name = itemTypeData.Property("name").Value;
          result.Reference = ItemReference.FromFullItem(itemTypeData, true);
          _itemTypes[result.Name.ToLowerInvariant()] = result;
        }

        var relationships = _conn.Apply(@"<Item action='get' type='RelationshipType' related_expand='0' select='related_id,source_id,relationship_id,name' />").Items();
        ItemType relType;
        foreach (var rel in relationships)
        {
          if (rel.SourceId().Attribute("name").HasValue()
            && _itemTypes.TryGetValue(rel.SourceId().Attribute("name").Value.ToLowerInvariant(), out result)
            && rel.Property("relationship_id").Attribute("name").HasValue()
            && _itemTypes.TryGetValue(rel.Property("relationship_id").Attribute("name").Value.ToLowerInvariant(), out relType))
          {
            result.Relationships.Add(relType);
          }
        }

        var floatProps = _conn.Apply(@"<Item type='Property' action='get' select='source_id,item_behavior,name' related_expand='0'>
                                        <data_type>item</data_type>
                                        <data_source>
                                          <Item type='ItemType' action='get'>
                                            <is_versionable>1</is_versionable>
                                          </Item>
                                        </data_source>
                                        <item_behavior>float</item_behavior>
                                        <name condition='not in'>'config_id','id'</name>
                                      </Item>").Items();
        foreach (var floatProp in floatProps)
        {
          if (_itemTypes.TryGetValue(floatProp.SourceId().Attribute("name").Value.ToLowerInvariant(), out result))
          {
            result.FloatProperties.Add(floatProp.Property("name").AsString(""));
          }
        }
      }
    }