Example #1
0
        static void Main()
        {
            var hierarchy = new Hierarchy<string>("Leonidas");
            hierarchy.Add("Leonidas", "Xena The Princess Warrior");
            hierarchy.Add("Leonidas", "General Protos");
            hierarchy.Add("Xena The Princess Warrior", "Gorok");
            hierarchy.Add("Xena The Princess Warrior", "Bozot");
            hierarchy.Add("General Protos", "Subotli");
            hierarchy.Add("General Protos", "Kira");
            hierarchy.Add("General Protos", "Zaler");

            var children = hierarchy.GetChildren("Leonidas");
            Console.WriteLine(string.Join(", ", children));

            var parent = hierarchy.GetParent("Kira");
            Console.WriteLine(parent);

            hierarchy.Remove("General Protos");
            children = hierarchy.GetChildren("Leonidas");
            Console.WriteLine(string.Join(", ", children));

            //foreach (var item in hierarchy)
            //{
            //    Console.WriteLine(item);
            //}
        }
Example #2
0
 public JobGraphViewModel(Guid jobId)
 {
     Hierarchy hierarchy = new Hierarchy();
     Tag jobHierarchicalTree = hierarchy.GetHierarchicalTreeByObject(jobId);
     this.JobHierarchicalTree = jobHierarchicalTree;
     this.JobId = jobId;
 }
        public void PerformanceRemove_With2GroupsOf25000RemovalsWith50000Elements()
        {
            var count = 50001;
            var counter1 = 1;
            var counter2 = 25001;
            var hierarchy = new Hierarchy<int>(-1);
            hierarchy.Add(-1, 1);
            hierarchy.Add(-1, 25001);
            for (int i = 1; i < 25000; i++)
            {
                hierarchy.Add(counter1, ++counter1);
                hierarchy.Add(counter2, ++counter2);
            }

            Stopwatch timer = new Stopwatch();
            timer.Start();
            for (int i = 1; i < 25001; i++)
            {
                hierarchy.Remove(i);
                hierarchy.Remove(25000 + i);
                count -= 2;
                Assert.AreEqual(count, hierarchy.Count, "Count did not decrease correctly!");
            }
            timer.Stop();
            Assert.IsTrue(timer.ElapsedMilliseconds < 200);

            Assert.AreEqual(1, hierarchy.Count, "Incorrect count after removal!");
            Assert.IsTrue(hierarchy.Contains(-1));
            CollectionAssert.AreEqual(new int[0], hierarchy.GetChildren(-1).ToArray(), "Children were not deleted correcly after removal!");
        }
        public void PerformanceGetParent_With50000ElementsWith5000Parents()
        {
            var counter = 5001;
            var hierarchy = new Hierarchy<int>(-88);
            for (int i = 1; i <= 5000; i++)
            {
                hierarchy.Add(-88, i);
                for (int j = 0; j < 10; j++)
                {
                    hierarchy.Add(i, counter++);
                }
            }

            counter = 5001;
            Stopwatch timer = new Stopwatch();
            timer.Start();

            for (int i = 1; i <= 5000; i++)
            {
                Assert.AreEqual(-88, hierarchy.GetParent(i), "Expected parent did not match!");
                for (int j = 0; j < 10; j++)
                {
                    Assert.AreEqual(i, hierarchy.GetParent(counter++), "Expected parent did not match!");
                }
            }

            timer.Stop();
            Assert.IsTrue(timer.ElapsedMilliseconds < 200);
        }
        public void PerformanceAdd_WithOnly2ParentWith50000SplitElements()
        {
            var count = 3;
            var counter1 = 1;
            var counter2 = 25001;
            var hierarchy = new Hierarchy<int>(-1);
            Stopwatch timer = new Stopwatch();
            timer.Start();
            hierarchy.Add(-1, 1);
            hierarchy.Add(-1, 25001);
            for (int i = 1; i < 25000; i++)
            {
                hierarchy.Add(1, ++counter1);
                hierarchy.Add(25001, ++counter2);
                count += 2;
                Assert.AreEqual(count, hierarchy.Count, "Count did not increase correctly!");
            }

            timer.Stop();
            Assert.IsTrue(timer.ElapsedMilliseconds < 200);
            counter1 = 1;
            counter2 = 25001;
            for (int i = 1; i < 25000; i++)
            {
                Assert.AreEqual(1, hierarchy.GetParent(++counter1), "Parent did not match!");
                Assert.AreEqual(25001, hierarchy.GetParent(++counter2), "Parent did not match!");
            }

            CollectionAssert.AreEqual(Enumerable.Range(2, 24999).ToArray(), hierarchy.GetChildren(1).ToArray(), "Children did not match!");
            CollectionAssert.AreEqual(Enumerable.Range(25002, 24999).ToArray(), hierarchy.GetChildren(25001).ToArray(), "Children did not match!");
        }
Example #6
0
 /// <summary>
 /// Constructor for the <c>FieldScanner</c> object. This is
 /// used to perform a scan on the specified class in order to find
 /// all fields that are labeled with an XML annotation.
 /// </summary>
 /// <param name="type">
 /// this is the schema class that is to be scanned
 /// </param>
 /// <param name="access">
 /// this is the access type for the class
 /// </param>
 public FieldScanner(Class type, DefaultType access) {
    this.factory = new AnnotationFactory();
    this.hierarchy = new Hierarchy(type);
    this.done = new ContactMap();
    this.access = access;
    this.Scan(type);
 }
Example #7
0
 public JSParserResult()
 {
     Nodes = new Hierarchy<CodeNode>(new CodeNode(){Alias = "All"});
     Errors = new List<ErrorMessage>();
     InternalErrors = new List<ErrorMessage>();
     TaskList = new List<TaskListItem>();
 }
Example #8
0
 public JobGraphViewModel(string jobtile)
 {
     Hierarchy hierarchy = new Hierarchy();
     Tag decisionTree = hierarchy.GetHierarchicalTreeByDecisionTree(jobtile);
     this.DecisionTree = decisionTree;
     this.JobTitile = jobtile;
 }
        public void PerformanceRemove_With20000RemovalsIn4GroupsInReverseOrderFromTheMiddleWith40000Elements()
        {
            var counter1 = 10000;
            var counter2 = 20000;
            var counter3 = 30000;
            var counter4 = 40000;
            var hierarchy = new Hierarchy<int>(-2);

            hierarchy.Add(-2, 10000);
            hierarchy.Add(-2, 20000);
            hierarchy.Add(-2, 30000);
            hierarchy.Add(-2, 40000);
            for (int i = 1; i < 10000; i++)
            {
                hierarchy.Add(counter1, --counter1);
                hierarchy.Add(counter2, --counter2);
                hierarchy.Add(counter3, --counter3);
                hierarchy.Add(counter4, --counter4);
            }

            var count = 40001;
            counter1 = 9000;
            counter2 = 18000;
            counter3 = 27000;
            counter4 = 36000;
            Stopwatch timer = new Stopwatch();
            timer.Start();
            for (int i = 1; i < 5001; i++)
            {
                hierarchy.Remove(counter1--);
                hierarchy.Remove(counter2--);
                hierarchy.Remove(counter3--);
                hierarchy.Remove(counter4--);
                count -= 4;
                Assert.AreEqual(count, hierarchy.Count, "Count did not decrease correctly!");
            }

            timer.Stop();
            Assert.IsTrue(timer.ElapsedMilliseconds < 200);

            Assert.AreEqual(20001, hierarchy.Count, "Incorrect count after removal!");
            counter1 = 9000;
            counter2 = 18000;
            counter3 = 27000;
            counter4 = 36000;
            for (int i = 0; i < 5000; i++)
            {
                Assert.IsFalse(hierarchy.Contains(counter1--));
                Assert.IsFalse(hierarchy.Contains(counter2--));
                Assert.IsFalse(hierarchy.Contains(counter3--));
                Assert.IsFalse(hierarchy.Contains(counter4--));
            }

            Assert.IsTrue(hierarchy.Contains(-2));
            CollectionAssert.AreEqual(new[] { 4000 }, hierarchy.GetChildren(9001).ToArray(), "Children were not correctly reattached!");
            CollectionAssert.AreEqual(new[] { 13000 }, hierarchy.GetChildren(18001).ToArray(), "Children were not correctly reattached!");
            CollectionAssert.AreEqual(new[] { 22000 }, hierarchy.GetChildren(27001).ToArray(), "Children were not correctly reattached!");
            CollectionAssert.AreEqual(new[] { 31000 }, hierarchy.GetChildren(36001).ToArray(), "Children were not correctly reattached!");
        }
        public void PerformanceForEach_With55500ElementsInterconnected()
        {
            var start1 = 0;
            var elements = new List<int>();
            elements.Add(start1);
            var hierarchy = new Hierarchy<int>(start1);

            for (int i = 1; i <= 51100; i = i + 511)
            {
                hierarchy.Add(start1, i);
                for (int j = i + 1; j <= i + 510; j = j + 51)
                {
                    hierarchy.Add(i, j);
                    for (int k = j + 1; k <= j + 50; k++)
                    {
                        hierarchy.Add(j, k);
                    }
                }
            }

            for (int i = 1; i <= 51100; i = i + 511)
            {
                elements.Add(i);
            }

            for (int i = 1; i <= 51100; i = i + 511)
            {
                for (int j = i + 1; j <= i + 510; j = j + 51)
                {
                    elements.Add(j);
                }
            }

            for (int i = 1; i <= 51100; i = i + 511)
            {
                for (int j = i + 1; j <= i + 510; j = j + 51)
                {
                    for (int k = j + 1; k <= j + 50; k++)
                    {
                        elements.Add(k);
                    }
                }
            }

            var counter = 0;

            Stopwatch timer = new Stopwatch();
            timer.Start();

            foreach (var element in hierarchy)
            {
                Assert.AreEqual(elements[counter++], element, "Expected element did not match!");
            }

            timer.Stop();
            Assert.IsTrue(timer.ElapsedMilliseconds < 200);

            Assert.AreEqual(counter, hierarchy.Count, "Incorect number of elements returned!");
        }
        public SceneFragment(String filename, Hierarchy hierarchy)
            : base(filename)
        {
            m_Hierarchy = hierarchy;

            if ( m_Hierarchy != null )
                m_ParentNode = hierarchy.RootNode;
        }
Example #12
0
 private Hierarchy GetTestHierarchy()
 {
     var hierarchy = new Hierarchy();
     hierarchy.Add(this.GetTermSet(5));
     hierarchy.Add(this.GetTermSet(7));
     hierarchy.Add(this.GetTermSet(9));
     return hierarchy;
 }
 public FilteredByNameSet(string name, Hierarchy hier, Level lev,  string GrOrEq ,string LessOrEq)
     : base(name, hier)
 {
     this.MdxParameters.Add(lev, true);
     this._grOrEq=GrOrEq;
     this._lessOrEq=LessOrEq;
     Initialize(name);
 }
        public MemToVisAggr(Hierarchy HostHier, System.Xml.XmlElement xmlEl)
            : base(null, HostHier)
        {
            if(HostHier.UniqueName!="[Measures]")
                throw new Exception("Cannot create on non-measures hierarchy");

            LoadFromXml(xmlEl);
        }
        public void GetCommonElements_WithHierarchyWithoutCommonElements_ShouldReturnAnEmptyCollection()
        {
            var otherHierarchy = new Hierarchy<int>(1);

            var result = this.Hierarchy.GetCommonElements(otherHierarchy).ToArray();

            CollectionAssert.AreEquivalent(result, new int[0],"GetCommonElements returned an incorrect collection!");
        }
 public static void SetParent(this ChangeSetBuilder pendingChanges, Hierarchy hierarchy, Unit target, Unit newParent)
 {
     var parentHierarchyNode = EnsureIsPartOfHierarchy(newParent, hierarchy, pendingChanges);
     var hierarchyNode = EnsureIsPartOfHierarchy(target, hierarchy, pendingChanges);
     EnsureDetachedFromFormerParent(hierarchyNode, pendingChanges);
     pendingChanges
         .Add(new AttachChildCommand(parentHierarchyNode.Id, hierarchyNode.Id))
         .Add(new SetParentCommand(hierarchyNode.Id, parentHierarchyNode.Id));
 }
        public void GetCommonElements_WithHierarchyWithOneCommonElement_ShouldReturnACollectionOfCorrectElement()
        {
            var otherHierarchy = new Hierarchy<int>(1);
            otherHierarchy.Add(1,13);
            this.Hierarchy.Add(DefaultRootValue,13);

            var result = this.Hierarchy.GetCommonElements(otherHierarchy).ToArray();

            CollectionAssert.AreEquivalent(result, new [] {13}, "GetCommonElements returned an incorrect collection!");
        }
        public MemToParent(string name, Hierarchy HostHier, Member Measure , Hierarchy MemHierarchy)
            : base(name, HostHier)
        {
            if(HostHier.UniqueName!="[Measures]")
                throw new Exception("Cannot create on non-measures hierarchy");

            //DataMember measure=this.Hierarchy.AddDataMember(Measure);
            this.MdxParameters.Add(Measure, true);
            this.MdxParameters.Add(MemHierarchy, false);
            Initialize(name, true);
        }
        /// <summary>
        /// Valuates a company using the discounted cashflow method,
        /// aggregating the linguistic information provided using the LAMA operator.
        /// </summary>
        /// <param name="cashflows">The cashflows.</param>
        /// <param name="waccs">The waccs.</param>
        /// <param name="linguisticHierarchy">The linguistic hierarchy.</param>
        /// <returns>
        /// An interval containing the probable value of the company.
        /// </returns>
        public Interval CashflowWithLama(IList<Expertise> cashflows, IList<Expertise> waccs, Hierarchy linguisticHierarchy)
        {
            Contract.NotNull(cashflows, "cashflows");
            Contract.NotNull(waccs, "waccs");
            Contract.NotNull(linguisticHierarchy, "linguisticHierarchy");

            IList<Interval> adjustedCashflows = this.lamaExpertiseAdjuster.AdjustByLama(cashflows, linguisticHierarchy) ;
            IList<Interval> adjustedWaccs = this.lamaExpertiseAdjuster.AdjustByLama(waccs, linguisticHierarchy);
            var result = this.companyValuator.Cashflow(adjustedCashflows, adjustedWaccs);
            return result;
        }
        public MeasureInheritedNull(string name, Hierarchy HostHier, Member Measure1 , Member Measure2)
            : base(name, HostHier)
        {
            if(HostHier.UniqueName!="[Measures]")
                throw new Exception("Cannot create on non-measures hierarchy");

            _mdxParameters.Add(Measure1, false);

            if(Measure1.UniqueName!=Measure2.UniqueName)
                _mdxParameters.Add(Measure2, false); //add if not equal

            Initialize(name);
        }
        /// <summary>
        /// Aggregates the linguistic information privided in the expertise using the expertone method.
        /// </summary>
        /// <param name="expertise">The expertise.</param>
        /// <param name="hierarchy">The hierarchy for the labels in the expertise.</param>
        /// <param name="referenceLevel">The reference level where we shall standarize the expertise.</param>
        /// <returns>
        /// An adjusted interval aggregating the linguistic information provided in the expertise.
        /// </returns>
        Interval IExpertoneAggregator.AggregateByExpertone(Expertise expertise, Hierarchy hierarchy, int referenceLevel)
        {
            Contract.NotNull(expertise, "expertise");
            Contract.NotNull(hierarchy, "hierarchy");

            var standardExpertise = this.standardizer.Standardize(expertise, hierarchy, referenceLevel);
            TwoTupleCardinalities cardinalities = new TwoTupleCardinalities(standardExpertise);

            var expertone = new Expertone<TwoTuple>(cardinalities);
            var expectedValue = expertone.GetExpectedValue();
            var expectedInterval = expertone.Interval.LowerBound + ((expertone.Interval.Width) * expectedValue);
            return expectedInterval;
        }
        Hierarchy IHierarchyManager.GetCurrentHierarchy()
        {
            if (this.currentHierarchy == null)
            {
                this.currentHierarchy = new Hierarchy();

                this.currentHierarchy.Add(this.GetLabelSet5());
                this.currentHierarchy.Add(this.GetLabelSet7());
                this.currentHierarchy.Add(this.GetLabelSet9());
            }

            return this.currentHierarchy;
        }
        /// <summary>
        /// Standardizes the specified expertise.
        /// </summary>
        /// <param name="expertise">The expertise.</param>
        /// <param name="hierarchy"></param>
        /// <param name="level"></param>
        /// <returns>A standarized expertise.</returns>
        Expertise IExpertiseStandardizer.Standardize(Expertise expertise, Hierarchy hierarchy, int level)
        {
            Contract.NotNull(expertise, "expertise");
            Contract.NotNull(hierarchy, "hierarchy");

            var result = new Expertise(expertise.Interval);
            foreach (var item in expertise.Opinions)
            {
                var lowerTuple = hierarchy.Translate(item.LowerOpinion, level);
                var upperTuple = hierarchy.Translate(item.UpperOpinion, level);
                result.Opinions.Add(new Opinion(lowerTuple, upperTuple));
            }
            return result;
        }
 private static HierarchyNode EnsureIsPartOfHierarchy(Unit target, Hierarchy hierarchy, ChangeSetBuilder pendingChanges)
 {
     var hierarchyNode = target.Nodes.SingleOrDefault(x => x.Context.Id == hierarchy.Id);
     if (hierarchyNode == null)
     {
         var nodeId = ObjectId.NewUniqueId();
         return pendingChanges
             .Add(new AttachToHierarchyCommand(target.Id, nodeId))
             .Add(new CreateHierarchyNodeCommand(nodeId, target.Id, hierarchy.Id))
             .GetPreview()
             .GetById<HierarchyNode>(nodeId);
     }
     return hierarchyNode;
 }
        public MemToVisAggr(string name, Hierarchy HostHier, Member Measure , Hierarchy VisAggrHierarchy, VisualAggregate.AggregateFunction AggregateFunction)
            : base(name, HostHier)
        {
            if(HostHier.UniqueName!="[Measures]")
                throw new Exception("Cannot create on non-measures hierarchy");

            //DataMember measure=this.Hierarchy.AddDataMember(Measure);
            VisualAggregate vAggr=new VisualAggregate(null, VisAggrHierarchy, AggregateFunction);
            //vAggr=(VisualAggregate)VisAggrHierarchy.AddDataMember(vAggr);

            _mdxParameters.Add(Measure, false);
            _mdxParameters.Add(vAggr, false);
            Initialize(name, true);
        }
Example #26
0
        public void GeoNames_Hierarchy_ShouldBePublic()
        {
            var model = new Hierarchy
            {
                ItemsList = new List<Toponym>
                {
                    new Toponym(), new Toponym(),
                },
            };

            model.ShouldNotBeNull();
            model.ItemsList.ShouldNotBeNull();
            model.ItemsList.Count.ShouldEqual(2);
        }
Example #27
0
        /// <summary>
        ///   Adds a screen to the manager.
        /// </summary>
        /// <param name="parent">The screen that owns the screen to add.</param>
        /// <param name="child">The screen to add.</param>
        public static void AddScreen(Screen parent, Screen child)
        {
            var childNode = new Hierarchy<Screen>(child);
            var parentNode = screens.Search(parent);

            if (parentNode != null)
            {
                parentNode.Add(childNode);
            }
            else
            {
                throw new ArgumentException("ScreenManager.AddScreen(Screen, Screen): Could not find the screen's parent node.");
            }
        }
 IList<Interval> IExpertoneExpertiseAdjuster.AdjustByExpertones(IList<Expertise> data, Hierarchy hierarchy)
 {
     var referenceLevel = hierarchy.LastOrDefault();
     if (referenceLevel == null)
     {
         throw new AggregateException("Hierarchy does not contains linguistic levels");
     }
     var adjustedData = new List<Interval>();
     foreach (var item in data)
     {
         var adjustedInterval = this.expertoneAggregator.AggregateByExpertone(item, hierarchy, referenceLevel.Count);
         adjustedData.Add(adjustedInterval);
     }
     return adjustedData;
 }
        public void SimpleHierarchySerializer_Test()
        {
            var testData = new Hierarchy<CodeNode>(new CodeNode("Node1", 0, 100, "Comment1"))
            {
                Children = new List<Hierarchy<CodeNode>>
                {
                    new Hierarchy<CodeNode>(new CodeNode("S1", 1, 2)),
                    new Hierarchy<CodeNode>(new CodeNode("S2", 2, 3))
                }
            };

            var serialized = SimpleHierarchySerializer.Serialize(testData);
            var deserialised = SimpleHierarchySerializer.Deserialize<CodeNode>(serialized);
            var isEqual = HierarchyComparer.Compare(testData, deserialised, CodeNode.GetDefaultComparer());
            Assert.IsTrue(isEqual);
        }
        public void GetCommonElements_WithHierarchyWithMultipleCommonElements_ShouldReturnACorrectCollection()
        {
            var otherHierarchy = new Hierarchy<int>(10);
            otherHierarchy.Add(10, -22);
            otherHierarchy.Add(-22, 56);
            otherHierarchy.Add(10, 108);
            otherHierarchy.Add(-22, 34);
            this.Hierarchy.Add(DefaultRootValue, 100);
            this.Hierarchy.Add(DefaultRootValue, -22);
            this.Hierarchy.Add(100, 34);
            this.Hierarchy.Add(100, 10);

            var result = this.Hierarchy.GetCommonElements(otherHierarchy).ToArray();

            CollectionAssert.AreEquivalent(result, new[] { -22,34,10 }, "GetCommonElements returned an incorrect collection!");
        }
Example #31
0
        /// <summary>
        /// Inserts hierarchies
        /// </summary>
        /// <param name="pathToHierarchiesFile"></param>
        private static void InsertHierarchies(string pathToHierarchiesFile)
        {
            Console.WriteLine("Inserting Hierarchies");
            string[] allLines = File.ReadAllLines(pathToHierarchiesFile)
                                .Skip(1) //Skipping the first line cause it's documentation
                                .ToArray();

            int lineCount = 1;

            foreach (string line in allLines)
            {
                Console.WriteLine("Inserting line number: " + lineCount);

                //File format: TagsetName:HierarchyName:ParrentTag:ChildTag:ChildTag:ChildTag:(...)
                string[] split         = line.Split(":");
                string   tagsetName    = split[0];
                string   hierarchyName = split[1];
                string   parentTagName = split[2];

                using (var context = new ObjectContext())
                {
                    //Finding tagset:
                    Tagset tagsetFromDb = context.Tagsets
                                          .Where(ts => ts.Name.Equals(tagsetName))
                                          .Include(ts => ts.Tags)
                                          .Include(ts => ts.Hierarchies)
                                          .FirstOrDefault();

                    //See if hierarchy exists:
                    Hierarchy hierarchyFromDb = context.Hierarchies
                                                .Include(h => h.Nodes)
                                                .Where(h => h.Name.Equals(hierarchyName))
                                                .FirstOrDefault();

                    //If hierarchyFromDb does not exist, create it:
                    if (hierarchyFromDb == null)
                    {
                        hierarchyFromDb = DomainClassFactory.NewHierarchy(tagsetFromDb);
                        tagsetFromDb.Hierarchies.Add(hierarchyFromDb);
                        //hierarchyFromDb.Tagset = tagsetFromDb;
                        context.Update(tagsetFromDb);
                        context.Update(hierarchyFromDb);
                        context.SaveChanges();
                    }

                    //Finding parent tag:
                    Tag parentTagFromDb = context.Tags
                                          .Where(t => t.TagsetId == tagsetFromDb.Id && t.Name.Equals(parentTagName))
                                          .FirstOrDefault();

                    //If parentTag does not exist, create it:
                    if (parentTagFromDb == null)
                    {
                        parentTagFromDb = DomainClassFactory.NewTag(parentTagName, tagsetFromDb);
                        tagsetFromDb.Tags.Add(parentTagFromDb);
                        context.Tags.Add(parentTagFromDb);
                        context.Update(tagsetFromDb);
                        context.SaveChanges();
                    }

                    //Finding parent node:
                    Node parentNodeFromDb = context.Nodes
                                            .Include(n => n.Children)
                                            .Where(n => n.HierarchyId == hierarchyFromDb.Id && n.TagId == parentTagFromDb.Id)
                                            .FirstOrDefault();

                    //If parent node does not exist, create it:
                    if (parentNodeFromDb == null)
                    {
                        //Probably root node:
                        parentNodeFromDb = DomainClassFactory.NewNode(parentTagFromDb, hierarchyFromDb);
                        hierarchyFromDb.Nodes.Add(parentNodeFromDb);
                        context.Update(hierarchyFromDb);
                        context.SaveChanges();

                        hierarchyFromDb.RootNodeId = parentNodeFromDb.Id;
                        context.Update(hierarchyFromDb);
                        context.SaveChanges();
                    }

                    //Adding child nodes:
                    for (int i = 3; i < split.Length; i++)
                    {
                        string childTagName = split[i];

                        Tag childTagFromDb = context.Tags
                                             .Where(t => t.TagsetId == tagsetFromDb.Id && t.Name.Equals(childTagName))
                                             .FirstOrDefault();

                        //If child tag does not exist, create it:
                        if (childTagFromDb == null)
                        {
                            childTagFromDb        = DomainClassFactory.NewTag(childTagName, tagsetFromDb);
                            childTagFromDb.Tagset = tagsetFromDb;
                            tagsetFromDb.Tags.Add(childTagFromDb);
                            context.Update(tagsetFromDb);
                            context.SaveChanges();
                        }

                        Node newChildNode = DomainClassFactory.NewNode(childTagFromDb, hierarchyFromDb);
                        parentNodeFromDb.Children.Add(newChildNode);
                        hierarchyFromDb.Nodes.Add(newChildNode);
                        context.Update(parentNodeFromDb);
                        context.Update(hierarchyFromDb);
                        context.SaveChanges();
                    }
                }
                lineCount++;
            }
        }
Example #32
0
 public HierarchyManager(Hierarchy hierarchy)
 {
     Hierarchy = hierarchy;
 }
 public bool Equals(Hierarchy other)
 {
     return(other == this);
 }
        public void LoadHtmlTable()
        {
            System.Web.UI.HtmlControls.HtmlTable tblPivot = new System.Web.UI.HtmlControls.HtmlTable();
            tblPivot.CellPadding = 0;
            tblPivot.CellSpacing = 0;
            tblPivot.Width       = "100%";
            tblPivot.Height      = "100%";
            tblPivot.Attributes.Add("class", "tbl1_T");
            pnlPivot.Controls.Add(tblPivot);

            if (_report == null || _report.Cellset.IsValid == false)
            {
                return;
            }

            int Ax0MemCount = _report.Cellset.Axis0TupleMemCount;
            int Ax1MemCount = _report.Cellset.Axis1TupleMemCount;
            int Ax0PosCount = _report.Cellset.Axis0PosCount;
            int Ax1PosCount = _report.Cellset.Axis1PosCount;

            int ax0OrderPos = _report.GetOrderPosition(_report.Axes[0]);
            int ax1OrderPos = _report.GetOrderPosition(_report.Axes[1]);

            Hierarchy ax1Hier = null;
            Hierarchy ax0Hier = null;

            //table
            System.Web.UI.HtmlControls.HtmlTableRow  tr = null;
            System.Web.UI.HtmlControls.HtmlTableCell td = null;

            if (Ax0PosCount == 0 && Ax1PosCount == 0)
            {
                tr = new HtmlTableRow();
                tblPivot.Rows.Add(tr);
                td = new HtmlTableCell();
                tr.Cells.Add(td);
                td.Attributes.Add("class", "tbl1_err");
                td.Attributes.Add("nowrap", "true");
                td.InnerText = "Query successfully executed, cellset contains no data";
                return;
            }


            for (int i = 0; i < Ax0MemCount; i++)
            {
                tr = new System.Web.UI.HtmlControls.HtmlTableRow();
                tblPivot.Rows.Add(tr);

                for (int j = 0; j < Ax1MemCount; j++)
                {
                    td = new System.Web.UI.HtmlControls.HtmlTableCell();
                    td.Attributes.Add("class", "tbl1_HC");
                    td.NoWrap = true;
                    tr.Cells.Add(td);

                    //hier controls in last row
                    if (i == Ax0MemCount - 1)
                    {
                        this.CreateHierControls(_report.Axes[1].Hierarchies[j], td);
                    }
                }

                ax0Hier = _report.Axes[0].Hierarchies[i];
                for (int j = 0; j < Ax0PosCount; j++)
                {
                    CellsetMember mem          = _report.Cellset.GetCellsetMember(0, i, j);
                    bool          inOrderTuple = false;

                    //if same as prev, continue
                    if (j != 0 && _report.Cellset.GetCellsetMember(0, i, j - 1).UniqueName == mem.UniqueName)
                    {
                        continue;
                    }

                    td        = new System.Web.UI.HtmlControls.HtmlTableCell();
                    td.NoWrap = true;

                    // handle order position highlight
                    if (j == ax0OrderPos)                  // in order tuple
                    {
                        inOrderTuple = true;
                    }


                    // handle colspan
                    int spanCount = 1;
                    for (int n = j + 1; n < Ax0PosCount; n++)
                    {
                        CellsetMember nextMem = _report.Cellset.GetCellsetMember(0, i, n);
                        if (nextMem.UniqueName == mem.UniqueName)
                        {
                            spanCount++;

                            // handle order position highlight
                            if (n == ax0OrderPos)
                            {
                                inOrderTuple = true;
                            }
                        }
                        else
                        {
                            break;
                        }
                    }

                    // handle order position highlight
                    if (inOrderTuple)                    // in order tuple
                    {
                        td.Attributes.Add("class", "tbl1_H3");
                    }
                    else
                    {
                        td.Attributes.Add("class", "tbl1_H2");
                    }

                    // if we span
                    if (spanCount > 1)
                    {
                        td.ColSpan = spanCount;
                    }


                    if (mem.ChildCount == 0)
                    {                     // leaf-level
                        System.Web.UI.HtmlControls.HtmlImage img = new System.Web.UI.HtmlControls.HtmlImage();
                        img.Src = "../images/leaf.gif";
                        td.Controls.Add(img);
                    }

                    System.Web.UI.HtmlControls.HtmlInputCheckBox chb = new System.Web.UI.HtmlControls.HtmlInputCheckBox();
                    chb.ID = "m:" + _contr.IdentifierFromCellsetPosition(0, j, i);
                    chb.EnableViewState = false;
                    td.EnableViewState  = false;
                    td.Controls.Add(chb);

                    System.Web.UI.LiteralControl literal = new System.Web.UI.LiteralControl(mem.Name);
                    td.Controls.Add(literal);

                    tr.Cells.Add(td);
                }


                // hier controls in last col
                td = new System.Web.UI.HtmlControls.HtmlTableCell();
                td.Attributes.Add("class", "tbl1_HC");
                td.NoWrap = true;
                CreateHierControls(ax0Hier, td);
                tr.Cells.Add(td);
            }



            for (int i = 0; i < Ax1PosCount; i++)
            {
                tr = new System.Web.UI.HtmlControls.HtmlTableRow();
                tblPivot.Rows.Add(tr);

                for (int j = 0; j < Ax1MemCount; j++)
                {
                    ax1Hier = _report.Axes[1].Hierarchies[j];
                    CellsetMember mem          = _report.Cellset.GetCellsetMember(1, j, i);
                    bool          inOrderTuple = false;

                    //if same as prev, continue
                    if (i != 0 && _report.Cellset.GetCellsetMember(1, j, i - 1).UniqueName == mem.UniqueName)
                    {
                        continue;
                    }

                    td        = new System.Web.UI.HtmlControls.HtmlTableCell();
                    td.NoWrap = true;

                    // handle order position highlight
                    if (i == ax1OrderPos)                  // in order tuple
                    {
                        inOrderTuple = true;
                    }


                    // handle rowspan
                    int spanCount = 1;
                    for (int n = i + 1; n < Ax1PosCount; n++)
                    {
                        CellsetMember nextMem = _report.Cellset.GetCellsetMember(1, j, n);
                        if (nextMem.UniqueName == mem.UniqueName)
                        {
                            spanCount++;

                            // handle order position highlight
                            if (n == ax1OrderPos)
                            {
                                inOrderTuple = true;
                            }
                        }
                        else
                        {
                            break;
                        }
                    }

                    // handle order position highlight
                    if (inOrderTuple)                    // in order tuple
                    {
                        td.Attributes.Add("class", "tbl1_H1");
                    }
                    else
                    {
                        td.Attributes.Add("class", "tbl1_H");
                    }

                    // if we span
                    if (spanCount > 1)
                    {
                        td.RowSpan = spanCount;
                    }



                    if (mem.ChildCount == 0)
                    {                     // leaf-level
                        System.Web.UI.HtmlControls.HtmlImage img = new System.Web.UI.HtmlControls.HtmlImage();
                        img.Src = "../images/leaf.gif";
                        td.Controls.Add(img);
                    }

                    System.Web.UI.HtmlControls.HtmlInputCheckBox chb = new System.Web.UI.HtmlControls.HtmlInputCheckBox();
                    chb.ID = "m:" + _contr.IdentifierFromCellsetPosition(1, i, j);
                    chb.EnableViewState = false;
                    td.EnableViewState  = false;
                    td.Controls.Add(chb);

                    System.Web.UI.LiteralControl literal = new System.Web.UI.LiteralControl(mem.Name);
                    td.Controls.Add(literal);


                    tr.Cells.Add(td);
                }

                for (int j = 0; j < Ax0PosCount; j++)
                {
                    td = new System.Web.UI.HtmlControls.HtmlTableCell();
                    td.Attributes.Add("class", "tbl1_C");
                    td.NoWrap = true;
                    Cell olapCell = _report.Cellset.GetCell(j, i);
                    td.InnerText = olapCell.FormattedValue;
                    tr.Cells.Add(td);
                }
            }
        }
Example #35
0
        static void Main(string[] args)
        {
            int numSimSteps = 500;

            ComputeSystem.DeviceType deviceType = ComputeSystem.DeviceType._gpu;

            Resources _res = new Resources();

            _res.create(deviceType);

            Architect arch = new Architect();

            arch.initialize(1234, _res);

            // Input size (width and height)
            int w = 4;
            int h = 4;

            ParameterModifier inputParams = arch.addInputLayer(new Vec2i(w, h));

            inputParams.setValue("in_p_alpha", 0.02f);
            inputParams.setValue("in_p_radius", 16);

            for (int i = 0; i < 2; i++)
            {
                ParameterModifier layerParams = arch.addHigherLayer(new Vec2i(36, 36), SparseFeaturesType._chunk);
                layerParams.setValue("sfc_chunkSize", new Vec2i(6, 6));
                layerParams.setValue("sfc_ff_radius", 12);
                layerParams.setValue("hl_poolSteps", 2);
                layerParams.setValue("sfc_weightAlpha", 0.02f);
                layerParams.setValue("sfc_biasAlpha", 0.001f);
                layerParams.setValue("p_alpha", 0.08f);
                layerParams.setValue("p_beta", 0.16f);
                layerParams.setValue("p_radius", 16);
            }

            Hierarchy hierarchy = arch.generateHierarchy();

            ValueField2D inputField = new ValueField2D(new Vec2i(w, h));

            for (int y = 0; y < h; y++)
            {
                for (int x = 0; x < w; x++)
                {
                    inputField.setValue(new Vec2i(x, y), (y * w) + x);
                }
            }

            vectorvf inputVector = new vectorvf();

            inputVector.Add(inputField);

            System.Console.WriteLine("Stepping the hierarchy...");
            for (int i = 0; i < numSimSteps; i++)
            {
                hierarchy.simStep(inputVector, true);
            }

            vectorvf prediction = hierarchy.getPredictions();

            System.Console.Write("Input      :");
            for (int y = 0; y < h; y++)
            {
                for (int x = 0; x < w; x++)
                {
                    System.Console.Write(" " + inputField.getValue(new Vec2i(x, y)).ToString("n2"));
                }
            }
            System.Console.WriteLine();

            System.Console.Write("Prediction :");
            for (int y = 0; y < h; y++)
            {
                for (int x = 0; x < w; x++)
                {
                    System.Console.Write(" " + prediction[0].getValue(new Vec2i(x, y)).ToString("n2"));
                }
            }
            System.Console.WriteLine();
        }
Example #36
0
 public MeasureWrapper(string Name, Hierarchy HostHier, Member SourceMember) : base(Name, HostHier, SourceMember)
 {
 }
 private ICommand CreateCommand(IExcelSpreadsheet spreadsheet, Hierarchy hierarchy)
 {
     return(new HierarchyReaderCommand(spreadsheet, hierarchy));
 }
Example #38
0
        protected override void Awake()
        {
            base.Awake();

            CachedTransform.SetParent(Hierarchy.Get("SRDebugger"));
        }
Example #39
0
        /// <summary>
        /// Converts the XML hierarchy of an <see cref="XmlReader"/> into an <see cref="IHierarchy{T}"/>.
        /// </summary>
        /// <param name="reader">The reader to convert.</param>
        /// <returns>An <see cref="IHierarchy{T}"/> implementation that uses <see cref="DataPair"/>.</returns>
        public static IHierarchy <DataPair> ToHierarchy(this XmlReader reader)
        {
            var index        = 0;
            var depthIndexes = new Dictionary <int, Dictionary <int, int> >();
            var dimension    = 0;
            IHierarchy <DataPair> hierarchy  = new Hierarchy <DataPair>();
            List <DataPair>       attributes = null;

            while (reader.Read())
            {
                object typeStrongValue;
                switch (reader.NodeType)
                {
                case XmlNodeType.Attribute:
                    typeStrongValue = ObjectConverter.FromString(reader.Value);
                    attributes.Add(new DataPair(reader.Name, typeStrongValue, typeStrongValue.GetType()));
                    while (reader.MoveToNextAttribute())
                    {
                        goto case XmlNodeType.Attribute;
                    }
                    var elementIndex = index;
                    foreach (var attribute in attributes)
                    {
                        hierarchy[index].Add(attribute).Data.Add("parent", elementIndex);
                        index++;
                    }
                    reader.MoveToElement();
                    break;

                case XmlNodeType.Element:
                    attributes = new List <DataPair>();
                    if (reader.Depth == 0)
                    {
                        hierarchy.Add(new DataPair(reader.Name, null, typeof(string))).Data.Add(XmlReaderKey, reader.Name);
                        continue;
                    }

                    hierarchy[depthIndexes.GetDepthIndex(reader, index, dimension)].Add(new DataPair(reader.Name, null, typeof(string))).Data.Add(XmlReaderKey, reader.Name);
                    index++;

                    if (reader.HasAttributes)
                    {
                        if (reader.MoveToFirstAttribute())
                        {
                            goto case XmlNodeType.Attribute;
                        }
                    }
                    break;

                case XmlNodeType.EndElement:
                    if (reader.Depth == 1)
                    {
                        dimension++;
                    }
                    break;

                case XmlNodeType.CDATA:
                case XmlNodeType.Text:
                    var indexToApplyText = hierarchy[index].Data.ContainsKey(XmlReaderKey) ? index : hierarchy[index].Data["parent"].As <int>();
                    typeStrongValue = ObjectConverter.FromString(reader.Value);
                    hierarchy[indexToApplyText].Replace(new DataPair(hierarchy[indexToApplyText].Data[XmlReaderKey]?.ToString(), typeStrongValue, typeStrongValue.GetType()));
                    hierarchy[indexToApplyText].Data.Remove(XmlReaderKey);
                    break;
                }
            }
            return(hierarchy);
        }
        private void CreateHierControls(Hierarchy hier, HtmlTableCell td)
        {
            Button btn;

            Literal lit = new Literal();

            lit.Text = hier.DisplayName;
            td.Controls.Add(lit);

            // visual avg button
            btn = new Button();
            if (HasAggragate(hier, VisualAggregate.AggregateFunction.AVG))
            {
                btn.ToolTip  = "Remove Avg";
                btn.ID       = "tbl_avg:off:" + hier.UniqueName;
                btn.CssClass = "tbl_avg_on";
            }
            else
            {
                btn.ToolTip  = "Add Avg";
                btn.ID       = "tbl_avg:on:" + hier.UniqueName;
                btn.CssClass = "tbl_avg_off";
            }
            td.Controls.Add(btn);

            // visual sum button
            btn = new Button();
            if (HasAggragate(hier, VisualAggregate.AggregateFunction.SUM))
            {
                btn.ToolTip  = "Remove Sum";
                btn.ID       = "tbl_sum:off:" + hier.UniqueName;
                btn.CssClass = "tbl_sum_on";
            }
            else
            {
                btn.ToolTip  = "Add Sum";
                btn.ID       = "tbl_sum:on:" + hier.UniqueName;
                btn.CssClass = "tbl_sum_off";
            }
            td.Controls.Add(btn);

            // visual min button
            btn = new Button();
            if (HasAggragate(hier, VisualAggregate.AggregateFunction.MIN))
            {
                btn.ToolTip  = "Remove Min";
                btn.ID       = "tbl_min:off:" + hier.UniqueName;
                btn.CssClass = "tbl_min_on";
            }
            else
            {
                btn.ToolTip  = "Add Min";
                btn.ID       = "tbl_min:on:" + hier.UniqueName;
                btn.CssClass = "tbl_min_off";
            }
            td.Controls.Add(btn);

            // visual avg button
            btn = new Button();
            if (HasAggragate(hier, VisualAggregate.AggregateFunction.MAX))
            {
                btn.ToolTip  = "Remove Max";
                btn.ID       = "tbl_max:off:" + hier.UniqueName;
                btn.CssClass = "tbl_max_on";
            }
            else
            {
                btn.ToolTip  = "Add Max";
                btn.ID       = "tbl_max:on:" + hier.UniqueName;
                btn.CssClass = "tbl_max_off";
            }
            td.Controls.Add(btn);
        }
Example #41
0
 public MembersAggregate(Hierarchy hier, System.Xml.XmlElement xmlEl) : base(null, hier)
 {
     LoadFromXml(xmlEl);
 }
Example #42
0
 protected override Box GetBoundingBox()
 {
     return(Hierarchy.NumChildren > 0 ? new Box(Hierarchy.Select(x => x.BoundingBox)) : Box.Empty);
 }
Example #43
0
        private void GetSymmetricCryptoProviderDataCollection()
        {
            SymmetricCryptoProviderCollectionNode symmetricCryptoProviderCollectionNode = Hierarchy.FindNodeByType(typeof(SymmetricCryptoProviderCollectionNode)) as SymmetricCryptoProviderCollectionNode;

            if (symmetricCryptoProviderCollectionNode == null)
            {
                return;
            }
            if (Object.ReferenceEquals(cryptographySettings.SymmetricCryptoProviders, symmetricCryptoProviderCollectionNode.SymmetricCryptoProviderDataCollection))
            {
                return;
            }

            cryptographySettings.SymmetricCryptoProviders.Clear();
            foreach (SymmetricAlgorithmProviderData symmetricAlgorithmProviderData in symmetricCryptoProviderCollectionNode.SymmetricCryptoProviderDataCollection)
            {
                cryptographySettings.SymmetricCryptoProviders[symmetricAlgorithmProviderData.Name] = symmetricAlgorithmProviderData;
            }
        }
Example #44
0
        internal void SetHideMemberIf(Microsoft.AnalysisServices.BackEnd.DataModelingSandbox sandboxParam, IEnumerable <Tuple <string, string, string> > hierarchyLevels, List <HideIfValue> newValues)
        {
            try
            {
#if DENALI || SQL2014
                Microsoft.AnalysisServices.BackEnd.DataModelingSandbox.AMOCode code;
                var sandbox = sandboxParam;
#else
                Microsoft.AnalysisServices.BackEnd.AMOCode code;
                var sandbox = (Microsoft.AnalysisServices.BackEnd.DataModelingSandboxAmo)sandboxParam.Impl;
#endif
                code = delegate
                {
                    Microsoft.AnalysisServices.BackEnd.SandboxTransactionProperties properties = new Microsoft.AnalysisServices.BackEnd.SandboxTransactionProperties();
                    properties.RecalcBehavior = Microsoft.AnalysisServices.BackEnd.TransactionRecalcBehavior.AlwaysRecalc;
                    List <Dimension> dims = new List <Dimension>();
                    using (Microsoft.AnalysisServices.BackEnd.SandboxTransaction tran = sandboxParam.CreateTransaction(properties))
                    {
                        if (!TabularHelpers.EnsureDataSourceCredentials(sandboxParam))
                        {
                            MessageBox.Show("Cancelling apply of HideMemberIf because data source credentials were not entered.", "BIDS Helper Tabular HideMemberIf - Cancelled!");
                            tran.RollbackAndContinue();
                            return;
                        }

                        SSAS.TabularHideMemberIfAnnotation annotation = GetAnnotation(sandboxParam);

                        foreach (Tuple <string, string, string> tuple in hierarchyLevels)
                        {
                            Dimension d = sandbox.Database.Dimensions.GetByName(tuple.Item1);
                            if (!dims.Contains(d))
                            {
                                dims.Add(d);
                            }
                            Hierarchy h = d.Hierarchies.GetByName(tuple.Item2);
                            Level     l = h.Levels.GetByName(tuple.Item3);
                            l.HideMemberIf = newValues[0];
                            newValues.RemoveAt(0);

                            annotation.Set(l);
                        }

                        TabularHelpers.SaveXmlAnnotation(sandbox.Database, HIDEMEMBERIF_ANNOTATION, annotation);

                        sandbox.Database.Update(UpdateOptions.ExpandFull);

                        //bug in AS2012 (still not working in RTM CU1) requires ProcessFull to successfully switch from HideMemberIf=Never to NoName
                        foreach (Dimension d in dims)
                        {
                            d.Process(ProcessType.ProcessFull);
                        }

                        tran.GetType().InvokeMember("Commit", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.Public, null, tran, null);     //The .Commit() function used to return a list of strings, but in the latest set of code it is a void method which leads to "method not found" errors
                        //tran.Commit();
                    }
                };
#if DENALI || SQL2014
                sandbox.ExecuteAMOCode(Microsoft.AnalysisServices.BackEnd.DataModelingSandbox.OperationType.Update, Microsoft.AnalysisServices.BackEnd.DataModelingSandbox.OperationCancellability.AlwaysExecute, code, true);
#else
                sandboxParam.ExecuteEngineCode(Microsoft.AnalysisServices.BackEnd.DataModelingSandbox.OperationType.Update, Microsoft.AnalysisServices.BackEnd.DataModelingSandbox.OperationCancellability.AlwaysExecute, code, true);
#endif
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace, "BIDS Helper - Error");
            }
        }
 public void SetUp()
 {
     runner    = TestRunnerBuilder.For(x => x.AddFixturesFromAssemblyContaining <GrammarMarker>());
     hierarchy = DataMother.GrammarProject().LoadTests();
 }
Example #46
0
 internal static global::System.Runtime.InteropServices.HandleRef getCPtr(Hierarchy obj)
 {
     return((obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr);
 }
Example #47
0
 public MeasureWrapper(Hierarchy HostHier, System.Xml.XmlElement xmlEl) : base(HostHier, xmlEl)
 {
 }
        public void PerformanceRemove_With20000RemovalsIn4GroupsInReverseOrderFromTheMiddleWith40000Elements()
        {
            var counter1  = 10000;
            var counter2  = 20000;
            var counter3  = 30000;
            var counter4  = 40000;
            var hierarchy = new Hierarchy <int>(-2);

            hierarchy.Add(-2, 10000);
            hierarchy.Add(-2, 20000);
            hierarchy.Add(-2, 30000);
            hierarchy.Add(-2, 40000);
            for (int i = 1; i < 10000; i++)
            {
                hierarchy.Add(counter1, --counter1);
                hierarchy.Add(counter2, --counter2);
                hierarchy.Add(counter3, --counter3);
                hierarchy.Add(counter4, --counter4);
            }

            var count = 40001;

            counter1 = 9000;
            counter2 = 18000;
            counter3 = 27000;
            counter4 = 36000;
            Stopwatch timer = new Stopwatch();

            timer.Start();
            for (int i = 1; i < 5001; i++)
            {
                hierarchy.Remove(counter1--);
                hierarchy.Remove(counter2--);
                hierarchy.Remove(counter3--);
                hierarchy.Remove(counter4--);
                count -= 4;
                Assert.AreEqual(count, hierarchy.Count, "Count did not decrease correctly!");
            }

            timer.Stop();
            Assert.IsTrue(timer.ElapsedMilliseconds < 200);

            Assert.AreEqual(20001, hierarchy.Count, "Incorrect count after removal!");
            counter1 = 9000;
            counter2 = 18000;
            counter3 = 27000;
            counter4 = 36000;
            for (int i = 0; i < 5000; i++)
            {
                Assert.IsFalse(hierarchy.Contains(counter1--));
                Assert.IsFalse(hierarchy.Contains(counter2--));
                Assert.IsFalse(hierarchy.Contains(counter3--));
                Assert.IsFalse(hierarchy.Contains(counter4--));
            }

            Assert.IsTrue(hierarchy.Contains(-2));
            CollectionAssert.AreEqual(new[] { 4000 }, hierarchy.GetChildren(9001).ToArray(), "Children were not correctly reattached!");
            CollectionAssert.AreEqual(new[] { 13000 }, hierarchy.GetChildren(18001).ToArray(), "Children were not correctly reattached!");
            CollectionAssert.AreEqual(new[] { 22000 }, hierarchy.GetChildren(27001).ToArray(), "Children were not correctly reattached!");
            CollectionAssert.AreEqual(new[] { 31000 }, hierarchy.GetChildren(36001).ToArray(), "Children were not correctly reattached!");
        }
        //public HierarchyItem SelectTransform( Transform target, Transform nextInPath = null )
        //{
        //	bool wasExpanded = IsExpanded;
        //	if( !wasExpanded )
        //		IsExpanded = true;
        //	else
        //		Refresh();

        //	if( nextInPath == null )
        //		nextInPath = target.root;

        //	HierarchyItem result = null;
        //	for( int i = 0; i < children.Count; i++ )
        //	{
        //		if( children[i].BoundTransform == target )
        //		{
        //			Hierarchy.OnClicked( children[i] );
        //			result = children[i];

        //			break;
        //		}
        //		else if( children[i].BoundTransform == nextInPath )
        //		{
        //			Transform next = target;
        //			Transform parent = next.parent;
        //			while( parent != null && parent != nextInPath )
        //			{
        //				next = parent;
        //				parent = next.parent;
        //			}

        //			if( parent != null )
        //				result = children[i].SelectTransform( target, next );

        //			break;
        //		}
        //	}

        //	if( result == null && !wasExpanded )
        //		IsExpanded = false;

        //	return result;
        //}

        public HierarchyItem SelectTransform(Transform target, Transform nextInPath = null)
        {
            bool isInitSearch = nextInPath == null;

            if (isInitSearch)
            {
                nextInPath = target.root;
            }

            RefreshContent();

            int childIndex = IndexOf(nextInPath);

            if (childIndex < 0)
            {
                if (isInitSearch && this is HierarchyItemRoot && ((HierarchyItemRoot)this).Content is HierarchyRootPseudoScene)
                {
                    nextInPath = target;
                    childIndex = IndexOf(nextInPath);
                    while (childIndex < 0 && nextInPath != null)
                    {
                        nextInPath = nextInPath.parent;
                        childIndex = IndexOf(nextInPath);
                    }

                    if (childIndex < 0)
                    {
                        return(null);
                    }
                }
                else
                {
                    return(null);
                }
            }

            bool wasExpanded = IsExpanded;

            if (!wasExpanded)
            {
                IsExpanded = true;
            }

            HierarchyItemTransform childItem = children[childIndex];

            if (childItem.BoundTransform == target)
            {
                Hierarchy.OnClicked(childItem);
                return(childItem);
            }

            HierarchyItem result = null;

            if (childItem.BoundTransform == nextInPath)
            {
                Transform next   = target;
                Transform parent = next.parent;
                while (parent != null && parent != nextInPath)
                {
                    next   = parent;
                    parent = next.parent;
                }

                if (parent != null)
                {
                    result = childItem.SelectTransform(target, next);

                    if (result.IsNull())
                    {
                        result = null;
                    }
                }
            }

            if (result.IsNull() && !wasExpanded)
            {
                IsExpanded = false;
            }

            return(result);
        }
Example #50
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            //Input
            List <Line>   lines = new List <Line>();
            List <string> crossectionsNameDirty = new List <string>();
            List <string> crossectionsName      = new List <string>();
            List <string> groupnamesDirty       = new List <string>();
            List <string> groupnames            = new List <string>();
            List <string> steelgrades           = new List <string>();

            GH_Structure <GH_Number> N  = new GH_Structure <GH_Number>();
            GH_Structure <GH_Number> My = new GH_Structure <GH_Number>();
            GH_Structure <GH_Number> Vz = new GH_Structure <GH_Number>();
            GH_Structure <GH_Number> Vy = new GH_Structure <GH_Number>();
            GH_Structure <GH_Number> Mt = new GH_Structure <GH_Number>();
            GH_Structure <GH_Number> Mz = new GH_Structure <GH_Number>();


            int           minThroatThickness = new int();
            List <string> hierarchy          = new List <string>();
            int           analysisMethod     = new int();

            analysisMethod = 4;

            double eccentricity = double.NaN;

            eccentricity = 0.0;

            List <Point3d> centerpoints      = new List <Point3d>();
            string         projectnameFromGH = null;
            string         templatelocation  = null;
            string         IDEAfilepath      = null;
            List <string>  shapesDirty       = new List <string>();
            List <string>  shapes            = new List <string>();

            List <double> height          = new List <double>();
            List <double> width           = new List <double>();
            List <double> thicknessFlange = new List <double>();
            List <double> thicknessWeb    = new List <double>();
            List <double> radius          = new List <double>();

            bool startIDEA          = false;
            bool calculateAllJoints = false;
            int  calculateThisJoint = 0;

            //Output

            List <Line> jointlines = new List <Line>();

            List <int>    numberOfSawingCuts   = new List <int>();
            int           TotalRightAngledCuts = new int();
            int           TotalSingleMiterCuts = new int();
            int           TotalDoubleMiterCuts = new int();
            double        totalWeldingVolume   = new double();
            List <double> weldVolumePerJoint   = new List <double>();
            List <string> plateYieldingJoint   = new List <string>();

            List <string> throatBegin = new List <string>();
            List <string> throatEnd   = new List <string>();

            List <string> plateBegin = new List <string>();
            List <string> plateEnd   = new List <string>();

            List <string> CSSnames = new List <string>();

            // grasshopperinput
            #region GrasshopperInput
            DA.GetData(0, ref templatelocation);
            DA.GetData(1, ref IDEAfilepath);


            if (!DA.GetDataList(2, hierarchy))
            {
                return;
            }
            ;
            DA.GetDataList(3, centerpoints);

            DA.GetDataList(4, lines);
            DA.GetDataList(5, groupnamesDirty);
            DA.GetDataList(6, steelgrades);

            DA.GetDataList(7, crossectionsNameDirty);
            DA.GetDataList(8, shapesDirty);
            DA.GetDataList(9, height);
            DA.GetDataList(10, width);
            DA.GetDataList(11, thicknessFlange);
            DA.GetDataList(12, thicknessWeb);
            DA.GetDataList(13, radius);


            DA.GetDataTree(14, out N);
            DA.GetDataTree(15, out Vz);
            DA.GetDataTree(16, out Vy);
            DA.GetDataTree(17, out Mt);
            DA.GetDataTree(18, out My);
            DA.GetDataTree(19, out Mz);



            DA.GetData(20, ref calculateThisJoint);
            DA.GetData(21, ref startIDEA);

            #endregion

            //Clean cross-section list from nextline ("\r\n") command produced by Karamba
            crossectionsName = ImportGrasshopperUtils.DeleteEnterCommandsInGHStrings(crossectionsNameDirty);

            //Clean groupnames list from nextline ("\r\n") command produced by Karamba
            groupnames = ImportGrasshopperUtils.DeleteEnterCommandsInGHStrings(groupnamesDirty);

            //Clean groupnames list from nextline ("\r\n") command produced by Karamba
            shapes = ImportGrasshopperUtils.DeleteEnterCommandsInGHStrings(shapesDirty);


            //CREATE PROJECT
            Project project = new Project(projectnameFromGH);

            //Load paths
            project.templatePath = templatelocation;
            project.filepath     = IDEAfilepath;

            //START IDEA BOOL
            project.startIDEA          = startIDEA;
            project.calculateAllJoints = calculateAllJoints;
            project.calculateThisJoint = calculateThisJoint;


            //CREATE HIERARCHY
            for (int i = 0; i < hierarchy.Count; i++)
            {
                Hierarchy w = new Hierarchy(i, hierarchy[i]);
                project.hierarchylist.Add(w);
            }

            //CREATE LIST OF ELEMENT OBJECTS
            for (int i = 0; i < crossectionsName.Count; i++)
            {
                MaterialSteel.SteelGrade steelGrade = (MaterialSteel.SteelGrade)Enum.Parse(typeof(MaterialSteel.SteelGrade), steelgrades[i]);
                MaterialSteel            material   = project.materials.FirstOrDefault(a => a.steelGrade == steelGrade);
                if (material == null)
                {
                    material = new MaterialSteel(project, steelGrade);
                }
                //CROSS SECTIONS
                CrossSection       crosssection = project.crossSections.FirstOrDefault(a => a.name == crossectionsName[i] && a.material == material);
                CrossSection.Shape shape        = new CrossSection.Shape();

                if (shapes[i].StartsWith("I"))
                {
                    shape = CrossSection.Shape.ISection;
                }
                else if (shapes[i].StartsWith("[]"))
                {
                    shape = CrossSection.Shape.HollowSection;
                }
                else
                {
                    shape = CrossSection.Shape.CHSsection;
                }
                if (crosssection == null)
                {
                    crosssection = new CrossSection(project, crossectionsName[i], shape, material, height[i], width[i], thicknessFlange[i], thicknessWeb[i], radius[i]);
                }

                //LINES
                PointRAZ start = PointRAZ.CreateNewOrExisting(project, lines[i].FromX, lines[i].FromY, lines[i].FromZ);
                PointRAZ end   = PointRAZ.CreateNewOrExisting(project, lines[i].ToX, lines[i].ToY, lines[i].ToZ);
                LineRAZ  line  = new LineRAZ(i, start, end);

                int       hierarchyId = -1;
                Hierarchy h           = project.hierarchylist.FirstOrDefault(a => groupnames[i].StartsWith(a.groupname));
                if (h != null)
                {
                    hierarchyId = h.numberInHierarchy;
                }
                ElementRAZ element = new ElementRAZ(project, i, line, crosssection, groupnames[i], hierarchyId);
            }

            //CREATE LIST OF LOADS
            //Here N,V,M are defined for the startpoint and endpoint of every line in the project.
            List <LoadsPerLineRAZ> loadsPerLineRAZs = new List <LoadsPerLineRAZ>();

            for (int i = 0; i < N.PathCount; i++)
            {
                LoadsRAZ        start = new LoadsRAZ(N[i][0].Value, Vz[i][0].Value, Vy[i][0].Value, Mt[i][0].Value, My[i][0].Value, Mz[i][0].Value);
                LoadsRAZ        end   = new LoadsRAZ(N[i][1].Value, Vz[i][1].Value, Vy[i][1].Value, Mt[i][1].Value, My[i][1].Value, Mz[i][1].Value);
                LoadsPerLineRAZ w     = new LoadsPerLineRAZ(start, end);
                loadsPerLineRAZs.Add(w);
            }

            //REARRANGE LIST OF LOADS TO SEPERATE LOADCASES
            //the project has x number of loadcases, here the list of loads created is rearranged to separate lists for every loadcase

            int loadcases = N.PathCount / lines.Count;
            int ib        = 0;
            for (int a = 0; a < loadcases; a++)
            {
                //LoadcasesRAZ loadcasesRAZ = new LoadcasesRAZ();
                //loadcase id start from 1 because of IDEA
                int                    loadCaseNumber = a + 1;
                LoadcaseRAZ            loadcase       = new LoadcaseRAZ(project, loadCaseNumber);
                List <LoadsPerLineRAZ> loadsPerline2s = new List <LoadsPerLineRAZ>();
                for (int b = 0; b < lines.Count; b++)
                {
                    //loadcasesRAZ w =
                    LoadsPerLineRAZ w = new LoadsPerLineRAZ(project.elementRAZs[b], loadcase, loadsPerLineRAZs[ib].startLoads, loadsPerLineRAZs[ib].endLoads);
                    ib++;
                    loadsPerline2s.Add(w);
                }
            }


            //Rhino.Point3D to PointRAZ
            List <PointRAZ> punten = new List <PointRAZ>();
            for (int i = 0; i < centerpoints.Count; i++)
            {
                PointRAZ pointRAZ = PointRAZ.CreateNewOrExisting(project, centerpoints[i].X, centerpoints[i].Y, centerpoints[i].Z);
                punten.Add(pointRAZ);
            }



            //CREATE LIST OF JOINTS
            double tol = 1e-6;
            project.CreateJoints(tol, eccentricity, punten, project.elementRAZs, project.hierarchylist);

            //Adjust out of bounds index calculateThisJoint
            project.calculateThisJoint = calculateThisJoint % project.joints.Count;

            //CALCULATE SAWING CUTS
            //store them in the element properties
            //Project.CalculateSawingCuts(project, tol);

            //SET ALL THROATS TO MIN-THROAT THICKNESS
            project.SetMinThroats(minThroatThickness);
            //SET WELDTYPE
            project.SetWeldType();



            //DEFINE ANALYSES METHODS
            if (analysisMethod == 0)
            {
                project.analysisMethod = Project.AnalysisMethod.MinSetWelds;
            }
            if (analysisMethod == 1)
            {
                project.analysisMethod = Project.AnalysisMethod.FullStrengthLazy;
            }
            if (analysisMethod == 2)
            {
                project.analysisMethod = Project.AnalysisMethod.FullStrengthMethod;
            }
            if (analysisMethod == 3)
            {
                project.analysisMethod = Project.AnalysisMethod.DirectionalMethod;
            }
            if (analysisMethod == 4)
            {
                project.analysisMethod = Project.AnalysisMethod.IdeaMethod;
            }



            //CALCULATE THROATS ACCORDING TO ANALYSIS METHOD
            //Send DATA to IDEA
            project.CalculateWeldsProject(project.filepath);

            //CALCULATE WELDVOLUME
            totalWeldingVolume = project.CalculateWeldVolume();


            //Output back to Grasshopper
            //OUTPUT: WELDING, VOLUME PER JOINT
            for (int i = 0; i < project.joints.Count; i++)
            {
                weldVolumePerJoint.Add(project.joints[i].weldVolume);
            }
            //OUTPUT: WELDING, THROATS PER ELEMENT


            foreach (ElementRAZ ele in project.elementRAZs)
            {
                throatBegin.Add(ele.BeginThroatsElement());
                throatEnd.Add(ele.EndThroatsElement());

                plateBegin.Add(ele.BeginPlatesElement());
                plateEnd.Add(ele.EndPlatesElement());

                if (ele.line.vector.length > tol + eccentricity)
                {
                    CSSnames.Add(ele.crossSection.name);
                }
                else
                {
                    CSSnames.Add("");
                }
            }



            //OUTPUT:SAWING
            for (int i = 0; i < project.elementRAZs.Count; i++)
            {
                ElementRAZ.SawingCut start = project.elementRAZs[i].startCut;
                ElementRAZ.SawingCut end   = project.elementRAZs[i].endCut;
                if (start == ElementRAZ.SawingCut.RightAngledCut)
                {
                    TotalRightAngledCuts++;
                }
                if (end == ElementRAZ.SawingCut.RightAngledCut)
                {
                    TotalRightAngledCuts++;
                }
                if (start == ElementRAZ.SawingCut.SingleMiterCut)
                {
                    TotalSingleMiterCuts++;
                }
                if (end == ElementRAZ.SawingCut.SingleMiterCut)
                {
                    TotalSingleMiterCuts++;
                }
                if (start == ElementRAZ.SawingCut.DoubleMiterCut)
                {
                    TotalDoubleMiterCuts++;
                }
                if (end == ElementRAZ.SawingCut.DoubleMiterCut)
                {
                    TotalDoubleMiterCuts++;
                }
                int tot = (int)start + (int)end;
                //If more than element has more than one cut, substract one cut
                //In the sawing line the endcut of one member serves as the start cut of the other
                int cutsPerElement;
                if (tot > 1)
                {
                    cutsPerElement = tot - 1;
                }
                else
                {
                    cutsPerElement = tot;
                }
                numberOfSawingCuts.Add(cutsPerElement);
            }


            //export lines of joint for visualisation purposes
            foreach (int i in project.joints[project.calculateThisJoint].beamIDs)
            {
                jointlines.Add(lines[i]);
            }

            //Output lines
            DA.SetData(0, project.joints.Count);
            DA.SetDataList(1, jointlines);
        }
Example #51
0
        public void PerformanceForEach_With55500ElementsInterconnected()
        {
            var start1   = 0;
            var elements = new List <int>();

            elements.Add(start1);
            var hierarchy = new Hierarchy <int>(start1);

            for (int i = 1; i <= 51100; i = i + 511)
            {
                hierarchy.Add(start1, i);
                for (int j = i + 1; j <= i + 510; j = j + 51)
                {
                    hierarchy.Add(i, j);
                    for (int k = j + 1; k <= j + 50; k++)
                    {
                        hierarchy.Add(j, k);
                    }
                }
            }

            for (int i = 1; i <= 51100; i = i + 511)
            {
                elements.Add(i);
            }

            for (int i = 1; i <= 51100; i = i + 511)
            {
                for (int j = i + 1; j <= i + 510; j = j + 51)
                {
                    elements.Add(j);
                }
            }

            for (int i = 1; i <= 51100; i = i + 511)
            {
                for (int j = i + 1; j <= i + 510; j = j + 51)
                {
                    for (int k = j + 1; k <= j + 50; k++)
                    {
                        elements.Add(k);
                    }
                }
            }

            var counter = 0;

            Stopwatch timer = new Stopwatch();

            timer.Start();

            foreach (var element in hierarchy)
            {
                Assert.AreEqual(elements[counter++], element, "Expected element did not match!");
            }

            timer.Stop();
            Assert.IsTrue(timer.ElapsedMilliseconds < 200);

            Assert.AreEqual(counter, hierarchy.Count, "Incorect number of elements returned!");
        }
Example #52
0
        /// <summary>
        /// Loads the log4net configuration either from the corresponding app.config file (see log4net for more details) or by
        /// statically generating a default logger.
        /// </summary>
        /// <param name="xml">If <c>true</c>, the app.config file will be loaded. Otherwise, a default configuration.</param>
        /// <param name="printDebug">If <c>true</c>, debug statements will be printed to console (otherwise only <c>Level.Info</c> and up).</param>
        public static void EnableLogging(bool xml = false, bool printDebug = false)
        {
            if (xml)
            {
                XmlConfigurator.Configure();
            }
            else
            {
                // see https://stackoverflow.com/questions/37213848/best-way-to-access-to-log4net-wrapper-app-config
                Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();

                PatternLayout patternLayout = new PatternLayout
                {
                    ConversionPattern = "%date %level [%thread] %logger{1} - %message%newline"
                };
                patternLayout.ActivateOptions();

                // Create a colored console appender with color mappings and level range [Info, Fatal]
                ColoredConsoleAppender console = new ColoredConsoleAppender
                {
                    Threshold = Level.All,
                    Layout    = patternLayout
                };
                LevelRangeFilter consoleRangeFilter = new LevelRangeFilter
                {
                    LevelMin = printDebug ? Level.Debug : Level.Info,
                    LevelMax = Level.Fatal
                };
                console.AddFilter(consoleRangeFilter);
                console.AddMapping(new ColoredConsoleAppender.LevelColors
                {
                    Level     = Level.Debug,
                    ForeColor = ColoredConsoleAppender.Colors.White
                });
                console.AddMapping(new ColoredConsoleAppender.LevelColors
                {
                    Level     = Level.Info,
                    ForeColor = ColoredConsoleAppender.Colors.Green
                });
                console.AddMapping(new ColoredConsoleAppender.LevelColors
                {
                    Level     = Level.Warn,
                    ForeColor = ColoredConsoleAppender.Colors.Yellow | ColoredConsoleAppender.Colors.HighIntensity
                });
                console.AddMapping(new ColoredConsoleAppender.LevelColors
                {
                    Level     = Level.Error,
                    ForeColor = ColoredConsoleAppender.Colors.Red | ColoredConsoleAppender.Colors.HighIntensity
                });
                console.AddMapping(new ColoredConsoleAppender.LevelColors
                {
                    Level     = Level.Fatal,
                    ForeColor = ColoredConsoleAppender.Colors.White | ColoredConsoleAppender.Colors.HighIntensity,
                    BackColor = ColoredConsoleAppender.Colors.Red | ColoredConsoleAppender.Colors.HighIntensity
                });
                console.ActivateOptions();

                hierarchy.Root.AddAppender(console);

                // Create also an appender that writes the log to sigma.log
                RollingFileAppender roller = new RollingFileAppender
                {
                    AppendToFile       = true,
                    File               = "sigma.log",
                    Layout             = patternLayout,
                    MaxSizeRollBackups = 5,
                    MaximumFileSize    = "15MB",
                    RollingStyle       = RollingFileAppender.RollingMode.Size,
                    StaticLogFileName  = true
                };
                roller.ActivateOptions();

                hierarchy.Root.AddAppender(roller);

                hierarchy.Root.Level = Level.Debug;
                hierarchy.Configured = true;
            }
        }
 public MemberChildrenSet(Hierarchy hier, System.Xml.XmlElement xmlEl) : base(null, hier)
 {
     LoadFromXml(xmlEl);
 }
 public void LoggerSetup(string SQLServer, string SQLDatenBank, string SQLTable, string customContent2)
 {
     if (i == 0)
     {
         RawLayoutConverter      rlc            = new RawLayoutConverter();
         AdoNetAppender          adoNet         = new AdoNetAppender();
         AdoNetAppenderParameter logDate        = new AdoNetAppenderParameter();
         AdoNetAppenderParameter thread         = new AdoNetAppenderParameter();
         AdoNetAppenderParameter logLevel       = new AdoNetAppenderParameter();
         AdoNetAppenderParameter logLogger      = new AdoNetAppenderParameter();
         AdoNetAppenderParameter message        = new AdoNetAppenderParameter();
         AdoNetAppenderParameter exception      = new AdoNetAppenderParameter();
         AdoNetAppenderParameter customColoumn1 = new AdoNetAppenderParameter();
         AdoNetAppenderParameter customColoumn2 = new AdoNetAppenderParameter();
         Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();
         hierarchy.Root.AddAppender(adoNet);
         hierarchy.Root.Level = Level.All;
         hierarchy.Configured = true;
         log4net.Config.BasicConfigurator.Configure(adoNet);
         //logDate
         logDate.ParameterName = "@log_date";
         logDate.DbType        = System.Data.DbType.DateTime;
         logDate.Layout        = new RawTimeStampLayout();
         //thread
         thread.ParameterName = "@thread";
         thread.DbType        = System.Data.DbType.String;
         thread.Size          = 255;
         thread.Layout        = (IRawLayout)rlc.ConvertFrom(new PatternLayout("%thread"));
         //logLevel
         logLevel.ParameterName = "@log_level";
         logLevel.DbType        = System.Data.DbType.String;
         logLevel.Size          = 50;
         logLevel.Layout        = (IRawLayout)rlc.ConvertFrom(new PatternLayout("%level"));
         //logLogger
         logLogger.ParameterName = "@logger";
         logLogger.DbType        = System.Data.DbType.String;
         logLogger.Size          = 255;
         logLogger.Layout        = (IRawLayout)rlc.ConvertFrom(new PatternLayout("%logger"));
         //message
         message.ParameterName = "@message";
         message.DbType        = System.Data.DbType.String;
         message.Size          = 4000;
         message.Layout        = (IRawLayout)rlc.ConvertFrom(new PatternLayout("%message"));
         //exception
         exception.ParameterName = "@exception";
         exception.DbType        = System.Data.DbType.String;
         exception.Size          = 2000;
         exception.Layout        = (IRawLayout)rlc.ConvertFrom(new ExceptionLayout());
         //customColoumn1
         customColoumn1.ParameterName = "@customValue1";
         customColoumn1.DbType        = System.Data.DbType.String;
         customColoumn1.Size          = 2000;
         customColoumn1.Layout        = (IRawLayout)rlc.ConvertFrom(new PatternLayout("%property{CustomColumn1}"));
         //customColoumn2
         customColoumn2.ParameterName = "@customValue2";
         customColoumn2.DbType        = System.Data.DbType.String;
         customColoumn2.Size          = 2000;
         customColoumn2.Layout        = (IRawLayout)rlc.ConvertFrom(new PatternLayout("%property{CustomColumn2}"));
         adoNet.BufferSize            = 1;
         adoNet.CommandType           = System.Data.CommandType.Text;
         adoNet.ConnectionType        = "System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
         adoNet.ConnectionString      = "data source=" + SQLServer + "; initial catalog=" + SQLDatenBank + ";integrated security=true";
         adoNet.CommandText           = "INSERT INTO " + SQLTable + " ([Date],[Thread],[Level],[Logger],[Message],[Exception],[CustomColoumn1],[CustomColoumn2]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception, @customValue1, @customValue2)";
         adoNet.AddParameter(logDate);
         adoNet.AddParameter(thread);
         adoNet.AddParameter(logLevel);
         adoNet.AddParameter(logLogger);
         adoNet.AddParameter(message);
         adoNet.AddParameter(exception);
         adoNet.AddParameter(customColoumn1);
         adoNet.AddParameter(customColoumn2);
         adoNet.ActivateOptions();
         log4net.LogicalThreadContext.Properties["CustomColumn2"] = customContent2;
         i = 1;
     }
     else
     {
         log4net.LogicalThreadContext.Properties["CustomColumn2"] = customContent2;
     }
 }
 public MemberChildrenSet(string name, Hierarchy hier, Member mem) : base(name, hier)
 {
     _mdxParameters.Add(mem, false);
     Initialize(name);
 }
Example #56
0
 public IEnumerable <T> GetCommonElements(Hierarchy <T> other)
 => this.nodes.Keys
 .Where(x => other.Contains(x));
Example #57
0
 public MembersAggregate(string name, Hierarchy hier, AggregateFunction aggr) : base(name, hier)
 {
     _aggregation = aggr;
     this.Initialize(name);
 }
Example #58
0
        //void UseFileCofnig(ILoggerRepository rep)
        //{
        //    var type = MethodBase.GetCurrentMethod().DeclaringType;
        //    if (type != null)
        //    {
        //        var ns = type.Namespace;
        //        Assembly assembly = Assembly.GetExecutingAssembly();
        //        string resourceName = ns + ".log4net.config";
        //        Stream stream = assembly.GetManifestResourceStream(resourceName);
        //        XmlConfigurator.Configure(rep, stream);
        //    }
        //}

        //void UseCodeConfig(Hierarchy repository, string type)
        void UseCodeConfig(Hierarchy repository, LogLevel logLevel)
        {
            var ip = JimuHelper.GetLocalIPAddress();

            if (_options.EnableFileLog && (_options.FileLogLevel & logLevel) == logLevel)
            {
                PatternLayout layout = new PatternLayout
                {
                    ConversionPattern = "%date{yyyy-MM-dd HH:mm:ss.fff} %-5p [" + ip + "] %m%n"
                };
                layout.ActivateOptions();

                RollingFileAppender roller = new RollingFileAppender
                {
                    AppendToFile = false
                };
                var path = _options.EnableFileLog ? _options.FileLogPath : "log";
                roller.File = $@"{path}/{logLevel.ToString().ToLower()}/";
                roller.PreserveLogFileNameExtension = true;
                roller.StaticLogFileName            = false;
                roller.MaxSizeRollBackups           = 0;
                roller.DatePattern  = $@"yyyyMMdd"".log""";
                roller.RollingStyle = RollingFileAppender.RollingMode.Date;
                roller.Layout       = layout;
                roller.MaxFileSize  = 10000000;
                switch (logLevel)
                {
                case LogLevel.Debug:
                    roller.Threshold = Level.Debug;
                    break;

                case LogLevel.Info:
                    roller.Threshold = Level.Info;
                    break;

                case LogLevel.Warn:
                    roller.Threshold = Level.Warn;
                    break;

                case LogLevel.Error:
                    roller.Threshold = Level.Error;
                    break;
                }
                roller.ActivateOptions();
                repository.Root.AddAppender(roller);
            }

            if (_options.EnableConsoleLog && (_options.ConsoleLogLevel & logLevel) == logLevel)
            {
                //ManagedColoredConsoleAppender managedColoredConsoleAppender = new
                ManagedColoredConsoleAppender console = new ManagedColoredConsoleAppender();
                PatternLayout layoutConsole           = new PatternLayout
                {
                    ConversionPattern = "%n%date{yyyy-MM-dd HH:mm:ss.fff} %-5level [" + ip + "] %m",
                };
                switch (logLevel)
                {
                case LogLevel.Debug:
                    //console.Threshold = Level.Debug;
                    console.AddFilter(new LevelRangeFilter()
                    {
                        LevelMax = Level.Debug, LevelMin = Level.Debug
                    });
                    //console.AddFilter(new LevelMatchFilter() { LevelToMatch = Level.Debug, AcceptOnMatch = true });
                    break;

                case LogLevel.Info:
                    //console.Threshold = Level.Info;
                    console.AddFilter(new LevelRangeFilter()
                    {
                        LevelMax = Level.Info, LevelMin = Level.Info
                    });
                    //console.AddFilter(new LevelMatchFilter() { LevelToMatch = Level.Info, AcceptOnMatch = true });
                    break;

                case LogLevel.Warn:
                    //console.Threshold = Level.Warn;
                    console.AddFilter(new LevelRangeFilter()
                    {
                        LevelMax = Level.Warn, LevelMin = Level.Warn
                    });
                    //console.AddFilter(new LevelMatchFilter() { LevelToMatch = Level.Warn, AcceptOnMatch = true });
                    break;

                case LogLevel.Error:
                    //console.Threshold = Level.Error;
                    console.AddFilter(new LevelRangeFilter()
                    {
                        LevelMax = Level.Error, LevelMin = Level.Error
                    });
                    //console.AddFilter(new LevelMatchFilter() { LevelToMatch = Level.Error });
                    break;
                }
                console.AddMapping(
                    new ManagedColoredConsoleAppender.LevelColors {
                    Level = Level.Error, ForeColor = ConsoleColor.DarkRed
                });
                console.AddMapping(
                    new ManagedColoredConsoleAppender.LevelColors {
                    Level = Level.Warn, ForeColor = ConsoleColor.DarkYellow
                });

                layoutConsole.ActivateOptions();
                console.Layout = layoutConsole;
                console.ActivateOptions();
                repository.Root.AddAppender(console);
            }

            //MemoryAppender memory = new MemoryAppender();
            //memory.ActivateOptions();
            //repository.Root.AddAppender(memory);

            //repository.Root.Level = Level.Debug;
            repository.Configured = true;
        }
Example #59
0
    public static bool WriteLog(object message, Exception ex = null, Level level = Level.Info)
    {
        lock (logLock)
        {
            try
            {
                bool writeLog = ConfigHelper.GetConfigBool("WriteLog"); //读取开关
                if (!writeLog)
                {
                    return(true);
                }
                if (message == null || string.IsNullOrWhiteSpace(message.ToString()))
                {
                    return(false);                                                                  //不写空日志
                }
                if (logger == null)
                {
                    PatternLayout patternLayout = new PatternLayout();
                    patternLayout.ConversionPattern = LOG_PATTERN;
                    patternLayout.ActivateOptions();

                    TraceAppender tracer = new TraceAppender();
                    tracer.Layout = patternLayout;
                    tracer.ActivateOptions();

                    RollingFileAppender roller = new RollingFileAppender();
                    roller.Layout             = patternLayout;
                    roller.AppendToFile       = true;
                    roller.File               = "Log/";
                    roller.StaticLogFileName  = false;
                    roller.DatePattern        = "yyyyMMdd.LOG";
                    roller.RollingStyle       = RollingFileAppender.RollingMode.Date;
                    roller.MaximumFileSize    = "10MB";
                    roller.MaxSizeRollBackups = 10;
                    //roller.ImmediateFlush = true;
                    roller.Encoding     = Encoding.UTF8;
                    roller.LockingModel = new FileAppender.MinimalLock();
                    roller.ActivateOptions();

                    Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();
                    hierarchy.Name = "log";
                    hierarchy.Root.AddAppender(tracer);
                    hierarchy.Root.AddAppender(roller);
                    hierarchy.Root.Level = log4net.Core.Level.All;
                    hierarchy.Configured = true;

                    logger = LogManager.GetLogger("log");
                }

                if (ex == null)
                {
                    switch (level)
                    {
                    case Level.Debug:
                        logger.Debug(message);
                        break;

                    case Level.Error:
                        logger.Error(message);
                        break;

                    case Level.Fatal:
                        logger.Fatal(message);
                        break;

                    case Level.Info:
                        logger.Info(message);
                        break;

                    case Level.Warn:
                        logger.Warn(message);
                        break;
                    }
                }
                else
                {
                    switch (level)
                    {
                    case Level.Debug:
                        logger.Debug(message, ex);
                        break;

                    case Level.Error:
                        logger.Error(message, ex);
                        break;

                    case Level.Fatal:
                        logger.Fatal(message, ex);
                        break;

                    case Level.Info:
                        logger.Info(message, ex);
                        break;

                    case Level.Warn:
                        logger.Warn(message, ex);
                        break;
                    }
                }
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
            finally
            {
            }
        }
    }
 public AnnotationAttribute(Hierarchy hierarchy, params Type[] types)
 {
 }