private bool IsCoreType(ItemReference itemRef)
 {
   switch (itemRef.KeyedName)
   {
     case "ItemType":
     case "RelationshipType":
     case "Action":
     case "Report":
     case "Identity":
     case "List":
     case "Team":
     case "Method":
     case "Permission":
     case "Sequence":
     case "UserMessage":
     case "Workflow Promotion":
     case "Grid":
     case "User":
     case "Preference":
     case "Form":
     case "Life Cycle Map":
     case "Workflow Map":
       return true;
     default:
       return false;
   }
 }
        /// <summary>
        /// Loads a preset from serialized items on disk.
        /// </summary>
        public void LoadTree(AdvancedLoadOptions options)
        {
            Assert.ArgumentNotNull(options, "options");

            _itemsProcessed = 0;

            var reference = new ItemReference(options.Preset.Database, options.Preset.Path);
            var physicalPath = PathUtils.GetDirectoryPath(reference.ToString());

            options.Progress.ReportStatus("Loading serialized items from " + physicalPath, MessageType.Info);

            if (!Directory.Exists(physicalPath)) throw new FileNotFoundException("The root serialization path " + physicalPath + " did not exist!", physicalPath);

            if (options.DisableEvents)
            {
                using (new EventDisabler())
                {
                    LoadTreePaths(physicalPath, options);
                }

                string targetDatabase = GetTargetDatabase(physicalPath, options);
                DeserializationFinished(targetDatabase);

                return;
            }

            LoadTreePaths(physicalPath, options);
        }
        public DependencyAnalyzer(Connection _conn, Dictionary<string, ItemType> itemTypes)
        {
            _parser.SchemaToKeep = "innovator";

              _coreMethods = new HashSet<ItemReference>();
              ItemReference itemRef;
              var methodItems = _conn.GetItems("ApplyItem", Properties.Resources.GetCoreMethods);
              foreach (var methodItem in methodItems)
              {
            itemRef = new ItemReference("Method", "[Method].[config_id] = '" + methodItem.Element("config_id", "") + "'");
            itemRef.KeyedName = methodItem.Element("id").Attribute("keyed_name", "");
            _coreMethods.Add(itemRef);
              }

              _systemIdentities = new Dictionary<string, ItemReference>();
              var sysIdents = _conn.GetItems("ApplyItem", Properties.Resources.SystemIdentities);
              foreach (var sysIdent in sysIdents)
              {
            itemRef = ItemReference.FromFullItem(sysIdent, false);
            itemRef.KeyedName = sysIdent.Element("name", "");
            _systemIdentities.Add(itemRef.Unique, itemRef);
              }

              _sql = new Dictionary<string, ItemReference>();
              var sqlItems = _conn.GetItems("ApplyItem", Properties.Resources.SqlItems);
              foreach (var sql in sqlItems)
              {
            itemRef = ItemReference.FromFullItem(sql, false);
            itemRef.KeyedName = sql.Element("name", "");
            _sql.Add(itemRef.KeyedName.ToLowerInvariant(), itemRef);
              }

              _customProps = new Dictionary<ItemProperty, ItemReference>();
              var customPropItems = _conn.GetItems("ApplyItem", Properties.Resources.CustomUserProperties);
              XmlElement itemType;
              foreach (var customProp in customPropItems)
              {
            itemType = customProp.Elements("source_id").Element("Item");
            _customProps.Add(new ItemProperty()
            {
              ItemType = itemType.Element("name").InnerText,
              ItemTypeId = itemType.Element("id").InnerText,
              Property = customProp.Element("name").InnerText,
              PropertyId = customProp.Element("id").InnerText
            }, new ItemReference("Property", customProp.Element("id").InnerText)
            {
              KeyedName = customProp.Element("name").InnerText
            });
              }

              _itemTypes = itemTypes;
        }
    /// <summary>
    /// Removes a dependency from the data
    /// </summary>
    /// <param name="masterRef">Parent of the dependency</param>
    /// <param name="dependency">Child of the dependency</param>
    public void RemoveDependency(ItemReference masterRef, ItemReference dependency)
    {
      HashSet<ItemReference> childDependencies;
      if (_allItemDependencies.TryGetValue(masterRef, out childDependencies))
      {
        childDependencies.Remove(dependency);

      }
      References refs;
      if (_allDependencies.TryGetValue(dependency, out refs))
      {
        refs.RemoveByMaster(masterRef);
      }
    }
    /// <summary>
    /// Incrementally update reference list.
    /// </summary>
    /// <param name="element"/><param name="oldReferences">Old references. Can be invalid.</param>
    public IReference[] GetReferences(ITreeNode element, IReference[] oldReferences)
    {
      var node = element as XmlTagHeaderNode;
      if (node == null)
      {
        return EmptyArray<IReference>.Instance;
      }

      var itemReference = new ItemReference(node);

      return new IReference[]
      {
        itemReference
      };
    }
Example #6
0
 public int Deserialize(LoadOptions options)
 {
     processed = 0;
     var reference = new ItemReference(entry.Database, entry.Path);
     if (entry is SingleEntry)
     {
         Manager.LoadItem(PathUtils.GetFilePath(reference.ToString()), options);
         processed++;
     }
     else
     {
         var messagesInit = MessageCount;
         Manager.LoadItem(PathUtils.GetFilePath(reference.ToString()), options);
         Manager.LoadTree(PathUtils.GetDirectoryPath(reference.ToString()), options);
         processed += (MessageCount - messagesInit);
     }
     return processed;
 }
Example #7
0
        private void SerializeToTarget(Item item, string target, bool recursive)
        {
            if (!string.IsNullOrEmpty(target) && ItemPathsAbsolute.IsPresent)
            {
                target = target.EndsWith("\\")
                    ? target + item.Parent.Paths.FullPath.Replace("/", "\\")
                    : target + "\\" + item.Parent.Paths.FullPath.Replace("/", "\\");
            }

            var message = string.Format("Serializing item '{0}' to target '{1}'", item.Name, target);

            WriteVerbose(message);
            WriteDebug(message);

            var fileName = target;

            if (string.IsNullOrEmpty(fileName))
            {
                var itemReference = new ItemReference(item);
                fileName = PathUtils.GetFilePath(itemReference.ToString());
            }
            if (!ShouldProcess(item.GetProviderPath(), string.Format("Serializing item to '{0}'", fileName)))
            {
                return;
            }

            if (string.IsNullOrEmpty(target))
            {
                Manager.DumpItem(item);
            }
            else
            {
                target = target.EndsWith("\\") ? target + item.Name : target + "\\" + item.Name;
                Manager.DumpItem(target + ".item", item);
            }
            if (recursive)
            {
                foreach (Item child in item.GetChildren(ChildListOptions.IgnoreSecurity))
                {
                    SerializeToTarget(child, target, true);
                }
            }
        }
        public int Deserialize(LoadOptions options)
        {
            processed = 0;
            var reference = new ItemReference(entry.Database, entry.Path);

            if (entry is SingleEntry)
            {
                Manager.LoadItem(PathUtils.GetFilePath(reference.ToString()), options);
                processed++;
            }
            else
            {
                var messagesInit = MessageCount;
                Manager.LoadItem(PathUtils.GetFilePath(reference.ToString()), options);
                Manager.LoadTree(PathUtils.GetDirectoryPath(reference.ToString()), options);
                processed += (MessageCount - messagesInit);
            }
            return(processed);
        }
Example #9
0
        /// <summary>
        /// The default serialization event handler actually deletes serialized subitems if the parent item is renamed. This patches that behavior to preserve subitem files. (bug 384931)
        /// </summary>
        public void OnItemRenamed(object sender, EventArgs e)
        {
            if (DisabledLocally)
            {
                return;
            }

            // param 0 = renamed item, param 1 = old item name
            var item    = Event.ExtractParameter <Item>(e, 0);
            var oldName = Event.ExtractParameter <string>(e, 1);

            if (item == null || oldName == null)
            {
                return;
            }

            // the name wasn't actually changed, you sneaky template builder you. Don't write.
            if (oldName.Equals(item.Name, StringComparison.Ordinal))
            {
                return;
            }

            if (!Presets.Includes(item))
            {
                return;
            }

            // we push this to get updated. Because saving now ignores "inconsquential" changes like a rename that do not change data fields,
            // this keeps renames occurring even if the field changes are inconsequential
            ShadowWriter.PutItem(Operation.Updated, item, item.Parent);

            var reference    = new ItemReference(item).ToString();
            var oldReference = reference.Substring(0, reference.LastIndexOf('/') + 1) + oldName;

            var oldSerializationPath = PathUtils.GetDirectoryPath(oldReference);
            var newSerializationPath = PathUtils.GetDirectoryPath(reference);

            if (Directory.Exists(oldSerializationPath) && !Directory.Exists(newSerializationPath))
            {
                Directory.Move(oldSerializationPath, newSerializationPath);
            }
        }
Example #10
0
    public bool RemoveItemOfType(string type)
    {
        ItemReference toRemove = null;

        foreach (ItemReference itemRef in GetItemReferences())
        {
            if (itemRef.SmallItem.type == type)
            {
                toRemove = itemRef;
                break;
            }
        }

        if (toRemove != null)
        {
            items.Remove(toRemove);
            return(true);
        }
        return(false);
    }
Example #11
0
 public static InstallItem FromDependency(ItemReference itemRef)
 {
     var result = new InstallItem();
       result._itemRef = itemRef;
       result._elem = new XmlDocument().CreateElement("Item");
       result._elem.SetAttribute("type", result._itemRef.Type);
       if (result._itemRef.Unique.IsGuid())
       {
     result._elem.SetAttribute("id", result._itemRef.Unique);
       }
       else
       {
     result._elem.SetAttribute("where", result._itemRef.Unique);
       }
       result._elem.SetAttribute("action", "get");
       result._elem.SetAttribute("_dependency_check", "1");
       result._elem.SetAttribute("_keyed_name", result._itemRef.KeyedName);
       result._type = InstallType.DependencyCheck;
       return result;
 }
Example #12
0
    protected void GV_List_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        ItemReference itemReference = new ItemReference();

        int    id        = (int)this.GV_List.DataKeys[e.RowIndex].Values[0];
        string itemCode  = ((Label)this.GV_List.Rows[e.RowIndex].FindControl("lblItemCode")).Text.Trim();
        string partyCode = ((Label)this.GV_List.Rows[e.RowIndex].FindControl("lblPartyCode")).Text.Trim();

        itemReference               = TheItemReferenceMgr.LoadItemReference(id);
        itemReference.Item          = TheItemMgr.LoadItem(itemCode);
        itemReference.Party         = ThePartyMgr.LoadParty(partyCode);
        itemReference.ReferenceCode = ((Label)this.GV_List.Rows[e.RowIndex].FindControl("lblItemReferenceCode")).Text.Trim();
        itemReference.Description   = ((TextBox)this.GV_List.Rows[e.RowIndex].FindControl("tbDescription")).Text.Trim();
        itemReference.Remark        = ((TextBox)this.GV_List.Rows[e.RowIndex].FindControl("tbRemark")).Text.Trim();
        itemReference.IsActive      = ((CheckBox)this.GV_List.Rows[e.RowIndex].FindControl("cbActive")).Checked;
        TheItemReferenceMgr.UpdateItemReference(itemReference);
        this.GV_List.EditIndex = -1;
        this.GV_List.Execute();
        ShowSuccessMessage("MasterData.ItemReference.UpdateItemReference.Successfully", itemReference.ReferenceCode);
    }
Example #13
0
        public ActionResult _ItemRefNew(ItemReference itemReference)
        {
            bool isError = false;

            if (ModelState.IsValid)
            {
                if (base.genericMgr.FindAll <long>(itemRefDuiplicateVerifyStatement, new object[] { itemReference.Id })[0] > 0)
                {
                    SaveErrorMessage(Resources.ErrorMessage.Errors_Existing_Code, itemReference.Id.ToString());
                    isError = true;
                }
                else
                {
                    if (itemReference.Party != null)
                    {
                        if (base.genericMgr.FindAll <long>(itemAndPartyDuiplicateVerifyStatement, new object[] { itemReference.Item, itemReference.Party })[0] > 0)
                        {
                            SaveErrorMessage(Resources.MD.ItemRef.ItemPartyErrors_Existing_Code);
                            isError = true;
                        }
                    }
                    else
                    {
                        if (base.genericMgr.FindAll <long>(itemAndPartyIsNullDuiplicateVerifyStatement, new object[] { itemReference.Item })[0] > 0)
                        {
                            SaveErrorMessage(Resources.MD.ItemRef.ItemPartyErrors_Existing_Code);
                            isError = true;
                        }
                    }
                }

                if (!isError)
                {
                    base.genericMgr.Create(itemReference);
                    SaveSuccessMessage(Resources.MD.ItemRef.ItemRef_Added);
                    return(RedirectToAction("ItemRefResult/" + itemReference.Item));
                }
            }

            return(PartialView(itemReference));
        }
Example #14
0
    public void AddItem(ItemReference item)
    {
        if (!item.IsSmallItem)
        {
            Debug.LogError("Trying to add large item to inventory.");
            return;
        }
        if (!item.IsAlive)
        {
            Debug.LogError("Trying to add dead item to inventory.");
            return;
        }
        if (IsFull)
        {
            Debug.LogError("Trying to add item to full inventory.");
            return;
        }

        // TODO: Item stacks.
        items.Add(item);
    }
Example #15
0
        protected override void Process(WriteItemHeaderPipeline pipeline)
        {
            var status = 0;

            try
            {
                var reference = new ItemReference(pipeline.Item);
                var path      = PathUtils.GetFilePath(reference.ToString());

                if (FileUtil.FileExists(path))
                {
                    status = GetStatus(pipeline.Item, path);
                }
            }
            catch
            {
                status = 3;
            }

            pipeline.Output.WriteAttributeString("serializationstatus", status.ToString(CultureInfo.InvariantCulture));
        }
Example #16
0
		public TestResult Execute(DiskItem contextItem, DiskItem[] allItems)
		{
			// translate the full physical path into an item path
			var mappedPath = PathUtils.MakeItemPath(contextItem.FullPath, _rootPath);

			// if more than one item is in the same path with the same name, it will map something like "name_FDA63242325453" (guid)
			// we want to strip the disambiguating GUID from the name, if it exists
			var split = mappedPath.Split('_');
			if (ShortID.IsShortID(split.Last()))
				mappedPath = string.Join("_", split.Take(split.Length - 1));

			if (_databaseName != null)
			{
				string dbPrefix = "/" + _databaseName;

				if (mappedPath.StartsWith(dbPrefix, StringComparison.OrdinalIgnoreCase))
					mappedPath = mappedPath.Substring(dbPrefix.Length);
			}

			// MakeItemPath seems to return paths in the format "//sitecore/foo" sometimes, let's normalize that
			mappedPath = "/" + mappedPath.TrimStart('/');

			// if we have a database name (e.g. we are pointing at a raw serialized root such as "serialization\master" instead of "serialization"), prepend to the mapped path
			if (_databaseName != null)
			{
				mappedPath = "/" + _databaseName + mappedPath;
			}

			// compute the item reference path for the context item SyncItem
			string syncItemReferencePath = new ItemReference(contextItem.Item.DatabaseName, contextItem.Item.ItemPath).ToString();

			// ensure the ref path is prepended with /
			syncItemReferencePath = "/" + syncItemReferencePath.TrimStart('/');

			bool passed = mappedPath.Equals(syncItemReferencePath, StringComparison.OrdinalIgnoreCase);

			if (passed) return new TestResult(this, true);

			return new TestResult(this, false, string.Format("Physical: {0} != Serialized: {1}", mappedPath, syncItemReferencePath));
		}
        public WishCreateCommand(
            string apiId,
            string category,
            string imageUrl,
            bool isOwned,
            ItemReference itemType,
            string notes,
            string title,
            Guid userId)
        {
            Guard.Against.NullOrWhiteSpace(title, nameof(title));
            Guard.Against.Default(userId, nameof(userId));

            ApiId    = apiId;
            Category = category;
            ImageUrl = imageUrl;
            IsOwned  = isOwned;
            ItemType = itemType;
            Notes    = notes;
            Title    = title;
            UserId   = userId;
        }
Example #18
0
        public async Task CopyDocumentAsync(string sourcePath, string directory, string fileName, bool isRetry = false)
        {
            try
            {
                var parent = await _client.Drives[_fileStorageConfig.DriveId].Root
                             .ItemWithPath(directory)
                             .Request()
                             .GetAsync();

                var parentReference = new ItemReference
                {
                    DriveId = _fileStorageConfig.DriveId,
                    Id      = parent.Id
                };

                await _client.Drives[_fileStorageConfig.DriveId].Root
                .ItemWithPath(sourcePath)
                .Copy(fileName, parentReference)
                .Request()
                .PostAsync();
            }
            catch (NullReferenceException)
            {
                _logger.LogInformation($"File on path {sourcePath} not found. nothing to copy.");
            }
            catch (ServiceException ex)
            {
                if (!isRetry && ex.StatusCode == HttpStatusCode.NotFound)
                {
                    var directories = directory.Split("/");
                    await CreateDirectoryPathAsync(directories);
                    await CopyDocumentAsync(sourcePath, directory, fileName, true); // folder has been created, try again...
                }
                else
                {
                    throw ex;
                }
            }
        }
Example #19
0
    protected void ODS_ItemReference_Inserting(object source, ObjectDataSourceMethodEventArgs e)
    {
        ItemReference itemReference = (ItemReference)e.InputParameters[0];
        string        partyCode     = ((Controls_TextBox)(this.FV_ItemReference.FindControl("tbPartyCode"))).Text;
        string        referenceCode = ((TextBox)(this.FV_ItemReference.FindControl("tbReferenceCode"))).Text;

        if (ItemCode == null || ItemCode.Trim() == string.Empty)
        {
            ShowWarningMessage("MasterData.ItemReference.Required.ItemCode");
            e.Cancel = true;
            return;
        }

        if (itemReference.ReferenceCode == null || itemReference.ReferenceCode.Trim() == string.Empty)
        {
            ShowWarningMessage("MasterData.ItemReference.Required.ReferenceCode");
            e.Cancel = true;
            return;
        }
        itemReference.Item  = TheItemMgr.LoadItem(ItemCode);
        itemReference.Party = ThePartyMgr.LoadParty(partyCode);
        ShowSuccessMessage("MasterData.ItemReference.AddItemReference.Successfully", itemReference.ReferenceCode);
    }
Example #20
0
 /// <summary>
 /// Occurs when an vItem has been dropped by the AI.
 /// </summary>
 /// <param name="item">Item that has been dropped.</param>
 /// <param name="amount">Amount that has been dropped.</param>
 public void DropItem(vItem item, int amount)
 {
     item.amount -= amount;
     if (item.dropObject != null)
     {
         var             dropObject = Instantiate(item.dropObject, transform.position, transform.rotation) as GameObject;
         vItemCollection collection = dropObject.GetComponent <vItemCollection>();
         if (collection != null)
         {
             collection.items.Clear();
             var itemReference = new ItemReference(item.id);
             itemReference.amount     = amount;
             itemReference.attributes = new List <vItemAttribute>(item.attributes);
             collection.items.Add(itemReference);
         }
     }
     onDropItem.Invoke(item, amount);
     if (item.amount <= 0 && items.Contains(item))
     {
         items.Remove(item);
         Destroy(item);
     }
 }
        public string Execute([NotNull] string id, [NotNull] string databaseName)
        {
            Assert.ArgumentNotNull(id, nameof(id));
            Assert.ArgumentNotNull(databaseName, nameof(databaseName));

            var database = Factory.GetDatabase(databaseName);

            if (database == null)
            {
                throw new Exception("Database not found");
            }

            var item = database.GetItem(id);

            if (item == null)
            {
                throw new Exception("Item not found");
            }

            var reference = new ItemReference(item);

            return(PathUtils.GetFilePath(reference.ToString()));
        }
Example #22
0
        public void Request_Throws_If_Title_Is_Missing(
            string apiId,
            string category,
            string imageUrl,
            ItemReference itemType,
            string notes,
            bool isOwned,
            Guid wishId)
        {
            Action createWithMissingTitle = ()
                                            => new WishUpdateRequest(
                apiId,
                category,
                imageUrl,
                isOwned,
                itemType,
                notes,
                string.Empty,
                _testUser,
                wishId);

            createWithMissingTitle.Should().Throw <ArgumentException>();
        }
Example #23
0
        public WishSubmissionRequest(
            string apiId,
            string category,
            string imageUrl,
            bool isOwned,
            ItemReference itemType,
            string notes,
            string title,
            ApplicationUser user)
        {
            Guard.Against.NullOrWhiteSpace(title, nameof(title));
            Guard.Against.Null(user, nameof(user));
            Guard.Against.Default(user.Id, nameof(user.Id));

            ApiId    = apiId;
            Category = category;
            ImageUrl = imageUrl;
            IsOwned  = isOwned;
            ItemType = itemType;
            Notes    = notes;
            Title    = title;
            User     = user;
        }
Example #24
0
        /// <summary>
        /// Serializes the version
        /// </summary>
        /// <param name="item">Version for serializing</param>
        /// <param name="first">First version number  </param>
        /// <param name="last">Last version number</param>
        private static void SerializeItemVersions(Item item, int first, int last)
        {
            Assert.ArgumentNotNull(item, "item");
            var reference = new ItemReference(item);

            Log.Info("Serializing {0}", new object[] { reference });
            var path = new StringBuilder("VersionManager/");

            path.Append(DateTime.Now.Year + "/");
            path.Append(DateTime.Now.Month + "/");
            path.Append(DateTime.Now.Day + "/");
            path.Append(item.Name + item.ID + "/");
            if (first != last)
            {
                path.Append("Versions_" + first + "-" + last);
            }
            else
            {
                path.Append("Versions_" + first);
            }

            Manager.DumpItem(PathUtils.GetFilePath(path.ToString()), item);
        }
Example #25
0
    /// <summary>
    /// Serialize to a JSON object
    /// </summary>
    public new void SerializeJson(Utf8JsonWriter writer, JsonSerializerOptions options, bool includeStartObject = true)
    {
      if (includeStartObject)
      {
        writer.WriteStartObject();
      }

      ((Fhir.R4.Models.BackboneElement)this).SerializeJson(writer, options, false);

      if (ItemCodeableConcept != null)
      {
        writer.WritePropertyName("itemCodeableConcept");
        ItemCodeableConcept.SerializeJson(writer, options);
      }

      if (ItemReference != null)
      {
        writer.WritePropertyName("itemReference");
        ItemReference.SerializeJson(writer, options);
      }

      if (IsActive != null)
      {
        writer.WriteBoolean("isActive", (bool)IsActive!);
      }

      if (Strength != null)
      {
        writer.WritePropertyName("strength");
        Strength.SerializeJson(writer, options);
      }

      if (includeStartObject)
      {
        writer.WriteEndObject();
      }
    }
Example #26
0
            public override IDeepCopyable CopyTo(IDeepCopyable other)
            {
                var dest = other as FindingComponent;

                if (dest == null)
                {
                    throw new ArgumentException("Can only copy to an object of the same type", "other");
                }

                base.CopyTo(dest);
                if (ItemCodeableConcept != null)
                {
                    dest.ItemCodeableConcept = (Hl7.Fhir.Model.CodeableConcept)ItemCodeableConcept.DeepCopy();
                }
                if (ItemReference != null)
                {
                    dest.ItemReference = (Hl7.Fhir.Model.ResourceReference)ItemReference.DeepCopy();
                }
                if (BasisElement != null)
                {
                    dest.BasisElement = (Hl7.Fhir.Model.FhirString)BasisElement.DeepCopy();
                }
                return(dest);
            }
        /// <summary>
        /// Exports the mipmaps in the image.
        /// </summary>
        public void RunExport()
        {
            ItemExportListStore.Foreach(delegate(ITreeModel model, TreePath path, TreeIter iter)
            {
                bool bShouldExport = (bool)ItemExportListStore.GetValue(iter, 0);

                if (bShouldExport)
                {
                    ItemReference referenceToExport = this.ReferenceMapping[(string)ItemExportListStore.GetValue(iter, 1)];

                    string ExportPath = "";
                    if (Config.GetShouldKeepFileDirectoryStructure())
                    {
                        string parentDirectoryOfFile =
                            ExtensionMethods.ConvertPathSeparatorsToCurrentNativeSeparator(ExportTarget.ItemPath);

                        ExportPath =
                            $"{ExportDirectoryFileChooserButton.Filename}{System.IO.Path.DirectorySeparatorChar}{parentDirectoryOfFile}{System.IO.Path.DirectorySeparatorChar}{referenceToExport.GetReferencedItemName()}";
                    }
                    else
                    {
                        ExportPath = $"{ExportDirectoryFileChooserButton.Filename}{System.IO.Path.DirectorySeparatorChar}{referenceToExport.GetReferencedItemName()}";
                    }

                    System.IO.Directory.CreateDirectory(System.IO.Directory.GetParent(ExportPath).FullName);

                    byte[] fileData = referenceToExport.Extract();
                    if (fileData != null)
                    {
                        File.WriteAllBytes(ExportPath, fileData);
                    }
                }

                return(false);
            });
        }
        private void btnOk_Click(object sender, EventArgs e)
        {
            try
            {
                _results.Clear();
                IEnumerable <XmlElement> queryResults;
                foreach (var itemType in _selectedTypes)
                {
                    if (txtModifiedBy.Text == _currUserKeyedName)
                    {
                        queryResults = _conn.GetItems("ApplyItem", string.Format(Properties.Resources.RecentItems_UserId,
                                                                                 itemType.KeyedName,
                                                                                 _conn.GetCurrUserInfo().Attribute("id"),
                                                                                 DateTime.Today.AddDays(-1 * (double)nudDays.Value).ToString("s")));
                    }
                    else
                    {
                        queryResults = _conn.GetItems("ApplyItem", string.Format(Properties.Resources.RecentItems_UserKeyedName,
                                                                                 itemType.KeyedName,
                                                                                 txtModifiedBy.Text,
                                                                                 DateTime.Today.AddDays(-1 * (double)nudDays.Value).ToString("s")));
                    }

                    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);
            }
        }
        public void Command_Throws_If_WishId_Is_Default(
            string apiId,
            string category,
            string imageUrl,
            ItemReference itemType,
            string notes,
            bool isOwned,
            string title,
            Guid userId)
        {
            Action createWithDefaultWishId = ()
                                             => new WishUpdateCommand(
                apiId,
                category,
                imageUrl,
                isOwned,
                itemType,
                notes,
                title,
                userId,
                Guid.Empty);

            createWithDefaultWishId.Should().Throw <ArgumentException>();
        }
Example #30
0
    private void ItemReferenceData(ItemReference itemRef)
    {
        GUILayout.BeginVertical("Item Reference", "Window", GUILayout.MinHeight(75f));

        itemRef.instanceCount = EditorGUILayout.IntField("Instance count", itemRef.instanceCount);
        itemRef.procedural    = EditorGUILayout.Toggle("Procedural", itemRef.procedural);

        itemRef.probability   = EditorGUILayout.Slider("Probability", itemRef.probability, 0f, 1f);
        itemRef.maxChildDepth = EditorGUILayout.IntSlider("Max depth", itemRef.maxChildDepth, 0, ItemFactory.ITEM_TREE_MAX_DEPTH);
        itemRef.viewTree      = EditorGUILayout.Toggle("View Tree", itemRef.viewTree);

        itemRef.visualizeRandomness      = EditorGUILayout.Toggle("Visualize", itemRef.visualizeRandomness);
        itemRef.randomSnappedOrientation = EditorGUILayout.Toggle("Random Snapped Orientation", itemRef.randomSnappedOrientation);
        itemRef.randomPositionAmplitude  = EditorGUILayout.Vector3Field("Random Position Amplitude", itemRef.randomPositionAmplitude);
        itemRef.randomRotationAmplitude  = EditorGUILayout.Vector3Field("Random Rotation Amplitude", itemRef.randomRotationAmplitude);
        itemRef.randomScaleAmplitude     = EditorGUILayout.Vector3Field("Random Scale Amplitude", itemRef.randomScaleAmplitude);
        itemRef.uniformScale             = EditorGUILayout.Toggle("Uniform Scale", itemRef.uniformScale);

        ShowRotatePanel(itemRef);

        if (itemRef.procedural)
        {
            itemRef.anchorPlane = (ItemAnchorPlane)EditorGUILayout.EnumPopup("Anchor", itemRef.anchorPlane);
            itemRef.availableProceduralVolume = EditorGUILayout.BoundsField("Volume", itemRef.availableProceduralVolume);
        }

        if (itemRef.transform.parent)
        {
            if (GUILayout.Button("Select parent"))
            {
                Selection.activeGameObject = itemRef.transform.parent.gameObject;
            }
        }

        GUILayout.EndVertical();
    }
 public virtual void DeleteItemReference(ItemReference entity)
 {
     entityDao.DeleteItemReference(entity);
 }
 public virtual void CreateItemReference(ItemReference entity)
 {
     entityDao.CreateItemReference(entity);
 }
 public virtual void UpdateItemReference(ItemReference entity)
 {
     entityDao.UpdateItemReference(entity);
 }
 private void AddDependency(ItemReference itemRef, XmlNode context, XmlNode reference, ItemReference masterRef)
 {
   _dependencies.Add(itemRef);
   if (context != null)
   {
     References refs;
     if (!_allDependencies.TryGetValue(itemRef, out refs))
     {
       refs = new References();
       _allDependencies.Add(itemRef, refs);
     }
     refs.AddReferences(reference, context, masterRef);
   }
 }
        private SyncItem ReadSerializedVersion(Item item)
        {
            Assert.IsNotNull(item, "Item cannot be null");

            var reference = new ItemReference(item);
            var path = PathUtils.GetFilePath(reference.ToString());

            if (!File.Exists(path)) return null;

            using (var file = new StreamReader(path))
            {
                 return SyncItem.ReadItem(new Tokenizer(file));
            }
        }
 public void AddReferences(XmlNode reference, XmlNode context, ItemReference masterRef)
 {
   _contexts.Add(new ReferenceContext()
   {
     Context = context,
     Reference = reference,
     MasterRef = masterRef
   });
 }
 private MigrationWorker(ItemReference[] elements, bool convertToBlob)
 {
     Assert.ArgumentNotNull(elements, "elements");
     this.dataToPrecess = elements;
     this.convertToBlob = convertToBlob;
 }
        // like CreateReference, except re-target the old WeakReference (if any)
        internal static object ReplaceReference(object oldReference, object item)
        {
            if (item != null && 
                !(item is BindingListCollectionView) &&
                !(item == BindingExpression.NullDataItem) && 
                !(item == DisconnectedItem)) 
            {
#if USE_ITEM_REFERENCE 
                // if this cast fails, it's because you have done a direct assignment of an
                // item to some field instead of assigning the result of CreateReference.
                oldReference = ((ItemReference)oldReference).Item;
#endif 
                WeakReference wr = oldReference as WeakReference;
                if (wr != null) 
                { 
                    wr.Target = item;
                    item = wr; 
                }
                else
                {
                    item = new WeakReference(item); 
                }
            } 
 
#if USE_ITEM_REFERENCE
            item = new ItemReference(item); 
#endif

            return item;
        } 
        // like CreateReference, but use an existing WeakReference 
        internal static object CreateReference(WeakReference item)
        {
            object result = item;
#if USE_ITEM_REFERENCE 
            result = new ItemReference(item);
#endif 
            return result; 
        }
 public IEnumerable<XmlNode> GetReferencesByMaster(ItemReference masterRef)
 {
   return (from c in _contexts where c.MasterRef.Equals(masterRef) select c.Reference);
 }
Example #41
0
 public void Deserialize(Item item)
 {
     var reference = new ItemReference(item);
     if (Recurse.IsPresent)
     {
         var path = PathUtils.GetDirectoryPath(reference.ToString());
         Deserialize(path);
     }
     else
     {
         var path = PathUtils.GetFilePath(reference.ToString());
         Deserialize(path);
     }
 }
Example #42
0
 public static InstallItem FromWarning(ItemReference itemRef, string warning)
 {
     var result = new InstallItem();
       result._itemRef = itemRef;
       result._name = warning;
       result._type = InstallType.Warning;
       return result;
 }
 public static Job CreateJob(ItemReference[] elements, bool convertToBlob)
 {
     MigrationWorker worker = new MigrationWorker(elements, convertToBlob);
     JobOptions options = new JobOptions("MediaMigration", "MediaMigration", "shell", worker, "ThreadEntry");
     return new Job(options);
 }
 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 LookupItemsIn(Guid itemId, string itemPath)
 {
     LookupItemIds = true;
     Destination   = new ItemReference(itemId, itemPath);
 }
 public void RemoveByMaster(ItemReference masterRef)
 {
   var i = 0;
   while (i < _contexts.Count)
   {
     if (_contexts[i].MasterRef == masterRef)
     {
       _contexts.RemoveAt(i);
     }
     else
     {
       i++;
     }
   }
 }
        // To prevent memory leaks, we store WeakReferences to certain objects 
        // in various places:  _dataItem, _sources, worker fields.  The logic 
        // for this is centralized in these two static methods.  (See bug 940041)
 
        internal static object CreateReference(object item)
        {
            // One source of leaks is the reference cycle formed when a BindingExpression's
            // source item contains a reference chain to the target element: 
            //      target -> BindingExpression -> source item -> target
            // 
            // Making the second link into a WeakReference incurs some cost, 
            // so it should be avoided if we know the third link never exists.
            // We definitely can't avoid this when the item is a DependencyObject, 
            // since it's reasonably common for the third link to occur (e.g.
            // a ContextMenu contains a link to its Popup, which has a property
            // bound back to the ContextMenu).
            // 
            // For safety, we choose to use WeakRef all the time, unless the item is null.
            // Exception (bug 1124954):  Keep a strong reference to 
            // BindingListCollectionView - this keeps the underlying DataView 
            // alive, when nobody else will.
            // Exception (bug 1970505):  Don't allocate a WeakRef for the common 
            // case of the NullDataItem

            if (item != null &&
                !(item is BindingListCollectionView) && 
                !(item == BindingExpression.NullDataItem) &&
                !(item == DisconnectedItem)) 
            { 
                item = new WeakReference(item);
            } 

#if USE_ITEM_REFERENCE
            item = new ItemReference(item);
#endif 

            return item; 
        } 
Example #48
0
        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 <Item> MoveAsync([NotNull] string driveId, [NotNull] string itemId, [NotNull] string newName, ItemReference newParent, CancellationToken cancellationToken)
        {
            var newItemValues = new Item
            {
                Name            = newName,
                ParentReference = newParent,
            };

            return(UpdateAsync(driveId, itemId, newItemValues, cancellationToken));
        }
Example #50
0
    protected void GV_List_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        ItemReference itemReference = new ItemReference();

        int id = (int)this.GV_List.DataKeys[e.RowIndex].Values[0];
        string itemCode = ((Label)this.GV_List.Rows[e.RowIndex].FindControl("lblItemCode")).Text.Trim();
        string partyCode = ((Label)this.GV_List.Rows[e.RowIndex].FindControl("lblPartyCode")).Text.Trim();

        itemReference = TheItemReferenceMgr.LoadItemReference(id);
        itemReference.Item = TheItemMgr.LoadItem(itemCode);
        itemReference.Party = ThePartyMgr.LoadParty(partyCode);
        itemReference.ReferenceCode = ((Label)this.GV_List.Rows[e.RowIndex].FindControl("lblItemReferenceCode")).Text.Trim();
        itemReference.Description = ((TextBox)this.GV_List.Rows[e.RowIndex].FindControl("tbDescription")).Text.Trim();
        itemReference.Remark = ((TextBox)this.GV_List.Rows[e.RowIndex].FindControl("tbRemark")).Text.Trim();
        itemReference.IsActive = ((CheckBox)this.GV_List.Rows[e.RowIndex].FindControl("cbActive")).Checked;
        TheItemReferenceMgr.UpdateItemReference(itemReference);
        this.GV_List.EditIndex = -1;
        this.GV_List.Execute();
        ShowSuccessMessage("MasterData.ItemReference.UpdateItemReference.Successfully", itemReference.ReferenceCode);
    }
        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);
                        }
                    });
                }
            }
        }
Example #52
0
    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);
      }

    }
        /// <summary>
        /// Checks if the specified file path exists in the archive.
        /// </summary>
        /// <returns>true</returns>
        /// <c>false</c>
        /// <param name="filePath">File path.</param>
        public bool ContainsFile(string filePath)
        {
            ItemReference itemReference = new ItemReference(null, null, "", filePath);

            return(this.ContainsFile(itemReference));
        }
 public ItemRefData(ItemReference itemRef)
 {
     _itemRef = itemRef;
 }
 /// <summary>
 /// Removes depencencies
 /// </summary>
 /// <returns>Nodes which are top-level nodes</returns>
 public IEnumerable<XmlNode> RemoveDependencyContexts(ItemReference dependency)
 {
   References refs;
   if (_allDependencies.TryGetValue(dependency, out refs))
   {
     foreach (var node in refs.GetContexts())
     {
       if (node.ParentNode == null || node.Attribute(XmlFlags.Attr_DependenciesAnalyzed) == "1")
       {
         yield return node;
       }
       else
       {
         node.Detatch();
       }
     }
   }
 }
        /// <summary>
        /// Extracts the file.
        /// </summary>
        /// <returns>The file.</returns>
        /// <param name="filePath">File path.</param>
        public byte[] ExtractFile(string filePath)
        {
            ItemReference itemReference = new ItemReference(null, null, "", filePath);

            return(this.ExtractReference(itemReference));
        }
        /// <summary>
        /// The default serialization event handler actually deletes serialized subitems if the parent item is renamed. This patches that behavior to preserve subitem files. (bug 384931)
        /// </summary>
        public void OnItemRenamed(object sender, EventArgs e)
        {
            if (DisabledLocally) return;

            // param 0 = renamed item, param 1 = old item name
            var item = Event.ExtractParameter<Item>(e, 0);
            var oldName = Event.ExtractParameter<string>(e, 1);

            if (item == null || oldName == null) return;

            // the name wasn't actually changed, you sneaky template builder you. Don't write.
            if (oldName.Equals(item.Name, StringComparison.Ordinal)) return;

            if (!Presets.Includes(item)) return;

            // we push this to get updated. Because saving now ignores "inconsquential" changes like a rename that do not change data fields,
            // this keeps renames occurring even if the field changes are inconsequential
            ShadowWriter.PutItem(Operation.Updated, item, item.Parent);

            var reference = new ItemReference(item).ToString();
            var oldReference = reference.Substring(0, reference.LastIndexOf('/') + 1) + oldName;

            var oldSerializationPath = PathUtils.GetDirectoryPath(oldReference);
            var newSerializationPath = PathUtils.GetDirectoryPath(reference);

            if(Directory.Exists(oldSerializationPath) && !Directory.Exists(newSerializationPath))
                Directory.Move(oldSerializationPath, newSerializationPath);
        }
        /// <summary>
        /// Gets the file info of the provided path.
        /// </summary>
        /// <returns>The file info, or null if the file doesn't exist in the archive.</returns>
        /// <param name="filePath">File path.</param>
        public MPQFileInfo GetFileInfo(string filePath)
        {
            ItemReference itemReference = new ItemReference(null, null, "", filePath);

            return(this.GetReferenceInfo(itemReference));
        }
        /// <summary>
        /// The default serialization event handler does not properly move serialized subitems when the parent is moved (bug 384931)
        /// </summary>
        public new void OnItemMoved(object sender, EventArgs e)
        {
            if (DisabledLocally) return;

            // [0] is the moved item, [1] is the ID of the previous parent item
            var item = Event.ExtractParameter<Item>(e, 0);
            var oldParentId = Event.ExtractParameter<ID>(e, 1);

            if (item == null || oldParentId == (ID)null) return;

            var oldParent = item.Database.GetItem(oldParentId);

            if (oldParent == null) return;

            if (!Presets.Includes(item)) return;

            // get references to new and old paths
            var reference = new ItemReference(item).ToString();
            var oldReference = new ItemReference(oldParent).ToString();

            // fix the reference to the old parent to be a reference to the old item path
            oldReference = oldReference + '/' + item.Name;

            var oldSerializationPath = PathUtils.GetDirectoryPath(oldReference);
            var newSerializationPath = PathUtils.GetDirectoryPath(reference);

            if (Directory.Exists(oldSerializationPath) && !Directory.Exists(newSerializationPath))
                Directory.Move(oldSerializationPath, newSerializationPath);

            base.OnItemMoved(sender, e);
        }