/// <summary>
        ///     Gets the value of the specified property of the specified item if the hierarchy supports it, or returns a HRESULT if there was an error.
        /// </summary>
        public static int GetProperty <T>(this IVsHierarchy hierarchy, HierarchyId item, VsHierarchyPropID property, T defaultValue, [MaybeNull] out T result)
        {
            Requires.NotNull(hierarchy, nameof(hierarchy));

            if (item.IsNilOrEmpty || item.IsSelection)
            {
                throw new ArgumentException(null, nameof(item));
            }

            HResult hr = hierarchy.GetProperty(item, (int)property, out object resultObject);

            if (hr.IsOK)
            {
                // NOTE: We consider it a bug in the underlying project system or the caller if this cast fails
                result = (T)resultObject;
                return(HResult.OK);
            }

            if (hr == HResult.MemberNotFound)
            {
                result = defaultValue;
                return(HResult.OK);
            }

            result = default !;
        /// <summary>
        /// Create a file with the given template file and add it to the parent node.
        /// </summary>
        /// <param name="templateFile">The name of the template zip file.</param>
        /// <param name="path">The path to the file to be created.</param>
        /// <returns>true if file is added successfully.</returns>
        public async Task <bool> CreateFileAsync(string templateFile, string path)
        {
            Requires.NotNull(templateFile, nameof(templateFile));
            Requires.NotNullOrEmpty(path, nameof(path));

            string directoryName = Path.GetDirectoryName(path);
            string fileName      = Path.GetFileName(path);

            string?templateLanguage = await GetTemplateLanguageAsync();

            if (string.IsNullOrEmpty(templateLanguage))
            {
                return(false);
            }

            await _projectVsServices.ThreadingService.SwitchToUIThread();

            string templateFilePath = ((Solution2)_dte.Value !.Solution).GetProjectItemTemplate(templateFile, templateLanguage);

            if (templateFilePath != null)
            {
                HierarchyId parentId = _projectVsServices.VsProject.GetHierarchyId(directoryName);
                var         result   = new VSADDRESULT[1];
                string[]    files    = new string[] { templateFilePath };
                _projectVsServices.VsProject.AddItemWithSpecific(parentId, VSADDITEMOPERATION.VSADDITEMOP_RUNWIZARD, fileName, (uint)files.Length, files, IntPtr.Zero, 0, Guid.Empty, null, Guid.Empty, result);

                if (result[0] == VSADDRESULT.ADDRESULT_Success)
                {
                    return(true);
                }
            }

            return(false);
        }
        /// <summary>
        ///     Returns the <see cref="HierarchyId"/> of the given document moniker, or
        ///     <see cref="HierarchyId.Nil"/> if the document moniker is not part of the project.
        /// </summary>
        public static HierarchyId GetHierarchyId(this IVsProject project, string documentMoniker)
        {
            Requires.NotNull(project, nameof(project));
            Requires.NotNullOrEmpty(documentMoniker, nameof(documentMoniker));

            var     priority = new VSDOCUMENTPRIORITY[1];
            int     isFound;
            uint    itemId;
            HResult result = project.IsDocumentInProject(documentMoniker, out isFound, priority, out itemId);

            if (result.Failed)
            {
                throw result.Exception;
            }

            // We only return items that are actually part of the project. CPS returns non-member from this API.
            if (isFound == 0 || priority[0] != VSDOCUMENTPRIORITY.DP_Standard && priority[0] != VSDOCUMENTPRIORITY.DP_Intrinsic)
            {
                return(HierarchyId.Nil);
            }

            HierarchyId id = itemId;

            Assumes.False(id.IsNilOrEmpty);

            return(id);
        }
Пример #4
0
        public void Can_insert_HierarchyId()
        {
            using (_db.Database.BeginTransaction())
            {
                var entities = new List <Patriarch>
                {
                    new() { Id = HierarchyId.Parse("/2/1/"), Name = "Thrór" },
                    new() { Id = HierarchyId.Parse("/2/2/"), Name = "Thráin II" },
                    new() { Id = HierarchyId.Parse("/3/"), Name = "Thorin Oakenshield" }
                };

                _db.AddRange(entities);
                _db.SaveChanges();
                _db.ChangeTracker.Clear();

                var queried = _db.Patriarchy.Where(e => e.Name.StartsWith("Th")).OrderBy(e => e.Id).ToList();

                Assert.Equal(3, queried.Count);

                Assert.Equal(HierarchyId.Parse("/2/1/"), queried[0].Id);
                Assert.Equal("Thrór", queried[0].Name);

                Assert.Equal(HierarchyId.Parse("/2/2/"), queried[1].Id);
                Assert.Equal("Thráin II", queried[1].Name);

                Assert.Equal(HierarchyId.Parse("/3/"), queried[2].Id);
                Assert.Equal("Thorin Oakenshield", queried[2].Name);
            }
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            RemoveVariableModelAnnotations(modelBuilder);

            modelBuilder.Entity <Patriarch>().HasData(
                new { Id = HierarchyId.GetRoot(), Name = "Eddard Stark" },
                new { Id = HierarchyId.Parse("/1/"), Name = "Robb Stark" },
                new { Id = HierarchyId.Parse("/2/"), Name = "Jon Snow" });

            modelBuilder.Entity <ConvertedPatriarch>(b =>
            {
                b.Property(e => e.HierarchyId)
                .HasConversion(v => HierarchyId.Parse(v), v => v.ToString());

                b.HasData(
                    new ConvertedPatriarch {
                    Id = 1, HierarchyId = HierarchyId.GetRoot().ToString(), Name = "Eddard Stark"
                },
                    new ConvertedPatriarch {
                    Id = 2, HierarchyId = HierarchyId.Parse("/1/").ToString(), Name = "Robb Stark"
                },
                    new ConvertedPatriarch {
                    Id = 3, HierarchyId = HierarchyId.Parse("/2/").ToString(), Name = "Jon Snow"
                });
            });
        }
            // <summary>
            // Initializes a map from primitive scalar types in the C-Space to default values
            // used within the placeholder.
            // </summary>
            private static Dictionary <PrimitiveTypeKind, object> InitializeTypeDefaultMap()
            {
                var typeDefaultMap = new Dictionary <PrimitiveTypeKind, object>(
                    EqualityComparer <PrimitiveTypeKind> .Default);

                // Use CLR defaults for value types, arbitrary constants for reference types
                // (since these default to null)
                typeDefaultMap[PrimitiveTypeKind.Binary]         = new Byte[0];
                typeDefaultMap[PrimitiveTypeKind.Boolean]        = default(Boolean);
                typeDefaultMap[PrimitiveTypeKind.Byte]           = default(Byte);
                typeDefaultMap[PrimitiveTypeKind.DateTime]       = default(DateTime);
                typeDefaultMap[PrimitiveTypeKind.Time]           = default(TimeSpan);
                typeDefaultMap[PrimitiveTypeKind.DateTimeOffset] = default(DateTimeOffset);
                typeDefaultMap[PrimitiveTypeKind.Decimal]        = default(Decimal);
                typeDefaultMap[PrimitiveTypeKind.Double]         = default(Double);
                typeDefaultMap[PrimitiveTypeKind.Guid]           = default(Guid);
                typeDefaultMap[PrimitiveTypeKind.Int16]          = default(Int16);
                typeDefaultMap[PrimitiveTypeKind.Int32]          = default(Int32);
                typeDefaultMap[PrimitiveTypeKind.Int64]          = default(Int64);
                typeDefaultMap[PrimitiveTypeKind.Single]         = default(Single);
                typeDefaultMap[PrimitiveTypeKind.SByte]          = default(SByte);
                typeDefaultMap[PrimitiveTypeKind.String]         = String.Empty;
                typeDefaultMap[PrimitiveTypeKind.HierarchyId]    = HierarchyId.GetRoot();

#if DEBUG
                foreach (var o in typeDefaultMap.Values)
                {
                    Debug.Assert(null != o, "DbConstantExpression instances do not support null values");
                }
#endif

                return(typeDefaultMap);
            }
        public ActionResult ReParent(string costCode, string newParent)
        {
            if (string.Equals(costCode, newParent, StringComparison.InvariantCultureIgnoreCase))
            {
                return(Json(new { costCode, success = false }));
            }
            var costCentre   = context.CostCentres.Find(costCode);
            var parentCentre = context.CostCentres.Find(newParent);

            if ((costCentre == null) || (parentCentre == null))
            {
                return(Json(new { costCode, success = false }));
            }
            var newParentNode = parentCentre.Node;
            var oldNode       = costCentre.Node;

            var orderId = context
                          .CostCentres
                          .Count(c => c.ParentCostCentreCostCode == newParent) + 1;
            var newNodeString = newParentNode.ToString() + orderId + "/";
            var newNode       = new HierarchyId(newNodeString);

            ReParentNodes(newNode, oldNode);

            costCentre.ParentCostCentreCostCode = newParent;
            context.SaveChanges();

            return(Json(new { costCode, success = true }));
        }
Пример #8
0
        //public void Add(ProductCategoryDto add, int? parentId)
        //{
        //    var entity = Context.HierarchyCategory.Create();
        //    entity.Name = add.Name;
        //    Context.HierarchyCategory.Add(entity);
        //    Context.SaveChanges();

        //    if (!parentId.HasValue)
        //    {
        //        entity.Level = HierarchyId.Parse(string.Format("/{0}/", entity.Id));
        //    }
        //    else
        //    {
        //        var parentEntity = Context.HierarchyCategory.FirstOrDefault(x => x.Id == parentId);
        //        entity.Level = HierarchyId.Parse(string.Format("{0}{1}/", parentEntity.Level.ToString(), entity.Id));
        //    }
        //    Context.SaveChanges();
        //}

        public void Add(ProductCategoryDto add, int?parentId)
        {
            var entity = Context.HierarchyCategory.Create();

            entity.Name = add.Name;

            HierarchyId       parentItem;
            HierarchyCategory lastItemInCurrentLevel;

            if (!parentId.HasValue)
            {
                parentItem = HierarchyId.GetRoot();
            }
            else
            {
                parentItem = Context.HierarchyCategory.FirstOrDefault(x => x.Id == parentId).Level;
            }

            lastItemInCurrentLevel = Context.HierarchyCategory
                                     .Where(x => x.Level.GetAncestor(1) == parentItem)
                                     .OrderByDescending(x => x.Level)
                                     .FirstOrDefault();

            var child1Level = lastItemInCurrentLevel != null ? lastItemInCurrentLevel.Level : null;

            var newLevel = parentItem.GetDescendant(child1Level, null);

            entity.Level = newLevel;

            Context.HierarchyCategory.Add(entity);
            Context.SaveChanges();
        }
Пример #9
0
        private void HierarchyIdIsPersistedCorrectlyLargerHierarchyTest()
        {
            ContextUtil.DbServer = DbServer.SQLServer;
            using (var context = new TestContext(ContextUtil.GetOptions()))
            {
                context.BulkDelete(context.Categories.ToList());
            }

            var nodeIdAsString = "/1.1/-2/3/4/5/";

            using (var context = new TestContext(ContextUtil.GetOptions()))
            {
                var entities = new List <Category> {
                    new Category
                    {
                        Name = "Deep Element",
                        HierarchyDescription = HierarchyId.Parse(nodeIdAsString)
                    }
                };
                context.BulkInsertOrUpdate(entities);
            }

            using (var context = new TestContext(ContextUtil.GetOptions()))
            {
                var category = context.Categories.Single();
                Assert.Equal(nodeIdAsString, category.HierarchyDescription.ToString());
            }
        }
Пример #10
0
        /// <summary>
        ///     Gets the value of the specified property if the hierarchy supports it.
        /// </summary>
        public static T GetProperty <T>(this IVsHierarchy hierarchy, HierarchyId item, VsHierarchyPropID property, T defaultValue)
        {
            Requires.NotNull(hierarchy, nameof(hierarchy));

            if (item.IsNilOrEmpty || item.IsSelection)
            {
                throw new ArgumentException(null, nameof(item));
            }

            object  resultObject;
            HResult hr = hierarchy.GetProperty(item, (int)property, out resultObject);

            if (hr == VSConstants.DISP_E_MEMBERNOTFOUND)
            {
                return(defaultValue);
            }

            if (hr.Failed)
            {
                throw hr.Exception;
            }

            // NOTE: We consider it a bug in the underlying project system or the caller if this cast fails
            return((T)resultObject);
        }
Пример #11
0
        public List <ProductCategoryDto> GetAll()
        {
            var root = HierarchyId.GetRoot();

            var parentEntity = Context.HierarchyCategory.FirstOrDefault(x => x.Level.IsDescendantOf(root));

            return(new List <ProductCategoryDto>());
        }
        /// <summary>
        ///     Gets the value of the specified property of the specified item if the hierarchy supports it, or throws an exception if there was an error.
        /// </summary>
        public static T GetProperty <T>(this IVsHierarchy hierarchy, HierarchyId item, VsHierarchyPropID property, [MaybeNull] T defaultValue = default)
        {
#pragma warning disable CS8717 // Needs https://github.com/dotnet/roslyn/issues/38638
            Verify.HResult(GetProperty(hierarchy, item, property, defaultValue, out T result));
#pragma warning restore CS8717

            return(result);
        }
        public void Implicit_ToUInt32_ReturnsId(uint id)
        {
            var hierarchyId = new HierarchyId(id);

            uint result = hierarchyId;

            Assert.Equal(id, result);
        }
Пример #14
0
        /// <summary>
        /// Возвращает путь для вставки в конец
        /// </summary>
        /// <param name="parentBlock"></param>
        /// <returns></returns>
        public HierarchyId GetAppendPath(Block parentBlock)
        {
            var index = context.Blocks.Count(x => x.Level == parentBlock.Level + 1 &&
                                             x.Path.IsDescendantOf(parentBlock.Path)) + 1;
            HierarchyId newItemPath = HierarchyId.Parse(parentBlock.Path + index.ToString() + "/");

            return(newItemPath);
        }
Пример #15
0
        // --------------------------------------------------------------------------------------------
        /// <summary>
        /// Gets the state of the item.
        /// </summary>
        /// <param name="manager">The manager.</param>
        /// <param name="id">The id.</param>
        /// <param name="stateMask">The state mask.</param>
        /// <returns></returns>
        // --------------------------------------------------------------------------------------------
        public __VSHIERARCHYITEMSTATE GetNodeState(IHierarchyManager manager, HierarchyId id,
                                                   __VSHIERARCHYITEMSTATE stateMask)
        {
            uint result;

            HierarchyWindow.GetNodeState(manager, (uint)id, (uint)stateMask, out result);
            return((__VSHIERARCHYITEMSTATE)(result));
        }
Пример #16
0
        public MappingProfile()
        {
            //from Domain to API Resource

            CreateMap <Category, CategoryResource>();

            CreateMap <Products, ProductResource>();


            //CreateMap<MyDbAcct, MyDBAcctsResources>();
            //CreateMap<MyDBAcctsResources, MyDbAcct>();


            CreateMap <MyDbAcct, MyDBAcctsResources>();
            CreateMap <MyDBAcctsResources, MyDbAcct>()
            .ForMember(a => a.acctId, opt => opt.Ignore());



            CreateMap <string, HierarchyId>().ConvertUsing(s => HierarchyId.Parse(s));


            CreateMap <Purchase, SavePurchaseResource>();
            CreateMap <SavePurchaseResource, Purchase>()
            .ForMember(p => p.purchId, opt => opt.Ignore()); //ignor mapping this field

            CreateMap <Purchase, PurchaseResource>()
            .ForMember(pr => pr.purchaseItems, opt => opt.MapFrom(p => p.purchaseItems));
            //.ForMember(dest => dest.dbAcct,opt => opt.MapFrom(src => src.dbAcct));
            //.ForMember(pr=>pr.purchaseItems,opt=>opt.MapFrom(p=>p.purchaseItems.Select(pr=> pr.Products)));

            //.ForPath(dest => dest.purchase,opt => opt.MapFrom(src => src.dbAcct.Purchases))
            //.ForMember(pr=>pr.product,op=>opt.MapFrom(p=>p.purchaseItems))

            //.ForMember(pr=>pr.Products,opt=>opt.MapFrom(p=> new ProductResource {prodName = "Hello" }))
            //.ForMember(dest => dest.Products.prodName,opt => opt.UseValue<string>("Hello"));

            //.ForMember(pr=>pr.product,opt=>opt.MapFrom(p=>p.purchaseItems.Select(pr=> new ProductResource{prodId = pr.prodId})));
            //.AfterMap((p,pr)=> Mapper.Map(p.purchaseItems,pr.Products));

            CreateMap <Purchase, PurchaseResource>();
            CreateMap <PurchaseResource, Purchase>();


            CreateMap <PurchaseItems, PurchaseItemsResource>();
            CreateMap <PurchaseItemsResource, PurchaseItems>();

            //from API Resource(source) to Domain
            //CreateMap<PurchaseResource, Purchase>()
            //    .ForMember(p=>p.purchaseItems,opt=>opt.MapFrom(pr=>pr.purchaseItems.Select(id=>new PurchaseItems {purchId = id})));

            CreateMap <PurchaseQuereyResource, PurchaseQuery>();
            CreateMap <PurchaseQuery, PurchaseQuereyResource>();



            //CreateMap<PurchaseItemsResource, PurchaseItems>();
        }
Пример #17
0
        /// <summary>
        ///     Opens the specified item with the specified editor using the primary logical view.
        /// </summary>
        /// <returns>
        ///     The <see cref="IVsWindowFrame"/> that contains the editor; otherwise, <see langword="null"/> if it was opened
        ///     with an editor external of Visual Studio.
        /// </returns>
        public static IVsWindowFrame?OpenItemWithSpecific(this IVsProject4 project, HierarchyId id, Guid editorType)
        {
            Requires.NotNull(project, nameof(project));

            Verify.HResult(project.OpenItemWithSpecific(id, 0, ref editorType, "", VSConstants.LOGVIEWID_Primary, (IntPtr)(-1), out IVsWindowFrame frame));

            // NOTE: frame is 'null' when opened in an external editor
            return(frame);
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            RemoveVariableModelAnnotations(modelBuilder);

            modelBuilder.Entity <Patriarch>().HasData(
                new { Id = HierarchyId.GetRoot(), Name = "Eddard Stark" },
                new { Id = HierarchyId.Parse("/1/"), Name = "Robb Stark" },
                new { Id = HierarchyId.Parse("/2/"), Name = "Jon Snow" });
        }
Пример #19
0
        public Block AddRoot()
        {
            Block systemRoot = new Block()
            {
                Id = Guid.NewGuid(), BlockName = "_SystemRoot", Path = HierarchyId.GetRoot()
            };

            context.Blocks.Add(systemRoot);
            return(systemRoot);
        }
Пример #20
0
        public static T GetProperty <T>(this IVsHierarchy hierarchy, HierarchyId item, VsHierarchyPropID property, T defaultValue = default)
        {
            HResult hr = GetProperty(hierarchy, item, property, defaultValue, out T result);

            if (hr.Failed)
            {
                throw hr.Exception;
            }

            return(result);
        }
        public virtual IQueryable <HierarchyId> SupplierHierarchyIdsWithinRange(HierarchyId path1, HierarchyId path2)
        {
            var objectContext = ((IObjectContextAdapter)this).ObjectContext;

            objectContext.MetadataWorkspace.LoadFromAssembly(typeof(SupplierWithHierarchyId).Assembly);

            return(objectContext.CreateQuery <HierarchyId>(
                       "[HierarchyIdNorthwindContext].[SupplierHierarchyIdsWithinRange](@path1, @path2)",
                       new ObjectParameter("path1", path1),
                       new ObjectParameter("path2", path2)));
        }
        /// <summary>
        ///     Gets the value of the specified property of the specified item if the hierarchy supports it, or throws an exception if there was an error.
        /// </summary>
        public static T GetProperty <T>(this IVsHierarchy hierarchy, HierarchyId item, VsHierarchyPropID property, [MaybeNull] T defaultValue = default)
        {
#pragma warning disable CS8717 // Needs https://github.com/dotnet/roslyn/issues/38638
            HResult hr = GetProperty(hierarchy, item, property, defaultValue, out T result);
#pragma warning restore CS8717
            if (hr.Failed)
            {
                throw hr.Exception;
            }

            return(result);
        }
    public static HierarchyId CommonAncestor(
        SqlHierarchyId h1,
        HierarchyId h2
        )
    {
        while (!h1.IsDescendantOf(h2))
        {
            h1 = h1.GetAncestor(1);
        }

        return(h1);
    }
        public void Should_GetEphraimEntryById()
        {
            // Arrange
            var databaseContext = new AbrahamicContext();

            // Act
            databaseContext.Database.EnsureCreated();
            var ephraim = databaseContext.Patriarchy.Single(w => w.Id == HierarchyId.Parse("/1/1/11.1/"));

            // Assert
            Assert.Equal("Ephraim", ephraim.Name);
        }
Пример #25
0
 public static decimal GetTotal(
     Func <DateTime, DateTime, HierarchyId, HierarchyId, decimal> totalFunc,
     DateTime startDate,
     DateTime endDate,
     HierarchyId activityNode,
     HierarchyId centreNode,
     HierarchyId[] nodes)
 {
     return(activityNode == null
         ? nodes.Sum(a => totalFunc(startDate, endDate, a, centreNode))
         : totalFunc(startDate, endDate, activityNode, centreNode));
 }
Пример #26
0
        public void Parse_can_translate()
        {
            var results = Enumerable.ToList(
                from p in _db.Patriarchy
                where p.Id == HierarchyId.GetRoot()
                select HierarchyId.Parse(p.Id.ToString()));

            Assert.Equal(
                condense(@"SELECT hierarchyid::Parse([p].[Id].ToString()) FROM [Patriarchy] AS [p] WHERE [p].[Id] = '/'"),
                condense(_db.Sql));

            Assert.Equal(new[] { HierarchyId.Parse("/") }, results);
        }
Пример #27
0
        public void Converted_HierarchyId_can_be_sent_as_parameter()
        {
            var results = Enumerable.ToList(
                from p in _db.ConvertedPatriarchy
                where p.HierarchyId == HierarchyId.Parse("/1/").ToString()
                select p.Name);

            Assert.Equal(
                condense(@"SELECT [c].[Name] FROM [ConvertedPatriarchy] AS [c] WHERE [c].[HierarchyId] = '/1/'"),
                condense(_db.Sql));

            Assert.Equal(new[] { "Isaac" }, results);
        }
Пример #28
0
        public void GetAncestor_3_can_translate()
        {
            var results = Enumerable.ToList(
                from p in _db.Patriarchy
                where p.Id.GetLevel() == 3
                select p.Id.GetAncestor(3));

            Assert.Equal(
                condense(@"SELECT [p].[Id].GetAncestor(3) FROM [Patriarchy] AS [p] WHERE [p].[Id].GetLevel() = CAST(3 AS smallint)"),
                condense(_db.Sql));

            Assert.All(results, h => Assert.Equal(HierarchyId.GetRoot(), h));
        }
        private ProjectItem GetProjectItemForDocumentMoniker(string documentMoniker)
        {
            ThreadingService.VerifyOnUIThread();

            HierarchyId id = _projectVsServices.VsProject.GetHierarchyId(documentMoniker);

            if (id.IsNil || id.IsRoot)
            {
                return(null);
            }

            return(_projectVsServices.VsHierarchy.GetProperty(id, VsHierarchyPropID.ExtObject, (ProjectItem)null));
        }
Пример #30
0
 private void ReParentNodes(HierarchyId newNode, HierarchyId oldNode)
 {
     foreach (var centre in context.CostCentres.Where(centre => centre.Node.IsDescendantOf(oldNode)))
     {
         var reparentedNode = centre.Node.GetReparentedValue(oldNode, newNode);
         centre.Node = reparentedNode;
         var code = centre.CostCode;
         foreach (var entry in context.CarbonEmissionEntries.Where(e => e.SourceEntry.CostCode == code))
         {
             entry.CostCentreNode = centre.Node;
         }
     }
 }
Пример #31
0
        public ActionResult ReParent(string costCode, string newParent)
        {
            if (string.Equals(costCode, newParent, StringComparison.InvariantCultureIgnoreCase))
            {
                return Json(new {costCode, success = false});
            }
            var costCentre = context.CostCentres.Find(costCode);
            var parentCentre = context.CostCentres.Find(newParent);
            if ((costCentre == null) || (parentCentre == null))
            {
                return Json(new {costCode, success = false});
            }
            var newParentNode = parentCentre.Node;
            var oldNode = costCentre.Node;

            var orderId = context
                .CostCentres
                .Count(c => c.ParentCostCentreCostCode == newParent) + 1;
            var newNodeString = newParentNode.ToString() + orderId + "/";
            var newNode = new HierarchyId(newNodeString);

            ReParentNodes(newNode, oldNode);

            costCentre.ParentCostCentreCostCode = newParent;
            context.SaveChanges();

            return Json(new {costCode, success = true});
        }
Пример #32
0
 public static decimal GetTotal(
     Func<DateTime, DateTime, HierarchyId, HierarchyId, decimal> totalFunc,
     DateTime startDate,
     DateTime endDate,
     HierarchyId activityNode,
     HierarchyId centreNode,
     HierarchyId[] nodes)
 {
     return activityNode == null
         ? nodes.Sum(a => totalFunc(startDate, endDate, a, centreNode))
         : totalFunc(startDate, endDate, activityNode, centreNode);
 }
Пример #33
0
 public decimal TotalUnits(
     DateTime startDate,
     DateTime endDate,
     HierarchyId groupNode,
     HierarchyId centreNode)
 {
     var query =
         from e in context.CarbonEmissionEntries
         where
             (e.EntryDate >= startDate) &&
             (e.EntryDate <= endDate) &&
             (e.ActivityGroupNode.IsDescendantOf(groupNode)) &&
             (e.CostCentreNode.IsDescendantOf(centreNode))
         select (decimal?) e.Units;
     return query.Sum() ?? 0M;
 }
Пример #34
0
     GetCurrencies(
     DateTime startDate,
     DateTime endDate,
     HierarchyId[] nodes,
     HierarchyId centreNode)
 {
     var currencyTotals = new SortedDictionary<string, decimal>();
     foreach (var node in nodes)
     {
         var activityId = node;
         foreach (var total in 
             from e in context.CarbonEmissionEntries
             where
                 (e.EntryDate >= startDate) &&
                 (e.EntryDate <= endDate) &&
                 (e.ActivityGroupNode.IsDescendantOf(activityId)) &&
                 (e.CostCentreNode.IsDescendantOf(centreNode))
             group
                 e.Money
                 by e.CostCentre.CurrencyCode
             into g
             select new
             {
                 Code = g.Key,
                 TotalMoney = g.Sum()
             })
         {
             if (currencyTotals.ContainsKey(total.Code))
             {
                 currencyTotals[total.Code] = currencyTotals[total.Code] + total.TotalMoney;
             }
             else
             {
                 currencyTotals.Add(total.Code, total.TotalMoney);
             }
         }
     }
     return currencyTotals
         .Select(pair => string.Format(CurrenciesContext.Cultures[pair.Key], "{0:C}", pair.Value));
 }
Пример #35
0
        public ActionResult ReOrder(string costCode, int index)
        {
            var costCentre = context.CostCentres.Find(costCode);
            if (costCentre == null)
            {
                return Json(new {costCode, success = false});
            }
            var parentCostCode = costCentre.ParentCostCentreCostCode;
            var parent = context.CostCentres.Find(parentCostCode);
            var currentOrderId = costCentre.OrderId;
            var indexOrderId = index*100;
            var destinationOrderId = indexOrderId + 1;
            var nodeId = index;
            var shift = -1;
            var centres = context
                .CostCentres
                .Where(c => (c.ParentCostCentreCostCode == parentCostCode));

            if (currentOrderId > indexOrderId)
            {
                shift = 1;
                destinationOrderId = indexOrderId - 1;
                nodeId = (index - 1);
                centres = centres
                    .Where(c => (c.OrderId > destinationOrderId) && (c.OrderId <= currentOrderId))
                    .OrderByDescending(c => c.OrderId);
            }
            else
            {
                centres = centres
                    .Where(c => (c.OrderId >= currentOrderId) && (c.OrderId < destinationOrderId))
                    .OrderBy(c => c.OrderId);
            }

            var parentNode = parent.Node;
            var currentNode = costCentre.Node;
            var tempNode = new HierarchyId(parentNode.ToString() + nodeId + ".1/");
            ReParentNodes(tempNode, currentNode);
            costCentre.OrderId = destinationOrderId;
            context.SaveChanges();

            foreach (var centre in centres)
            {
                var orderId = centre.OrderId/100;
                orderId = orderId + shift;
                var node = centre.Node;
                var newNode = new HierarchyId(parentNode.ToString() + orderId + "/");
                ReParentNodes(newNode, node);
                centre.OrderId = orderId*100;
            }
            context.SaveChanges();

            var updatedNode = new HierarchyId(parentNode.ToString() + index + "/");
            ReParentNodes(updatedNode, tempNode);
            costCentre.OrderId = index*100;
            context.SaveChanges();
            
            return Json(new {costCode, success = true});
        }
Пример #36
0
 public ISiteItem GetSiteItem(HierarchyId id)
 {
     throw new NotImplementedException();
 }
Пример #37
0
 private void ReParentNodes(HierarchyId newNode, HierarchyId oldNode)
 {
     foreach (var centre in context.CostCentres.Where(centre => centre.Node.IsDescendantOf(oldNode)))
     {
         var reparentedNode = centre.Node.GetReparentedValue(oldNode, newNode);
         centre.Node = reparentedNode;
         var code = centre.CostCode;
         foreach (var entry in context.CarbonEmissionEntries.Where(e => e.SourceEntry.CostCode == code))
         {
             entry.CostCentreNode = centre.Node;
         }
     }
 }
     AverageUnits(
     DateTime startDate,
     DateTime endDate,
     HierarchyId groupNode,
     HierarchyId centreNode)
 {
     var query =
         from e in context.CarbonEmissionEntries
         where
             (e.EntryDate >= startDate) &&
             (e.EntryDate <= endDate) &&
             (e.ActivityGroupNode.IsDescendantOf(groupNode)) &&
             (e.CostCentreNode.IsDescendantOf(centreNode))
         group e.Units by
             ((e.EntryDate.Year * 100) + (e.EntryDate.Month))
             into g
             select new AverageData
             {
                 Average = g.Average(),
                 YearMonth = g.Key
             };
     return query;
 }