public static IEnumerable <object> GetAllItemsRecursive(this IItemContainer rootContainer)
        {
            yield return(rootContainer);

            var queue = new Queue <object>();

            queue.Enqueue(rootContainer);

            while (queue.Count > 0)
            {
                var obj = queue.Dequeue();

                var container = obj as IItemContainer;
                if (container == null)
                {
                    continue;
                }

                foreach (var item in container.GetDirectChildren())
                {
                    yield return(item);

                    queue.Enqueue(item);
                }
            }
        }
        /// <summary>
        /// Builds the URI for the given template based on the containing project VSIX manifest identifier.
        /// </summary>
        internal static Uri BuildUri(IItemContainer selectedItem)
        {
            var manifest = selectedItem.GetToolkitManifest();
            var owningProject = selectedItem.Traverse(x => x.Parent, item => item.Kind == ItemKind.Project);

            tracer.Info(Properties.Resources.TextTemplateUriEditor_TraceReadingManifest, manifest.GetLogicalPath());

            string vsixId;
            try
            {
                vsixId = Vsix.ReadManifestIdentifier(manifest.PhysicalPath);
            }
            catch (Exception e)
            {
                tracer.Error(e,
                    String.Format(CultureInfo.CurrentCulture, Properties.Resources.TextTemplateUriEditor_TraceReadingManifestFailed, manifest.GetLogicalPath()));
                throw;
            }

            var path = GetLogicalPath(selectedItem).Replace(owningProject.GetLogicalPath(), string.Empty);

            // Use alternative name if IncludeInVSIXAs defined
            var templateItem = (IItem)selectedItem;
            if (IsIncludeInVSIXAs(templateItem))
            {
                path = Path.Combine(Path.GetDirectoryName(path), templateItem.Data.IncludeInVSIXAs);
            }

            return new Uri(new Uri(TextTemplateUri.UriHostPrefix), new Uri(vsixId + path, UriKind.Relative));
        }
Exemple #3
0
 public VendorData(
     IItemContainer buyingItemContainer,
     IItemContainer sellingItemContainer)
 {
     itemContainers[0] = buyingItemContainer;
     itemContainers[1] = sellingItemContainer;
 }
Exemple #4
0
        private void RenameNamespacesRecursive(IItemContainer itemContainer, string currentName, string newName, IDictionary <string, string> currentNewNamespace)
        {
            if (itemContainer.Kind == ItemKind.Folder)
            {
                // Rename namespace on child files
                foreach (var item in itemContainer.Items)
                {
                    RenameNamespacesRecursive(item, currentName, newName, currentNewNamespace);
                }

                // Do folder renaming
                if (itemContainer.Name == currentName)
                {
                    itemContainer.Rename(newName);
                }
            }
            else
            {
                // File exists?
                if (!System.IO.File.Exists(itemContainer.PhysicalPath))
                {
                    return;
                }

                // Do rename
                var fileText = File.ReadAllText(itemContainer.PhysicalPath);
                foreach (var renameNamespace in currentNewNamespace)
                {
                    fileText = fileText.Replace(renameNamespace.Key, renameNamespace.Value);
                }
                File.WriteAllText(itemContainer.PhysicalPath, fileText);
            }
        }
 private void AddResults(IItemContainer itemContainer) {
     foreach (ItemAmount itemAmount in Results) {
         for (int i = 0; i < itemAmount.Amount; i++) {
             itemContainer.AddItem(itemAmount.Item.GetCopy());
         }
     }
 }
    public void Craft(IItemContainer itemContainer)
    {
        // if we have sufficient materials to craft the item
        if (CanCraft(itemContainer))
        {
            // loop through the materials list and remove the required materials
            foreach (ItemAmount itemAmount in materials)
            {
                for (int i = 0; i < itemAmount.amount; i++)
                {
                    sScrapItem oldItem = itemContainer.RemoveItem(itemAmount.item.ID);
                    Destroy(oldItem);
                }
            }

            // loop through the results list and add them back to the inventory
            foreach (ItemAmount itemAmount in results)
            {
                for (int i = 0; i < itemAmount.amount; i++)
                {
                    itemContainer.AddItem(Instantiate(itemAmount.item));
                }
            }
        }
    }
Exemple #7
0
        private void WriteBodyObjects(PlayerAppearance appearance, IItemContainer equipment)
        {
            /*
             * todo : some equipped items conflict with body parts
             * write body model if chest doesn't conceal the body
             * write head model if head item doesn't fully conceal the head.
             * write beard model if head item doesn't fully conceal the head.
             * abstract out all of that logic
             */

            const int equipSlotSize = 12;

            for (var i = 0; i < equipSlotSize; i++)
            {
                const short plrObjMagic = 0x100;
                const short itemMagic   = 0x200;

                if (!equipment.Provider[i].IsEmpty())
                {
                    SerializedAppearance.Write16((short)(equipment.Provider[i].Id.ItemId + itemMagic));
                }
                else
                {
                    switch (i)
                    {
                    case 4:
                        SerializedAppearance.Write16((short)(appearance.Chest + plrObjMagic));
                        break;

                    case 6:
                        SerializedAppearance.Write16((short)(appearance.Arms + plrObjMagic));
                        break;

                    case 7:
                        SerializedAppearance.Write16((short)(appearance.Legs + plrObjMagic));
                        break;

                    case 8:
                        SerializedAppearance.Write16((short)(appearance.Head + plrObjMagic));
                        break;

                    case 9:
                        SerializedAppearance.Write16((short)(appearance.Hands + plrObjMagic));
                        break;

                    case 10:
                        SerializedAppearance.Write16((short)(appearance.Feet + plrObjMagic));
                        break;

                    case 11:
                        SerializedAppearance.Write16((short)(appearance.Beard + plrObjMagic));
                        break;

                    default:
                        SerializedAppearance.Write(0);
                        break;
                    }
                }
            }
        }
Exemple #8
0
        public Prefab FromPpd(IItemContainer map, string unitName, string variant, string look,
                              PrefabDescriptor ppd, Vector3 pos, Quaternion rot)
        {
            this.map       = map;
            this.ppd       = ppd;
            this.prefabPos = pos;
            this.prefabRot = rot;

            prefab = new Prefab
            {
                Model   = unitName,
                Variant = variant,
                Look    = look
            };

            // create map nodes from ppd
            CreateMapNodes();

            if (ppd.SpawnPoints.Count > 0)
            {
                CreateSlaveItems();
            }

            map.AddItem(prefab);
            return(prefab);
        }
 /// <summary>
 /// Add document to system. If db is set to true, only create file.
 /// </summary>
 /// <param name="parent"></param>
 /// <param name="title"></param>
 /// <param name="db"></param>
 /// <returns></returns>
 public override Document AddDocument(IItemContainer parent, string title, string revision = "", int id = 0, bool db = false)
 {
     if (!db) title = GetAvailableName(title, id, parent.GetPath(), ".txt");
     string documentPath = Path.Combine(parent.GetPath(), Helper.GenerateName(id, title));
     documentPath += ".txt";
     try {
         FileStream fileStream = File.Create(documentPath);
         StreamWriter streamWriter = new StreamWriter(fileStream);
         string[] lines = revision.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
         foreach (string line in lines) {
             streamWriter.WriteLine(line);
         }
         streamWriter.Flush();
         streamWriter.Close();
         fileStream.Close();
     } catch (IOException e) {
         // Should not be accesible
         Console.WriteLine(e.Message);
     }
     if (db) return null;
     Document document = new Document();
     document.Title = title;
     document.Parent = parent;
     parent.Documents.Add(document);
     return document;
 }
Exemple #10
0
        public override Folder AddFolder(IItemContainer parent, string title, int id = 0, bool db = false)
        {
            if (title == null || parent == null)
            {
                throw new ArgumentNullException();
            }
            Folder f = new Folder()
            {
                Title  = title,
                Parent = parent
            };

            if (parent is Folder)
            {
                f.FolderId = parent.Id;
            }
            else
            {
                f.ProjectId = parent.Id;
            }
            using (var dbContext = new sliceofpieEntities2()) {
                dbContext.Folders.AddObject(f);
                dbContext.SaveChanges();
            }
            return(new Folder()
            {
                Title = title,
                Parent = parent,
                Id = f.Id,
                ProjectId = f.ProjectId,
                FolderId = f.FolderId
            });
        }
Exemple #11
0
 /// <summary>
 /// Finds items in the parent (recursively) that match the
 /// given condition and are of the given type <typeparamref name="T"/>
 /// </summary>
 /// <param name="parent">The parent to traverse.</param>
 /// <param name="condition">The condition to check against each traversed item.</param>
 /// <returns></returns>
 public static IEnumerable <T> Find <T>(this IItemContainer parent, Func <T, bool> condition)
     where T : IItemContainer
 {
     return(parent.Items.Traverse(i => i.Items)
            .OfType <T>()
            .Where(condition));
 }
Exemple #12
0
        public static CameraPoint Add(IItemContainer map, Vector3 position, List <Token> tags)
        {
            var point = Add <CameraPoint>(map, position);

            point.Tags = tags;
            return(point);
        }
Exemple #13
0
        /// <summary>
        /// Determines whether the item is to be filtered or not.
        /// </summary>
        /// <param name="item">The item to check.</param>
        /// <returns>Returns <c>true</c> when the item should be included; otherwise <c>false</c>.</returns>
        public bool ApplyFilter(IItemContainer item)
        {
            Guard.NotNull(() => item, item);

            // Permit anything that matches the filters
            if (this.MatchesFilter(item))
            {
                return(true);
            }
            else
            {
                // Only permit non-matches if their Kind allowed
                if (IsAllowedKind(item.Kind))
                {
                    // Only permit containing items that have children that match the filter
                    if (HasChildrenItems(item))
                    {
                        return(HasAnyMatchingChildren(item));
                    }
                    else
                    {
                        // Permit empty (notional) containers if flag allowed
                        if (IsNotionalContainerKind(item) && this.IncludeEmptyContainers)
                        {
                            return(true);
                        }
                    }
                }
            }

            return(false);
        }
Exemple #14
0
        /// <summary>
        /// Recursively get all folders and their documents. These are saved to the IItemContainer provided,
        /// hence no return value.
        /// </summary>
        /// <param name="parent">Item whose sub-folders to get</param>
        private void GetFolders(IItemContainer parent)
        {
            List <Folder> folderList = new List <Folder>();

            using (var dbContext = new sliceofpieEntities2()) {
                IQueryable <Folder> folders;
                if (parent is Folder)
                {
                    folders = from folder in dbContext.Folders
                              where folder.FolderId == parent.Id
                              select folder;
                }
                else
                {
                    folders = from folder in dbContext.Folders
                              where folder.ProjectId == parent.Id
                              select folder;
                }
                foreach (Folder folder in folders)
                {
                    folderList.Add(new Folder()
                    {
                        Id     = folder.Id,
                        Title  = folder.Title,
                        Parent = parent
                    });
                }
            }
            foreach (Folder folder in folderList)
            {
                parent.Folders.Add(folder);
                GetFolders(folder);
                GetDocuments(folder);
            }
        }
Exemple #15
0
        private static void ClearDatabaseDocuments(IItemContainer parent, Container container = Container.Folder)
        {
            List <Document> documentsContainer = new List <Document>();

            using (var dbContext = new sliceofpieEntities2()) {
                IEnumerable <Document> documents;
                if (container == Container.Project)
                {
                    documents = from document in dbContext.Documents
                                where document.ProjectId == parent.Id
                                select document;
                }
                else
                {
                    documents = from document in dbContext.Documents
                                where document.FolderId == parent.Id
                                select document;
                }
                foreach (Document document in documents)
                {
                    documentsContainer.Add(document);
                }
            }
            foreach (Document document in documentsContainer)
            {
                ClearDatabaseRevisions(document);
                using (var dbContext = new sliceofpieEntities2()) {
                    var documents = from dbDocument in dbContext.Documents
                                    where dbDocument.Id == document.Id
                                    select dbDocument;
                    dbContext.Documents.DeleteObject(documents.First());
                    dbContext.SaveChanges();
                }
            }
        }
Exemple #16
0
        /// <summary>
        /// Unfolds the template
        /// </summary>
        public IItemContainer Unfold(string name, IItemContainer parent)
        {
            if (!Path.HasExtension(name) && !String.IsNullOrEmpty(defaultExtension))
                name = Path.ChangeExtension(name, defaultExtension);

            ProjectItems itemsParent;

            if (parent.Kind == ItemKind.Project)
            {
                itemsParent = (((VsProject)parent).ExtenderObject as Project).ProjectItems;
                itemsParent.AddFromTemplate(templatePath, name);
            }
            else if (parent.Kind == ItemKind.Folder)
            {
                itemsParent = (((HierarchyItem)parent).ExtenderObject as ProjectItem).ProjectItems;
                itemsParent.AddFromTemplate(templatePath, name);
            }
            else if (parent.Kind == ItemKind.SolutionFolder)
            {
                var project = ((VsSolutionFolder)parent).ExtenderObject as Project;
                var solutionFolder = project.Object as SolutionFolder;
                project.ProjectItems.AddFromTemplate(templatePath, name);
            }
            else
            {
                throw new NotSupportedException();
            }

            return (from item in parent.Items
                    where item.Kind == ItemKind.Item && item.Name == name
                    select item)
                         .FirstOrDefault();
        }
Exemple #17
0
        /// <summary>
        /// Unfolds the template
        /// </summary>
        public IItemContainer Unfold(string name, IItemContainer parent)
        {
            if (!Path.HasExtension(name) && !String.IsNullOrEmpty(defaultExtension))
            {
                name = Path.ChangeExtension(name, defaultExtension);
            }

            ProjectItems itemsParent;

            if (parent.Kind == ItemKind.Project)
            {
                itemsParent = (((VsProject)parent).ExtenderObject as Project).ProjectItems;
                itemsParent.AddFromTemplate(templatePath, name);
            }
            else if (parent.Kind == ItemKind.Folder)
            {
                itemsParent = (((HierarchyItem)parent).ExtenderObject as ProjectItem).ProjectItems;
                itemsParent.AddFromTemplate(templatePath, name);
            }
            else if (parent.Kind == ItemKind.SolutionFolder)
            {
                var project        = ((VsSolutionFolder)parent).ExtenderObject as Project;
                var solutionFolder = project.Object as SolutionFolder;
                project.ProjectItems.AddFromTemplate(templatePath, name);
            }
            else
            {
                throw new NotSupportedException();
            }

            return((from item in parent.Items
                    where item.Kind == ItemKind.Item && item.Name == name
                    select item)
                   .FirstOrDefault());
        }
Exemple #18
0
        /// <summary>
        /// Add folder to system. If db is set to true, only create folder.
        /// </summary>
        /// <param name="parent"></param>
        /// <param name="title"></param>
        /// <param name="db"></param>
        /// <returns></returns>
        public override Folder AddFolder(IItemContainer parent, string title, int id = 0, bool db = false)
        {
            if (!db)
            {
                title = GetAvailableName(title, id, parent.GetPath());
            }
            string folderPath = Path.Combine(parent.GetPath(), Helper.GenerateName(id, title));

            try {
                Directory.CreateDirectory(folderPath);
            } catch (IOException e) {
                // Should not be accesible
                Console.WriteLine(e.Message);
            }
            if (db)
            {
                return(null);
            }
            Folder folder = new Folder();

            folder.Title  = title;
            folder.Parent = parent;
            parent.Folders.Add(folder);
            return(folder);
        }
Exemple #19
0
 private static void ClearDatabaseDocuments(IItemContainer parent, Container container = Container.Folder)
 {
     List<Document> documentsContainer = new List<Document>();
     using (var dbContext = new sliceofpieEntities2()) {
         IEnumerable<Document> documents;
         if (container == Container.Project) {
             documents = from document in dbContext.Documents
                         where document.ProjectId == parent.Id
                         select document;
         } else {
             documents = from document in dbContext.Documents
                         where document.FolderId == parent.Id
                         select document;
         }
         foreach (Document document in documents) {
             documentsContainer.Add(document);
         }
     }
     foreach (Document document in documentsContainer) {
         ClearDatabaseRevisions(document);
         using (var dbContext = new sliceofpieEntities2()) {
             var documents = from dbDocument in dbContext.Documents
                             where dbDocument.Id == document.Id
                             select dbDocument;
             dbContext.Documents.DeleteObject(documents.First());
             dbContext.SaveChanges();
         }
     }
 }
        /// <summary>
        /// Swaps items between two containers and preserves the item indicies.
        /// </summary>
        /// <returns>True on success, false otherwise</returns>
        public static bool InterManagerSwapPreserveIndex(
            IItemContainer containerA, int idxA,
            IItemContainer containerB, int idxB)
        {
            // validate indicies
            if (IsNotInRange(idxA, containerA.Provider.Count))
            {
                return(false);
            }
            if (IsNotInRange(idxB, containerB.Provider.Count))
            {
                return(false);
            }

            // get items
            var itemA = containerA.Provider[idxA];
            var itemB = containerB.Provider[idxB];

            // check ids
            if (itemA.Id == itemB.Id)
            {
                // calc stacking A into B
                long uncheckedOverflow = itemB.Amount + itemA.Amount;
                var  overflow          = itemB.Id.GetOverflow(uncheckedOverflow);

                if (!SafeDoubleInfoExecute(
                        // stack A into B
                        containerB,
                        new ItemChangeInfo(idxB, new ItemStack(itemB.Id, Convert.ToInt32(uncheckedOverflow - overflow)), 0),
                        // leave overflow for A
                        containerA,
                        new ItemChangeInfo(idxA, new ItemStack(itemA.Id, Convert.ToInt32(overflow)), 0)))
                {
                    return(false);
                }
            }
            else
            {
                // remove A and B
                if (!SafeDoubleInfoExecute(
                        containerA, ItemChangeInfo.Remove(idxA),
                        containerB, ItemChangeInfo.Remove(idxB)))
                {
                    return(false);
                }

                // exec swap
                if (!SafeDoubleInfoExecute(
                        containerA, new ItemChangeInfo(idxA, itemB, 0),
                        containerB, new ItemChangeInfo(idxB, itemA, 0)))

                {
                    // reverse removal
                    GuaranteedExecuteInfo(containerA, new ItemChangeInfo(idxA, itemA, 0));
                    GuaranteedExecuteInfo(containerB, new ItemChangeInfo(idxB, itemB, 0));
                }
            }

            return(true);
        }
Exemple #21
0
        public override IItemContainer Unfold(string name, IItemContainer parent)
        {
            var container = base.Unfold(name, parent);

            File.Delete(this.SourcePath);
            return(container);
        }
Exemple #22
0
        public override Document AddDocument(IItemContainer parent, string title, string revision = "", int id = 0, bool db = false)
        {
            if (parent == null || title == null)
            {
                throw new ArgumentNullException();
            }
            Document d = new Document()
            {
                Title           = title,
                Parent          = parent,
                CurrentRevision = revision,
                CurrentHash     = revision.GetHashCode()
            };

            if (parent is Project)
            {
                d.ProjectId = parent.Id;
            }
            else
            {
                d.FolderId = parent.Id;
            }

            using (var dbContext = new sliceofpieEntities2()) {
                dbContext.Documents.AddObject(d);
                dbContext.SaveChanges();
            }
            return(d);
        }
Exemple #23
0
        private void SetArtifactLink(UnfoldScope scope)
        {
            var container = scope.Automation.Owner;

            // Determine created item
            IItemContainer createdItem = null;

            createdItem = this.Solution.Find <IProject>(p => p.PhysicalPath == this.projectCreated).SingleOrDefault();
            if (createdItem == null)
            {
                createdItem = this.Solution.Find <IItem>(pi => pi.PhysicalPath == this.projectItemCreated).SingleOrDefault();
            }

            if (createdItem != null)
            {
                if (this.UriService.CanCreateUri <IItemContainer>(createdItem))
                {
                    // Set the artifact link
                    SolutionArtifactLinkReference
                    .SetReference(container, this.UriService.CreateUri <IItemContainer>(createdItem))
                    .Tag = BindingSerializer.Serialize(scope.ReferenceTag);
                }
                else
                {
                    tracer.Warn(Properties.Resources.InstantiationTemplateWizard_CantCreateUri, createdItem.GetLogicalPath());
                }
            }
        }
        /// <summary>
        /// Builds the URI for the given template based on the containing project VSIX manifest identifier.
        /// </summary>
        internal static Uri BuildUri(IItemContainer selectedItem)
        {
            var manifest      = selectedItem.GetToolkitManifest();
            var owningProject = selectedItem.Traverse(x => x.Parent, item => item.Kind == ItemKind.Project);

            tracer.Info(Properties.Resources.TextTemplateUriEditor_TraceReadingManifest, manifest.GetLogicalPath());

            string vsixId;

            try
            {
                vsixId = Vsix.ReadManifestIdentifier(manifest.PhysicalPath);
            }
            catch (Exception e)
            {
                tracer.Error(e,
                             String.Format(CultureInfo.CurrentCulture, Properties.Resources.TextTemplateUriEditor_TraceReadingManifestFailed, manifest.GetLogicalPath()));
                throw;
            }

            var path = GetLogicalPath(selectedItem).Replace(owningProject.GetLogicalPath(), string.Empty);

            // Use alternative name if IncludeInVSIXAs defined
            var templateItem = (IItem)selectedItem;

            if (IsIncludeInVSIXAs(templateItem))
            {
                path = Path.Combine(Path.GetDirectoryName(path), templateItem.Data.IncludeInVSIXAs);
            }

            return(new Uri(new Uri(TextTemplateUri.UriHostPrefix), new Uri(vsixId + path, UriKind.Relative)));
        }
Exemple #25
0
        /// <summary>
        /// Add document to system. If db is set to true, only create file.
        /// </summary>
        /// <param name="parent"></param>
        /// <param name="title"></param>
        /// <param name="db"></param>
        /// <returns></returns>
        public override Document AddDocument(IItemContainer parent, string title, string revision = "", int id = 0, bool db = false)
        {
            if (!db)
            {
                title = GetAvailableName(title, id, parent.GetPath(), ".txt");
            }
            string documentPath = Path.Combine(parent.GetPath(), Helper.GenerateName(id, title));

            documentPath += ".txt";
            try {
                FileStream   fileStream   = File.Create(documentPath);
                StreamWriter streamWriter = new StreamWriter(fileStream);
                string[]     lines        = revision.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
                foreach (string line in lines)
                {
                    streamWriter.WriteLine(line);
                }
                streamWriter.Flush();
                streamWriter.Close();
                fileStream.Close();
            } catch (IOException e) {
                // Should not be accesible
                Console.WriteLine(e.Message);
            }
            if (db)
            {
                return(null);
            }
            Document document = new Document();

            document.Title  = title;
            document.Parent = parent;
            parent.Documents.Add(document);
            return(document);
        }
Exemple #26
0
        /// <summary>
        /// Download all folders for a specific parent folder. Do this recursively.
        /// </summary>
        /// <param name="parent"></param>
        public void DownloadFolders(IItemContainer parent, Container container = Container.Folder)
        {
            List <Folder> foldersContainer = new List <Folder>();

            using (var dbContext = new sliceofpieEntities2()) {
                IEnumerable <Folder> folders;
                if (container == Container.Project)
                {
                    folders = from folder in dbContext.Folders
                              where folder.ProjectId == parent.Id
                              select folder;
                }
                else
                {
                    folders = from folder in dbContext.Folders
                              where folder.FolderId == parent.Id
                              select folder;
                }
                foreach (Folder folder in folders)
                {
                    folder.Parent = parent;
                    AddFolder(parent, folder.Title, folder.Id, true);
                    foldersContainer.Add(folder);
                }
            }
            foreach (Folder folder in foldersContainer)
            {
                DownloadFolders(folder);
                DownloadDocuments(folder);
            }
        }
 void Start()
 {
     itemContainer  = invintory.GetComponent <IItemContainer>();
     move           = GetComponent <IMovementInput>();
     invintoryInput = GetComponent <IInvintoryInput>();
     rb             = GetComponent <Rigidbody2D>();
 }
Exemple #28
0
        /// <summary>
        /// Determines whether the item is to be filtered or not.
        /// </summary>
        /// <param name="item">The item to check.</param>
        /// <returns>Returns <c>true</c> when the item should be included; otherwise <c>false</c>.</returns>
        public bool ApplyFilter(IItemContainer item)
        {
            Guard.NotNull(() => item, item);

            // Permit anything that matches the filters
            if (this.MatchesFilter(item))
            {
                return true;
            }
            else
            {
                // Only permit non-matches if their Kind allowed
                if (IsAllowedKind(item.Kind))
                {
                    // Only permit containing items that have children that match the filter
                    if (HasChildrenItems(item))
                    {
                        return HasAnyMatchingChildren(item);
                    }
                    else
                    {
                        // Permit empty (notional) containers if flag allowed
                        if (IsNotionalContainerKind(item) && this.IncludeEmptyContainers)
                        {
                            return true;
                        }
                    }
                }
            }

            return false;
        }
        public static (int?existingIdx, int?emptyIdx) GetExistingOrEmptyIdx(
            this IItemContainer container, int id)
        {
            int?emptyIdx    = null;
            int?existingIdx = null;

            for (var i = 0; i < container.Provider.Count; i++)
            {
                // handle empty items, store the first index we find just in case.
                var item = container.Provider[i];
                if (item.IsEmpty())
                {
                    if (emptyIdx == null)
                    {
                        emptyIdx = i;
                    }
                    continue;
                }

                // compare id's
                if (item.Id.ItemId == id)
                {
                    if (!item.IsFull())
                    {
                        // we found an existing item, set the existing item index and gtfo out of the loop.
                        existingIdx = i;
                        break;
                    }
                }
            }

            return(existingIdx, emptyIdx);
        }
        private static string GetProjectItemUniqueName(string baseName, IVsTemplate template, IItemContainer parent)
        {
            Guard.NotNull(() => baseName, baseName);
            Guard.NotNull(() => template, template);
            Guard.NotNull(() => parent, parent);

            var directoryBase = System.IO.Path.GetDirectoryName(parent.PhysicalPath);
            var files = Directory.EnumerateFiles(directoryBase);

            var contentProjectItem = template.TemplateContent.Items.OfType<VSTemplateTemplateContentProjectItem>().FirstOrDefault();

            if (contentProjectItem == null)
            {
                return baseName;
            }

            var outputExtension = System.IO.Path.GetExtension(contentProjectItem.TargetFileName);

            var uniqueName = UniqueNameGenerator.EnsureUnique(
                baseName,
                newName => !files.Any(file => System.IO.Path.GetFileName(file).Equals(
                    string.Format(CultureInfo.InvariantCulture, @"{0}{1}", System.IO.Path.GetFileNameWithoutExtension(newName), outputExtension),
                    StringComparison.OrdinalIgnoreCase)));

            return string.Format(
                CultureInfo.InvariantCulture,
                @"{0}{1}",
                System.IO.Path.GetFileNameWithoutExtension(uniqueName),
                System.IO.Path.GetExtension(baseName));
        }
Exemple #31
0
 public void AddItemToInvitory(IItemContainer container)
 {
     //print("can add item " + container.AddItem(item));
     if (container.AddItem(item))
     {
         Destroy(gameObject);
     }
 }
Exemple #32
0
        /// <summary>
        /// Start asynchronously creating a folder in accordance with the Asynchronous Programming Model.
        /// </summary>
        /// <param name="name">Name of folder</param>
        /// <param name="userMail">Email of owner of folder</param>
        /// <param name="parent">Parent of folder; folders must be placed in folders or projects</param>
        /// <param name="callback">Callback called upon folder creation</param>
        /// <param name="stateObject">State object (passed to callback)</param>
        /// <returns>IAsyncResult for EndCreateFolder</returns>
        /// <seealso cref="EndCreateFolder"/>
        public IAsyncResult BeginCreateFolder(string name, string userMail, IItemContainer parent, AsyncCallback callback, object stateObject)
        {
            AsyncResult <Folder, string, string, IItemContainer> ar = new AsyncResult <Folder, string, string, IItemContainer>(callback, stateObject, name, userMail, parent);

            ThreadPool.QueueUserWorkItem(CreateFolderAsyncHelper, ar);

            return(ar);
        }
Exemple #33
0
 public AssignItemHandler(NetworkRelay networkRelay, CharacterInfo info, ItemFactory factory, IItemContainer inventory)
 {
     _networkRelay = networkRelay;
     _info         = info;
     _factory      = factory;
     _inventory    = inventory;
     PreInitialize();
 }
 public void Craft(IItemContainer itemContainer)
 {
     if (CanCraft(itemContainer))
     {
         RemoveMaterials(itemContainer);
         AddResults(itemContainer);
     }
 }
Exemple #35
0
        /// <summary>
        /// Adds a new element to the container by unfolding the given template and using the
        /// specified name for the new element.
        /// </summary>
        /// <param name="parent">Parent container into which the template will be unfolded.</param>
        /// <param name="name">Name to use when unfolding the template.</param>
        /// <param name="template">Template to unfold.</param>
        /// <returns>The created element.</returns>
        public static IItemContainer Add(this IItemContainer parent, string name, ITemplate template)
        {
            Guard.NotNull(() => parent, parent);
            Guard.NotNull(() => template, template);
            Guard.NotNull(() => name, name);

            return(template.Unfold(name, parent));
        }
Exemple #36
0
 //designated constructor
 public Room(string tag)
 {
     exits         = new Dictionary <string, Door>();
     this.tag      = tag;
     _delegate     = null;
     itemContainer = new ItemContainer();
     //uitemContainer = new UItemContainer();
 }
        public IItemContainer Unfold(string name, IItemContainer parent)
        {
            Guard.NotNullOrEmpty(() => name, name);

            var container = parent.As<dynamic>();
            var item = container.ProjectItems.AddFromDirectory(this.SourcePath);

            return parent.Items.FirstOrDefault(i => i.Name == item.Name);
        }
 public void InitializeContext()
 {
     this.item = Mock.Of<IItemContainer>(i =>
         i.Items == Enumerable.Empty<IItemContainer>()
         && i.Icon == System.Drawing.SystemIcons.Application);
     this.filter = Mock.Of<IPickerFilter>(pf =>
         pf.ApplyFilter(this.item) == false
         && pf.MatchesFilter(this.item) == true);
     this.container = new FilteredItemContainer(this.item, this.filter);
 }
 /// <summary>
 /// </summary>
 /// <param name="owner">
 /// </param>
 public PlayerInventory(IItemContainer owner)
     : base(owner)
 {
     this.StandardPage = (int)IdentityType.Inventory;
     this.Pages.Add((int)IdentityType.ArmorPage, new ArmorInventoryPage(owner.Identity));
     this.Pages.Add((int)IdentityType.SocialPage, new SocialArmorInventoryPage(owner.Identity));
     this.Pages.Add((int)IdentityType.ImplantPage, new ImplantInventoryPage(owner.Identity));
     this.Pages.Add((int)IdentityType.WeaponPage, new WeaponInventoryPage(owner.Identity));
     this.Pages.Add((int)IdentityType.Bank, new BankInventoryPage(owner.Identity));
 }
        /// <summary>
        /// Converts the value to the destination type.
        /// </summary>
        protected override object ConvertValue(ITypeDescriptorContext context, IServiceProvider provider, IItemContainer value)
        {
            if (value != null)
            {
                var uriService = provider.GetService<IUriReferenceService>();
                return uriService.CreateUri(value, SolutionUri.UriScheme);
            }

            return null;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="FilteredItemContainer"/> class.
        /// </summary>
        /// <param name="parent">The parent item.</param>
        /// <param name="item">The wrapped item.</param>
        /// <param name="filter">The filter to apply to the children of the item.</param>
        private FilteredItemContainer(FilteredItemContainer parent, IItemContainer item, IPickerFilter filter)
        {
            Guard.NotNull(() => item, item);
            Guard.NotNull(() => filter, filter);

            this.filter = filter;
            this.Item = item;
            this.Parent = parent;
            this.Items = item.Items.Where(filter.ApplyFilter).Select(i => new FilteredItemContainer(this, i, filter)).ToArray();
        }
Exemple #42
0
        public virtual IItemContainer Unfold(string name, IItemContainer parent)
        {
            Guard.NotNullOrEmpty(() => name, name);
            Guard.NotNull(() => parent, parent);

            if (!typeof(HierarchyItem).IsAssignableFrom(parent.GetType()))
                throw new NotSupportedException(Resources.VsFileTemplate_ErrorParentNotHierarchy);

            Guard.NotNullOrEmpty(() => parent.PhysicalPath, parent.PhysicalPath);

            var targetPath = Path.Combine(Path.GetDirectoryName(parent.PhysicalPath), name);
            if (File.Exists(targetPath))
            {
                VsHelper.CheckOut(targetPath);
            }

            if (!this.SourcePath.Equals(targetPath, StringComparison.OrdinalIgnoreCase))
            {
                File.Copy(this.SourcePath, targetPath, this.overwrite);
            }

            var container = parent.As<dynamic>();
            EnvDTE.ProjectItem newlyAddedFile = null;

            if (!parent.Items.Any(i => i.Name == name))
            {
                newlyAddedFile = container.ProjectItems.AddFromFile(targetPath) as EnvDTE.ProjectItem;
            }

            if (this.openFile)
            {
                container.DTE.ItemOperations.OpenFile(targetPath);
            }
            else if (newlyAddedFile != null)
            {
                //
                // The file may have opened anyway, if we're not supposed to open it, we'll search for
                // the matching window and close it
                //
                foreach (EnvDTE.Window w in container.DTE.Windows)
                {
                    if (newlyAddedFile.Equals(w.ProjectItem))
                    {
                        w.Close(EnvDTE.vsSaveChanges.vsSaveChangesNo);
                        break;
                    }
                }

            }

            return parent.Items.FirstOrDefault(item => item.Kind == ItemKind.Item && item.Name == name);
        }
 /// <summary>
 /// Sets the selected item
 /// </summary>
 /// <param name="selectedItem">Item to select</param>
 internal void SetSelectedItem(IItemContainer selectedItem)
 {
     if (selectedItem != null)
     {
         // Find the item in the hierarchy
         var filteredItem = this.Items.Traverse(item => item.Items)
             .FirstOrDefault(subItem => subItem.Item.Equals(selectedItem));
         if (filteredItem != null)
         {
             filteredItem.IsSelected = true;
             filteredItem.IsExpanded = true;
         }
     }
 }
        /// <summary>
        /// Converts the value to the destination type.
        /// </summary>
        protected virtual object ConvertValue(ITypeDescriptorContext context, IServiceProvider provider, IItemContainer value)
        {
            Guard.NotNull(() => context, context);

            var converter = context.PropertyDescriptor.Converter;
            if (converter != null &&
                value != null &&
                !context.PropertyDescriptor.PropertyType.IsAssignableFrom(value.GetType()) &&
                converter.CanConvertTo(context, context.PropertyDescriptor.PropertyType))
            {
                return converter.ConvertTo(context, CultureInfo.CurrentCulture, value, context.PropertyDescriptor.PropertyType);
            }

            return value;
        }
 /// <summary>
 /// Add folder to system. If db is set to true, only create folder.
 /// </summary>
 /// <param name="parent"></param>
 /// <param name="title"></param>
 /// <param name="db"></param>
 /// <returns></returns>
 public override Folder AddFolder(IItemContainer parent, string title, int id = 0, bool db = false)
 {
     if (!db) title = GetAvailableName(title, id, parent.GetPath());
     string folderPath = Path.Combine(parent.GetPath(), Helper.GenerateName(id, title));
     try {
         Directory.CreateDirectory(folderPath);
     } catch (IOException e) {
         // Should not be accesible
         Console.WriteLine(e.Message);
     }
     if (db) return null;
     Folder folder = new Folder();
     folder.Title = title;
     folder.Parent = parent;
     parent.Folders.Add(folder);
     return folder;
 }
Exemple #46
0
        /// <summary>
        /// Transforms the template and adds the content with the given name to the specified parent.
        /// </summary>
        public IItemContainer Unfold(string name, IItemContainer parent)
        {
            Guard.NotNull(() => parent, parent);
            Guard.NotNullOrEmpty(() => name, name);

            //var sessionHost = this.templating as ITextTemplatingSessionHost;

            using (tracer.StartActivity(Resources.TextTemplate_TraceStartUnfold, this.templateFile, parent.GetLogicalPath()))
            {
                this.templating.BeginErrorSession();
                try
                {
                    // TODO: add support for parameters.
                    //foreach (var parameter in Parameters)
                    //{
                    //    sessionHost.Session[parameter.Name] = parameter.GetTypedValue();
                    //}
                    var callback = new TemplateCallback(tracer, templateFile);
                    var content = this.templating.ProcessTemplate(templateFile, templateContent, callback);
                    var targetName = name;
                    if (!Path.HasExtension(targetName))
                    {
                        targetName = targetName + callback.FileExtension;
                    }

                    // BUGFIX: FBRT does not checkout the file, if SCC.
                    var targetItem = parent.Find<IItem>(targetName).FirstOrDefault();
                    if (targetItem != null)
                    {
                        targetItem.Checkout();
                    }

                    using (new TempFileCleaner())
                    {
                        // HACK: \o/ feature runtime VsFileContentTemplate creates a temp file and 
                        // doesn't delete it, so we go FSW to detect it.
                        return parent.AddContent(content, targetName, true, false, callback.OutputEncoding);
                    }
                }
                finally
                {
                    this.templating.EndErrorSession();
                }
            }
        }
Exemple #47
0
        public override Document AddDocument(IItemContainer parent, string title, string revision = "", int id = 0, bool db = false)
        {
            if (parent == null || title == null) throw new ArgumentNullException();
            Document d = new Document() {
                Title = title,
                Parent = parent,
                CurrentRevision = revision,
                CurrentHash = revision.GetHashCode()
            };
            if(parent is Project) d.ProjectId = parent.Id;
            else d.FolderId = parent.Id;

            using(var dbContext = new sliceofpieEntities2()) {
                dbContext.Documents.AddObject(d);
                dbContext.SaveChanges();
            }
            return d;
        }
        /// <summary>
        /// Unfolds the template
        /// </summary>
        public IItemContainer Unfold(string name, IItemContainer parent)
        {
            if (parent.Kind == ItemKind.Solution)
            {
                var solution = ((VsSolution)parent).ExtenderObject as EnvDTE.Solution;
                var destinationPath = Path.GetDirectoryName(parent.PhysicalPath);
                solution.AddFromTemplate(path, Path.Combine(destinationPath, name), name);
            }
            else if (parent.Kind == ItemKind.SolutionFolder)
            {
                var project = ((VsSolutionFolder)parent).ExtenderObject as Project;
                var solutionFolder = project.Object as SolutionFolder;
                solutionFolder.AddFromTemplate(path, Path.Combine(parent.PhysicalPath, name), name);
            }
            else
            {
                throw new NotSupportedException(Resources.VsProjectTemplate_UnsupportedTarget);
            }

            return parent.Items.FirstOrDefault(item => item.Kind == ItemKind.Project && item.Name == name);
        }
Exemple #49
0
 public override Folder AddFolder(IItemContainer parent, string title, int id = 0, bool db = false)
 {
     if (title == null || parent == null) throw new ArgumentNullException();
     Folder f = new Folder() {
         Title = title,
         Parent = parent
     };
     if (parent is Folder) f.FolderId = parent.Id;
     else f.ProjectId = parent.Id;
     using (var dbContext = new sliceofpieEntities2()) {
         dbContext.Folders.AddObject(f);
         dbContext.SaveChanges();
     }
     return new Folder() {
         Title = title,
         Parent = parent,
         Id = f.Id,
         ProjectId = f.ProjectId,
         FolderId = f.FolderId
     };
 }
        public string GetUniqueName(string baseName, IVsTemplate template, IItemContainer parent)
        {
            Guard.NotNull(() => baseName, baseName);
            Guard.NotNull(() => parent, parent);

            if (template.Type == VsTemplateType.ProjectGroup)
            {
                return baseName;
            }
            else if (template.Type == VsTemplateType.Project)
            {
                return GetProjectUniqueName(baseName);
            }
            else if (template.Type == VsTemplateType.Item)
            {
                return GetProjectItemUniqueName(baseName, template, parent);
            }

            throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture,
                Resources.UnfoldPathHelper_TemplateTypeIsNotSupported, template));
        }
Exemple #51
0
        /// <summary>
        /// Begin creation of a document using the Asynchronous Programming Model.
        /// </summary>
        /// <param name="name">Name of document</param>
        /// <param name="userMail">Email of owning user</param>
        /// <param name="parent">Folder or project to place the document in</param>
        /// <param name="callback">Callback called on completion of creation</param>
        /// <param name="stateObject">state object (passed to callback)</param>
        /// <returns>IAsyncResult to be used in EndCreateDocument</returns>
        /// <seealso cref="EndCreateDocument"/>
        public IAsyncResult BeginCreateDocument(string name, string userMail, IItemContainer parent, AsyncCallback callback, object stateObject)
        {
            AsyncResult<Document, string, string, IItemContainer> ar = new AsyncResult<Document, string, string, IItemContainer>(callback, stateObject, name, userMail, parent);
            ThreadPool.QueueUserWorkItem(CreateDocumentAsyncHelper, ar);

            return ar;
        }
Exemple #52
0
 /// <summary>
 /// Create a new folder
 /// </summary>
 /// <param name="name">Name of folder</param>
 /// <param name="userMail">Email of owning user</param>
 /// <param name="parent">Parent of folder, folders must be placed in folders or projects</param>
 /// <returns>The newly created folder</returns>
 public Folder CreateFolder(String name, string userMail, IItemContainer parent)
 {
     return fileModel.AddFolder(parent, name);
 }
Exemple #53
0
 /// <summary>
 /// Create a new document
 /// </summary>
 /// <param name="name">Name of document</param>
 /// <param name="userMail">Email of owning user</param>
 /// <param name="parent">Parent of document. Must be placed in a project or folder</param>
 /// <returns>Newly created document</returns>
 /// <seealso cref="BeginCreateDocument"/>
 public Document CreateDocument(string name, string userMail, IItemContainer parent)
 {
     return fileModel.AddDocument(parent, name);
 }
        private void EnsureTargetContainer()
        {
            var resolver = new PathResolver(this.currentElement, this.uriService, this.targetPath);
            resolver.Resolve();
            if (!string.IsNullOrEmpty(resolver.Path))
            {
                this.TargetContainer = this.solution.Find(resolver.Path).FirstOrDefault();
                if (this.TargetContainer == null)
                {
                    throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture,
                        Resources.WindowsFileImporter_ErrorTargetContainerNotExist, resolver.Path));
                }
            }
            else
            {
                throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture,
                    Resources.WindowsFileImporter_ErrorTargetPathResolvedFailed, this.targetPath));
            }

            tracer.Info(
                Resources.WindowsFileImporter_TraceTargetContainer, this.TargetContainer.GetLogicalPath());
        }
 /// <summary>
 /// </summary>
 /// <param name="owner">
 /// </param>
 public UnitInventory(IItemContainer owner)
     : base(0, owner)
 {
     this.StandardPage = 0x40;
     this.Pages.Add((int)IdentityType.Inventory, new PlayerInventoryPage(owner.Identity.Instance));
 }
        /// <summary>
        /// Find all folders in project folder and subfolders in file system and create them in internal system.
        /// </summary>
        /// <param name="parent"></param>
        public void FindFolders(IItemContainer parent)
        {
            string[] folders = Directory.GetDirectories(parent.GetPath());
            foreach (string folderName in folders) {
                string pathName = Path.GetFileName(folderName);
                string[] parts = pathName.Split('-');
                Folder folder = new Folder {
                    Id = int.Parse(parts[0]),
                    Title = pathName.Replace(parts[0] + "-", ""),
                    Parent = parent
                };
                parent.Folders.Add(folder);

                FindFolders(folder);
                FindDocuments(folder);
            }
        }
 /// <summary>
 /// Find all documents in project/folder in file system and create them in internal system.
 /// </summary>
 /// <param name="parent"></param>
 public void FindDocuments(IItemContainer parent)
 {
     string[] documentPaths = Directory.GetFiles(parent.GetPath());
     foreach (string documentName in documentPaths) {
         string pathName = Path.GetFileName(documentName);
         string[] parts = pathName.Split('-');
         int id = int.Parse(parts[0]);
         bool isRevision = false;
         int hash = "".GetHashCode();
         string revision = "";
         FileStream fileStream = new FileStream(documentName, FileMode.Open, FileAccess.Read);
         StreamReader streamReader = new StreamReader(fileStream);
         string line;
         int i = 0;
         while ((line = streamReader.ReadLine()) != null) {
             if (i == 0) {
                 if (line.Length > 0) {
                     if (line.Substring(0, 3).Equals("rev")) {
                         isRevision = true;
                         line = line.Substring(3);
                     }
                     hash = int.Parse(line);
                 }
             } else {
                 revision += line + "\n";
             }
             i++;
         }
         streamReader.Close();
         fileStream.Close();
         Document document = new Document {
             Id = id,
             Title = pathName.Replace(parts[0] + "-", "").Replace(".txt", ""),
             Parent = parent,
             CurrentRevision = revision,
             CurrentHash = (id == 0 ? revision.GetHashCode() : hash),
             IsMerged = isRevision
         };
         parent.Documents.Add(document);
     }
 }
 /// <summary>
 /// Download all folders for a specific parent folder. Do this recursively.
 /// </summary>
 /// <param name="parent"></param>
 public void DownloadFolders(IItemContainer parent, Container container = Container.Folder)
 {
     List<Folder> foldersContainer = new List<Folder>();
     using (var dbContext = new sliceofpieEntities2()) {
         IEnumerable<Folder> folders;
         if (container == Container.Project) {
             folders = from folder in dbContext.Folders
                       where folder.ProjectId == parent.Id
                       select folder;
         } else {
             folders = from folder in dbContext.Folders
                       where folder.FolderId == parent.Id
                       select folder;
         }
         foreach (Folder folder in folders) {
             folder.Parent = parent;
             AddFolder(parent, folder.Title, folder.Id, true);
             foldersContainer.Add(folder);
         }
     }
     foreach (Folder folder in foldersContainer) {
         DownloadFolders(folder);
         DownloadDocuments(folder);
     }
 }
 /// <summary>
 /// Download all documents for a specific parent folder.
 /// </summary>
 /// <param name="parent"></param>
 public void DownloadDocuments(IItemContainer parent, Container container = Container.Folder)
 {
     using (var dbContext = new sliceofpieEntities2()) {
         IEnumerable<Document> documents;
         if (container == Container.Project) {
             documents = from document in dbContext.Documents
                         where document.ProjectId == parent.Id
                         select document;
         } else {
             documents = from document in dbContext.Documents
                         where document.FolderId == parent.Id
                         select document;
         }
         foreach (Document document in documents) {
             document.Parent = parent;
             document.IsMerged = false;
             if (File.Exists(document.GetPath())) {
                 FileStream fileStream = new FileStream(document.GetPath(), FileMode.Open, FileAccess.Read);
                 StreamReader streamReader = new StreamReader(fileStream);
                 string line;
                 int i = 0;
                 while ((line = streamReader.ReadLine()) != null) {
                     if (i == 0) {
                         if (line.Length > 0) {
                             if (line.Substring(0, 3).Equals("rev")) {
                                 document.IsMerged = true;
                             }
                         }
                     }
                     i++;
                 }
                 streamReader.Close();
             }
             if (!document.IsMerged) {
                 AddDocument(parent, document.Title, document.CurrentHash + "\n" + document.CurrentRevision, document.Id, true);
             }
         }
     }
 }
 private static IItem GetTemplateItemFromTT(IItemContainer item)
 {
     return ExtensionMatches(item) ? item.As<IItem>() : item.Traverse().First(i => ExtensionMatches(i)).As<IItem>();
 }