Exemplo n.º 1
0
        }       //	MTreeNodeCMS

        /// <summary>
        /// Full Constructor
        /// </summary>
        /// <param name="tree">tree</param>
        /// <param name="Node_ID">node</param>
        public MTreeNodeCMT(MTree tree, int Node_ID) : base(tree.GetCtx(), 0, tree.Get_TrxName())
        {
            //super (tree.getCtx(), 0, tree.get_TrxName());
            SetClientOrg(tree);
            SetAD_Tree_ID(tree.GetAD_Tree_ID());
            SetNode_ID(Node_ID);
            //	Add to root
            SetParent_ID(0);
            SetSeqNo(0);
        }       //	MTreeNodeCMT
Exemplo n.º 2
0
        public MTree GetMenuTree(int AD_Tree_ID, bool editable, bool onDemandTree, int nodeID)
        {
            MTree vTree = null;

            if (onDemandTree)
            {
                vTree = new MTree(ctx, AD_Tree_ID, editable, true, null, true, 180, 0);
            }

            return(vTree);
        }
Exemplo n.º 3
0
        public void KNearestNeighborsTest()
        {
            int            maxItems  = 10000;
            int            k         = 100;
            Random         rand      = new Random();
            CartesianPoint testPoint = new CartesianPoint(0, 0);

            MTree <CartesianPoint>         tree       = new MTree <CartesianPoint>(CartesianPoint.PythagoreanTheorem);
            PriorityQueue <CartesianPoint> kNeighbors = new PriorityQueue <CartesianPoint>(k);

            CartesianPoint newPoint;

            for (int i = 0; i < maxItems; i++)
            {
                int xMultiplier = rand.Next(-2, 1);
                while (xMultiplier == 0)
                {
                    xMultiplier = rand.Next(-2, 1);
                }

                int yMultiplier = rand.Next(-2, 1);
                while (yMultiplier == 0)
                {
                    yMultiplier = rand.Next(-2, 1);
                }

                double x = maxItems * xMultiplier * rand.NextDouble() * 0.05;
                double y = maxItems * yMultiplier * rand.NextDouble() * 0.05;

                newPoint = new CartesianPoint(x, y);

                tree.Add(newPoint);

                double dist = tree.GetDistance(newPoint, testPoint);

                kNeighbors.Enqueue(newPoint, dist);
            }

            PriorityQueue <CartesianPoint> queryReturns = tree.KNearestNeighborSearch(testPoint, k);

            Assert.AreEqual(k, queryReturns.Count, "K neighor search did not return the correct number of items.");

            while (kNeighbors.HasNext)
            {
                var neighbor = kNeighbors.Dequeue();
                var result   = queryReturns.Dequeue();

                Assert.AreEqual(neighbor.Value, result.Value, "K neighbor search returned wrong item.");
                Assert.AreEqual(neighbor.Key, result.Key, "K neighbor search returned correct item with wrong distance.");
            }

            Assert.IsFalse(queryReturns.HasNext, "K neighbor search returned too many items.");
        }
Exemplo n.º 4
0
    public Mesh GenerateTree(bool instantAo = false)
    {
        tree = null;
        ExecuteFunctions();
        tree.Simplify(LODs[LodIndex].simplifyAngleThreshold, LODs[LodIndex].simplifyRadiusThreshold);
        Mesh mesh = CreateMesh();

        filter.mesh = mesh;

        BakeAo(!instantAo);
        UpdateMaterials();
        return(mesh);
    }
Exemplo n.º 5
0
        public Node(MTree <T> tree, Node <T> parent, T item, double distToParent, bool isRoot, bool isLeaf)
            : base(item, distToParent, 0)
        {
            Tree   = tree;
            Parent = parent;

            IsRoot = isRoot;
            IsLeaf = isLeaf;

            NodeID = tree.NewNodeID();

            Children = new List <MTreeElement <T> >(tree.MaxNodesSize + 1);
        }
Exemplo n.º 6
0
    void InitializeTree()
    {
        MtreeVersion = MtreeVariables.MtreeVersion;
        filter       = GetComponent <MeshFilter>();
        tree         = new MTree(transform);

        if (LODs == null || LODs.Count == 0)
        {
            for (int i = 0; i < 4; i++)
            {
                AddLODLevel(false);
            }
        }
    }
        /// <summary>
        ///
        /// </summary>
        /// <param name="AD_Tree_ID"></param>
        /// <param name="editable"></param>
        /// <returns></returns>

        public MTree GetMenuTree(int AD_Tree_ID, bool editable, bool onDemandTree, int nodeID, int AD_Tab_ID, int winNo)
        {
            _onDemandTree = onDemandTree;
            MTree vTree = null;

            if (onDemandTree)
            {
                vTree = new MTree(_ctx, AD_Tree_ID, editable, true, null, true, AD_Tab_ID, winNo);
            }
            else
            {
                vTree = new MTree(_ctx, AD_Tree_ID, editable, true, null, nodeID, AD_Tab_ID);
            }
            return(vTree);
        }
Exemplo n.º 8
0
        public void MTreeSearchTest()
        {
            MTree <IPoint> tree = new MTree <IPoint>(2, 3, (x, y) => GeometryDistanceAlgorithm.Distance(x, y));

            tree.Search(this.geometries[0]).ShouldBeEmpty();

            IPoint[] points = new IPoint[9];

            for (Int32 i = 0; i < 9; i++)
            {
                points[i] = this.factory.CreatePoint(i, 0);
                tree.Add(points[i]);
            }

            // search without limits should return all items in the tree
            tree.Search(this.factory.CreatePoint(2, 0)).Count().ShouldBe(9);

            // search returns the correct data items in the correct order with correct distance information
            List <ResultItem <IPoint> > results = new List <ResultItem <IPoint> >(tree.Search(this.factory.CreatePoint(8, 0)));
            List <IPoint> expectedResults       = new List <IPoint>(points.Reverse());

            for (Int32 i = 0; i < points.Length; i++)
            {
                results[i].Item.ShouldBe(expectedResults[i]);
                results[i].Distance.ShouldBe(i);
            }

            // search with a given radius should return only the elements within that radius
            tree.Search(this.factory.CreatePoint(8, 0), 1.0D).Count().ShouldBe(2);
            tree.Search(this.factory.CreatePoint(7, 0), 1.0D).Count().ShouldBe(3);
            tree.Search(this.factory.CreatePoint(9, 0), 1.0D).Count().ShouldBe(1);
            tree.Search(this.factory.CreatePoint(10, 0), 1.0D).Count().ShouldBe(0);

            // search with a given limit should return only that amount of elements
            tree.Search(this.factory.CreatePoint(2, 0), 0).Count().ShouldBe(0);
            tree.Search(this.factory.CreatePoint(2, 0), 1).Count().ShouldBe(1);
            tree.Search(this.factory.CreatePoint(2, 0), 5).Count().ShouldBe(5);
            tree.Search(this.factory.CreatePoint(2, 0), 10).Count().ShouldBe(9);

            // search with both radius and limit where radius contains less elements than limit
            tree.Search(this.factory.CreatePoint(2, 0), 1.1D, 5).Count().ShouldBe(3);

            // search with both radius and limit where radius contains more elements than limit
            tree.Search(this.factory.CreatePoint(2, 0), 1.1D, 2).Count().ShouldBe(2);

            // errors
            Should.Throw <ArgumentNullException>(() => tree.Search(null));
        }
Exemplo n.º 9
0
    public Mesh GenerateTree(bool ao = false)
    {
        if (treeFunctions != null && treeFunctions.Count > 1 && MtreeVersion != MtreeVariables.MtreeVersion)
        {
            return(null);
        }


        tree = null;
        ExecuteFunctions();
        tree.Simplify(simplifyAngleThreshold[Lod], simplifyRadiusThreshold[Lod]);
        Mesh mesh = CreateMesh(ao);

        UpdateMaterials();
        return(mesh);
    }
Exemplo n.º 10
0
        public void ContainsTest()
        {
            int         maxNodeSize = 25;
            int         numItems    = 10000;
            MTree <int> tree        = new MTree <int>((x, y) => Math.Abs(x - y), maxNodeSize);

            for (int i = 0; i < numItems; i++)
            {
                tree.Add(i);
                Assert.AreEqual(i + 1, tree.Count, "Count is not returning the correct value.");
            }

            for (int i = 0; i < numItems; i++)
            {
                Assert.IsTrue(tree.Contains(i), "Contains is returning false for a value that has been inserted in the MTree.");
            }
        }
Exemplo n.º 11
0
        public void NearestNeighboorsTest()
        {
            var dataSize     = 10000;
            var testDataSize = 10;
            var range        = 100;
            var neighboors   = 10;

            var testData = global::Supercluster.Tests.Utilities.GenerateDoubles(testDataSize, range, 5);

            for (int index = 0; index < testData.Length; index++)
            {
                var treeData = global::Supercluster.Tests.Utilities.GenerateDoubles(dataSize, range, 5);

                Console.WriteLine($"Test {index} of {testData.Length}");


                var target = testData[index];

                // load tree
                var mtree = new MTree <double[]>(Metrics.L2Norm, 3, treeData);


                // linear search
                var linearResults = Utilities.LinearNearestNeighboors(target, neighboors, treeData, Metrics.L2Norm);

                // tree knn
                var resultsList = mtree.NearestNeighbors(target, neighboors).ToArray();

                for (int i = 0; i < resultsList.Length; i++)
                {
                    var result   = resultsList[i];
                    var lin      = linearResults[i];
                    var treeDist = Metrics.L2Norm(result, target);
                    var linDist  = Metrics.L2Norm(lin, target);

                    var check = treeDist == linDist;
                    if (!check)
                    {
                        Console.WriteLine($"MTree: {treeDist} Linear: {linDist}");
                    }
                    Assert.That(treeDist == linDist);
                }
            }
        }
Exemplo n.º 12
0
    public Mesh GenerateTree(bool instantAo = false)
    {
        if (treeFunctionsAssets != null && treeFunctionsAssets.Count > 1 && MtreeVersion != MtreeVariables.MtreeVersion)
        {
            return(null);
        }


        tree = null;
        ExecuteFunctions();
        tree.Simplify(LODs[LodIndex].simplifyAngleThreshold, LODs[LodIndex].simplifyRadiusThreshold);
        Mesh mesh = CreateMesh();

        filter.mesh = mesh;

        BakeAo(!instantAo);
        UpdateMaterials();
        return(mesh);
    }
Exemplo n.º 13
0
        public void GeographicPoint_OptimalNodeSize()
        {
            Stopwatch watch = new Stopwatch();

            List <GeographicPoint> testPoints = GenerateTestGeographicPoints();

            foreach (int nodeSize in testNodeSizes)
            {
                Console.WriteLine("Maximum node size: " + nodeSize);
                Console.WriteLine("----------------------------");

                MTree <GeographicPoint> tree = new MTree <GeographicPoint>(GeographicPoint.HaversineFormula, nodeSize);

                watch.Reset();
                watch.Start();

                PopulateTree(tree, testPoints);

                watch.Stop();

                Console.WriteLine("Build:\t\t" + FormatTime(watch.Elapsed.Ticks));

                watch.Reset();
                watch.Start();

                PerformRangeSearch(tree, testPoints);

                watch.Stop();

                Console.WriteLine("Range:\t\t" + FormatTime(watch.Elapsed.Ticks));

                watch.Reset();
                watch.Start();

                PerformKNeighborSearch(tree, testPoints);

                watch.Stop();

                Console.WriteLine("K Neighbor:\t" + FormatTime(watch.Elapsed.Ticks));
                Console.WriteLine("\n\n");
            }
        }
        public int updateTree(Ctx ctx, string nodeID, int oldParentID, int newParentID, int AD_Tree_ID)
        {
            MTree  trr       = new MTree(ctx, AD_Tree_ID, null);
            string tableName = trr.GetNodeTableName();


            string[] selectedID = nodeID.Split(',');


            string sql = "Update " + tableName + " SET SeqNo=Seqno+" + selectedID.Length + ", updated=SYSDATE WHERE AD_Tree_ID=" + AD_Tree_ID + " AND Parent_ID=" + newParentID;

            DB.ExecuteQuery(sql);

            for (int i = 0; i < selectedID.Length; i++)
            {
                DB.ExecuteQuery("UPDATE " + tableName + " SET Parent_ID=" + newParentID + ", seqNo=0, updated=SYSDATE WHERE AD_Tree_ID=" + AD_Tree_ID + " AND Node_ID=" + selectedID[i]);
            }

            return(1);
        }
Exemplo n.º 15
0
        }                                  //	prepare

        /// <summary>
        /// Perform Process.
        /// </summary>
        /// <returns>Message (clear text)</returns>
        protected override String DoIt()
        {
            log.Info("AD_Tree_ID=" + m_AD_Tree_ID);
            if (m_AD_Tree_ID == 0)
            {
                throw new ArgumentException("Tree_ID = 0");
            }
            MTree tree = new MTree(GetCtx(), m_AD_Tree_ID, Get_Trx());

            if (tree == null || tree.GetAD_Tree_ID() == 0)
            {
                throw new ArgumentException("No Tree -" + tree);
            }
            //
            if (MTree.TREETYPE_BoM.Equals(tree.GetTreeType()))
            {
                return("BOM Trees not implemented");
            }
            return(VerifyTree(tree));
        }       //	doIt
Exemplo n.º 16
0
    public static void Function()
    {
        MTree <int> mTree = new MTree <int>();

        mTree.Add(123);
        mTree.Add(324);
        mTree.Add(45);
        mTree.Add(78);
        mTree.Add(126653);
        mTree.Add(144523);
        mTree.Add(1624444443);
        mTree.Add(12 + 73);
        mTree.MidOrder();
        WriteLine("--------------------------------------------------");
        mTree.PreOrder();
        WriteLine("--------------------------------------------------");
        mTree.PostOrder();
        WriteLine("--------------------------------------------------");
        WriteLine(mTree.Max());
    }
Exemplo n.º 17
0
 /// <summary>
 /// Before Save
 /// </summary>
 /// <param name="newRecord">new</param>
 /// <returns>true</returns>
 protected override bool BeforeSave(bool newRecord)
 {
     //	Create Trees
     if (newRecord)
     {
         MTree tree = new MTree(GetCtx(),
                                GetName() + MTree.TREETYPE_CMContainer, MTree.TREETYPE_CMContainer, Get_TrxName());
         if (!tree.Save())
         {
             return(false);
         }
         SetAD_TreeCMC_ID(tree.GetAD_Tree_ID());
         //
         tree = new MTree(GetCtx(),
                          GetName() + MTree.TREETYPE_CMContainerStage, MTree.TREETYPE_CMContainerStage, Get_TrxName());
         if (!tree.Save())
         {
             return(false);
         }
         SetAD_TreeCMS_ID(tree.GetAD_Tree_ID());
         //
         tree = new MTree(GetCtx(),
                          GetName() + MTree.TREETYPE_CMTemplate, MTree.TREETYPE_CMTemplate, Get_TrxName());
         if (!tree.Save())
         {
             return(false);
         }
         SetAD_TreeCMT_ID(tree.GetAD_Tree_ID());
         //
         tree = new MTree(GetCtx(),
                          GetName() + MTree.TREETYPE_CMMedia, MTree.TREETYPE_CMMedia, Get_TrxName());
         if (!tree.Save())
         {
             return(false);
         }
         SetAD_TreeCMM_ID(tree.GetAD_Tree_ID());
     }
     return(true);
 }       //	beforeSave
Exemplo n.º 18
0
        /// <summary>
        /// Get Tree Node
        /// </summary>
        /// <param name="tree">tree</param>
        /// <param name="Node_ID">node</param>
        /// <returns>node or null</returns>
        public static MTreeNodeBP Get(MTree tree, int Node_ID)
        {
            MTreeNodeBP retValue = null;
            String      sql      = "SELECT * FROM AD_TreeNodeBP WHERE AD_Tree_ID=@Param1 AND Node_ID=@Param2";

            SqlParameter[] Param = new SqlParameter[2];
            IDataReader    idr   = null;
            DataTable      dt    = null;

            try
            {
                //pstmt = DataBase.prepareStatement (sql, tree.get_TrxName());
                //pstmt.setInt (1, tree.getAD_Tree_ID());
                Param[0] = new SqlParameter("@Param1", tree.GetAD_Tree_ID());
                //pstmt.setInt (2, Node_ID);
                Param[1] = new SqlParameter("@Param2", Node_ID);
                //ResultSet rs = pstmt.executeQuery ();
                dt  = new DataTable();
                idr = DataBase.DB.ExecuteReader(sql, Param, tree.Get_TrxName());
                dt.Load(idr);
                idr.Close();
                //if (rs.next ())
                foreach (DataRow dr in dt.Rows)
                {
                    retValue = new MTreeNodeBP(tree.GetCtx(), dr, tree.Get_TrxName());
                }
            }
            catch (Exception e)
            {
                _log.Log(Level.SEVERE, "get", e);
            }
            finally
            {
                dt = null;
                idr.Close();
            }
            return(retValue);
        }       //	get
Exemplo n.º 19
0
        public void ItemInsertVerification()
        {
            int    maxItems = 1000;
            int    maxNodes = 25;
            Random rand     = new Random();

            MTree <CartesianPoint> tree = new MTree <CartesianPoint>(CartesianPoint.PythagoreanTheorem, maxNodes);

            CartesianPoint newPoint;

            for (int i = 1; i <= maxItems; i++)
            {
                int xMultiplier = rand.Next(-2, 1);
                while (xMultiplier == 0)
                {
                    xMultiplier = rand.Next(-2, 1);
                }

                int yMultiplier = rand.Next(-2, 1);
                while (yMultiplier == 0)
                {
                    yMultiplier = rand.Next(-2, 1);
                }

                double x = maxItems * xMultiplier * rand.NextDouble() * 0.05;
                double y = maxItems * yMultiplier * rand.NextDouble() * 0.05;

                newPoint = new CartesianPoint(x, y);

                tree.Add(newPoint);

                Assert.AreEqual(i, tree.Count, "MTree does not give correct Count after adding a new element.");
                Assert.IsTrue(tree.Contains(newPoint), "MTree does not say it Contains new item that has been added.");

                NodeDescentAssert(tree.Root, 1, maxNodes);
            }
        }
Exemplo n.º 20
0
        public void MTreeConstructorTest()
        {
            MTree <IPoint> tree = new MTree <IPoint>((x, y) => GeometryDistanceAlgorithm.Distance(x, y));

            tree.NumberOfDataItems.ShouldBe(0);
            tree.MinChildren.ShouldBe(50);
            tree.MaxChildren.ShouldBe(101);

            tree = new MTree <IPoint>(2, 4, (x, y) => GeometryDistanceAlgorithm.Distance(x, y));
            tree.NumberOfDataItems.ShouldBe(0);
            tree.MinChildren.ShouldBe(2);
            tree.MaxChildren.ShouldBe(4);

            tree = new MTree <IPoint>(10, 100, (x, y) => GeometryDistanceAlgorithm.Distance(x, y));
            tree.NumberOfDataItems.ShouldBe(0);
            tree.MinChildren.ShouldBe(10);
            tree.MaxChildren.ShouldBe(100);

            Should.Throw <ArgumentOutOfRangeException>(() => new MTree <IPoint>(-10, 1, (x, y) => GeometryDistanceAlgorithm.Distance(x, y)));
            Should.Throw <ArgumentOutOfRangeException>(() => new MTree <IPoint>(0, 1, (x, y) => GeometryDistanceAlgorithm.Distance(x, y)));
            Should.Throw <ArgumentOutOfRangeException>(() => new MTree <IPoint>(1, 1, (x, y) => GeometryDistanceAlgorithm.Distance(x, y)));

            Should.Throw <ArgumentNullException>(() => new MTree <IPoint>(3, 5, null));
        }
Exemplo n.º 21
0
        }   //  parse

        public String ParseAndSaveLine(String line, int AD_Client_ID, int AD_Org_ID, int C_Element_ID, MTree tree)
        {
            log.Config(line);

            //  Fields with ',' are enclosed in "
            StringBuilder   newLine = new StringBuilder();
            StringTokenizer st      = new StringTokenizer(line, "\"", false);

            newLine.Append(st.NextToken());         //  first part
            while (st.HasMoreElements())
            {
                String s = st.NextToken();           //  enclosed part
                newLine.Append(s.Replace(',', ' ')); //  remove ',' with space
                if (st.HasMoreTokens())
                {
                    newLine.Append(st.NextToken()); //  unenclosed
                }
            }
            //  add space at the end        - tokenizer does not count empty fields
            newLine.Append(" ");

            //  Parse Line - replace ",," with ", ,"    - tokenizer does not count empty fields
            String pLine = Utility.Util.Replace(newLine.ToString(), ",,", ", ,");

            pLine = Utility.Util.Replace(pLine, ",,", ", ,");
            st    = new StringTokenizer(pLine, ",", false);
            //  All fields there ?
            if (st.CountTokens() == 1)
            {
                log.Log(Level.SEVERE, "Ignored: Require ',' as separator - " + pLine);
                return("");
            }
            if (st.CountTokens() < 9)
            {
                log.Log(Level.SEVERE, "Ignored: FieldNumber wrong: " + st.CountTokens() + " - " + pLine);
                return("");
            }

            //  Fill variables
            String Value = null, Name = null, Description = null,
                   AccountType = null, AccountSign = null, IsDocControlled = null,
                   IsSummary = null, Default_Account = null;
            int accountParent = -1;

            //
            for (int i = 0; i < 9 && st.HasMoreTokens(); i++)
            {
                String s = st.NextToken().Trim();
                //  Ignore, if is it header line
                if (s.StartsWith("[") && s.EndsWith("]"))
                {
                    return("");
                }
                if (s == null)
                {
                    s = "";
                }
                //
                if (i == 0)                     //	A - Value
                {
                    Value = s;
                }
                else if (i == 1)        //	B - Name
                {
                    Name = s;
                }
                else if (i == 2)        //	C - Description
                {
                    Description = s;
                }
                else if (i == 3)        //	D - Type
                {
                    AccountType = s.Length > 0 ? s[0].ToString() : "E";
                }
                else if (i == 4)        //	E - Sign
                {
                    AccountSign = s.Length > 0 ? s[0].ToString() : "N";
                }
                else if (i == 5)        //	F - DocControlled
                {
                    IsDocControlled = s.Length > 0 ? s[0].ToString() : "N";
                }
                else if (i == 6)        //	G - IsSummary
                {
                    IsSummary = s.Length > 0 ? s[0].ToString() : "N";
                }
                else if (i == 7)        //	H - Default_Account
                {
                    Default_Account = s;
                }
                else if (i == 8)
                {
                    accountParent = Util.GetValueOfInt(s);
                }
            }

            //	Ignore if Value & Name are empty (no error message)
            if ((Value == null || Value.Length == 0) && (Name == null || Name.Length == 0))
            {
                return("");
            }
            ////////////////////
            //Commented By Lakhwinder
            ////  Default Account may be blank
            //if (Default_Account == null || Default_Account.Length == 0)
            //    //	Default_Account = String.valueOf(s_keyNo++);
            //    return "";

            ////	No Summary Account
            //if (IsSummary == null || IsSummary.Length == 0)
            //    IsSummary = "N";
            //if (!IsSummary.Equals("N"))
            //    return "";

            ////  Validation
            //if (AccountType == null || AccountType.Length == 0)
            //    AccountType = "E";

            //if (AccountSign == null || AccountSign.Length == 0)
            //    AccountSign = "N";
            //if (IsDocControlled == null || IsDocControlled.Length == 0)
            //    IsDocControlled = "N";
            //////////////////////

            //	log.config( "Value=" + Value + ", AcctType=" + AccountType
            //		+ ", Sign=" + AccountSign + ", Doc=" + docControlled
            //		+ ", Summary=" + summary + " - " + Name + " - " + Description);

            try
            {
                //	Try to find - allows to use same natutal account for multiple default accounts
                MElementValue na = null;
                if (m_valueMap.ContainsKey(Value))
                {
                    na = (MElementValue)m_valueMap[Value];
                }
                if (na == null)
                {
                    //  Create Account - save later
                    na = new MElementValue(m_ctx, Value, Name, Description, AccountType, AccountSign, IsDocControlled.ToUpper().StartsWith("Y"), IsSummary.ToUpper().StartsWith("Y"), m_trx);
                    int refElementID = Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT C_ElementValue_ID FROM C_ElementValue
                                                                                    WHERE IsActive='Y' AND AD_Client_ID=" + na.GetAD_Client_ID() + " AND Value='" + accountParent + @"'
                                                                                    AND C_Element_ID=" + C_Element_ID, null, m_trx));
                    na.SetRef_C_ElementValue_ID(refElementID);
                    m_valueMap[Value] = na;
                    na.SetAD_Client_ID(AD_Client_ID);
                    na.SetAD_Org_ID(AD_Org_ID);
                    na.SetC_Element_ID(C_Element_ID);
                    na.SetVIS_DefaultAccount(Default_Account);
                    if (!na.Save(m_trx))
                    {
                        return("Acct Element Values NOT inserted");
                        //m_info.Append(Msg.Translate(m_lang, "C_ElementValue_ID")).Append(" # ").Append(m_nap.Count).Append("\n");
                    }
                    VAdvantage.Model.MTreeNode mNode = VAdvantage.Model.MTreeNode.Get(tree, na.Get_ID());
                    if (mNode == null)
                    {
                        mNode = new VAdvantage.Model.MTreeNode(tree, na.Get_ID());
                    }
                    ((VAdvantage.Model.PO)mNode).Set_Value("Parent_ID", refElementID);
                    if (!mNode.Save(m_trx))
                    {
                        return("Acct Element Values NOT inserted");
                    }
                }

                if (!(Default_Account == null || Default_Account.Length == 0))
                {
                    //  Add to Cache
                    s_base.Add(Default_Account.ToUpper(), na);
                }
            }
            catch (Exception e)
            {
                return(e.Message);
            }

            return("");
        }   //
Exemplo n.º 22
0
        }   //  parseLine

        public String ParseFile(FileStream file, int AD_Client_ID, int AD_Org_ID, int C_Element_ID, MTree tree)
        {
            //log.Config(file.Name);
            String line = null;

            try
            {
                //  see FileImport
                FileStream   fs  = file; // new FileStream("E:\\FrameworkLive\\Framework\\bin\\Debug\\data\\import\\AccountingUS.csv", FileMode.Open);
                StreamReader inn = new StreamReader(fs);
                //	not safe see p108 Network pgm
                String errMsg = "";

                //  read lines
                while ((line = inn.ReadLine()) != null && errMsg.Length == 0)
                {
                    errMsg = ParseAndSaveLine(line, AD_Client_ID, AD_Org_ID, C_Element_ID, tree);
                }
                line = "";
                inn.Close();

                //  Error
                if (errMsg.Length != 0)
                {
                    return(errMsg);
                }
            }
            catch (Exception ioe)
            {
                String s = ioe.Message;
                if (s == null || s.Length == 0)
                {
                    s = ioe.ToString();
                }
                return("Parse Error: Line=" + line + " - " + s);
            }
            return("");
        }   //  parse
Exemplo n.º 23
0
        static void Main(string[] args)
        {
            var mtreeStopwatch     = new Stopwatch();
            var fastMtreeStopWatch = new Stopwatch();

            var originalTimes = new List <long>();
            var fastTimes     = new List <long>();

            var dataSize     = 100000;
            var testDataSize = 50;
            var range        = 1000000;
            var neighbors    = 10;
            var dimensions   = 1000;

            Console.WriteLine($"{nameof(dataSize)}: {dataSize}");
            Console.WriteLine($"{nameof(dimensions)}: {dimensions}");
            Console.WriteLine($"{nameof(neighbors)}: {neighbors}");
            Console.WriteLine();

            var testData = Supercluster.Tests.Utilities.GenerateDoubles(testDataSize, range, dimensions);

            for (int index = 0; index < testData.Length; index++)
            {
                var treeData = Supercluster.Tests.Utilities.GenerateDoubles(dataSize, range, dimensions);
                var target   = testData[index];


                // 1. Build Trees
                var fastMtree = new FastMTree <double[]> {
                    Capacity = 3, Metric = Metrics.L2Norm_Double
                };
                foreach (var point in treeData)
                {
                    fastMtree.Add(point);
                }


                var mtree = new MTree <double[]> {
                    Capacity = 3, Metric = Metrics.L2Norm_Double
                };
                foreach (var point in treeData)
                {
                    mtree.Add(point);
                }

                GC.Collect();
                GCLatencyMode oldMode = GCSettings.LatencyMode;

                // Make sure we can always go to the catch block,
                // so we can set the latency mode back to `oldMode`
                RuntimeHelpers.PrepareConstrainedRegions();

                try
                {
                    GCSettings.LatencyMode = GCLatencyMode.LowLatency;

                    // Measure Trees
                    mtreeStopwatch.Start();
                    var resultsList = mtree.NearestNeighbors(target, neighbors).ToArray();
                    mtreeStopwatch.Stop();

                    fastMtreeStopWatch.Start();
                    var fastResults = fastMtree.NearestNeighbors(target, neighbors).ToArray();
                    fastMtreeStopWatch.Stop();

                    // Generation 2 garbage collection is now
                    // deferred, except in extremely low-memory situations
                }
                finally
                {
                    // ALWAYS set the latency mode back
                    GCSettings.LatencyMode = oldMode;
                }


                // Print times
                if (index != 0) // We skip first run because of jitting
                {
                    // Record Times
                    originalTimes.Add(mtreeStopwatch.ElapsedTicks);
                    fastTimes.Add(fastMtreeStopWatch.ElapsedTicks);
                    Console.WriteLine(mtreeStopwatch.ElapsedTicks + " " + fastMtreeStopWatch.ElapsedTicks);
                }

                // reset stopwatches
                mtreeStopwatch.Reset();
                fastMtreeStopWatch.Reset();
            }

            Console.WriteLine("Average: " + originalTimes.Average() + " " + fastTimes.Average());
            Console.Read();
        }
        protected override string DoIt()
        {
            string extension = filename;
            string path      = HostingEnvironment.ApplicationPhysicalPath;

            if (filename.Contains("_FileCtrl"))
            {
                path = path + "TempDownload//" + filename;
                if (Directory.Exists(path))
                {
                    string[] files = Directory.GetFiles(path);
                    if (files != null && files.Length > 0)
                    {
                        filename = "//" + Path.GetFileName(files[0]);
                    }
                }
                else
                {
                    _message = Msg.GetMsg(GetCtx(), "PathNotExist");
                    return(_message);
                }
            }

            int ind = filename.LastIndexOf(".");

            extension = filename.Substring(ind, filename.Length - ind);

            int client = Util.GetValueOfInt(GetAD_Client_ID());
            int user   = GetAD_User_ID();

            sql = "select ad_tree_id from c_element where c_element_id = " + C_Elememt_ID + " and ad_client_id = " + client;
            int   ad_tree_id = 0;
            MTree tree       = null;

            try
            {
                ad_tree_id = Util.GetValueOfInt(DB.ExecuteScalar(sql));
                tree       = new MTree(GetCtx(), ad_tree_id, null);
            }
            catch
            {
                ad_tree_id = 0;
            }
            if (ad_tree_id == 0)
            {
                _message = Msg.GetMsg(GetCtx(), "TreeNotBind");
                return(_message);
            }

            //  if (extension.ToUpper() == ".XLSX" || extension.ToUpper() == ".XLS" || extension.ToUpper() == ".CSV")
            if (extension.ToUpper() == ".XLSX" || extension.ToUpper() == ".CSV")
            {
                try
                {
                    DataSet ds = ImportExcelXLS(path + filename, false);

                    System.Data.DataTable dt = null;
                    if (ds != null)
                    {
                        dt = ds.Tables[0];
                    }

                    if (dt != null && dt.Rows.Count > 0)
                    {
                        //if (ad_tree_id == 0)
                        //{
                        //    int tableID = Convert.ToInt32(DB.ExecuteScalar("select ad_table_id from ad_table where lower(tablename)='vactwz_elementvalue'"));

                        //    tree = new MTree(GetCtx(), 0, null);

                        //    tree.SetName(CreateName("AcctWiz"));


                        //    tree.SetAD_Table_ID(tableID);
                        //    //tree.SetTreeType("EV");
                        //    tree.Save();
                        //    ad_tree_id = tree.Get_ID();
                        //}
                        MElementValue eleValue = null;
                        string        key      = "";
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            key = Util.GetValueOfString(dt.Rows[i]["(Account_Value)"]);
                            if (key != "")
                            {
                                sql = " SELECT c_elementvalue_id FROM c_elementvalue WHERE IsActive='Y' AND C_ELEMENT_ID=" + C_Elememt_ID + " AND value = '" + key + "' AND ad_client_id = " + client;
                                int C_ElementValue_ID = 0;
                                try
                                {
                                    C_ElementValue_ID = Util.GetValueOfInt(DB.ExecuteScalar(sql));
                                }
                                catch
                                {
                                    C_ElementValue_ID = 0;
                                }

                                eleValue = new MElementValue(GetCtx(), C_ElementValue_ID, null);

                                string parent_ID = Util.GetValueOfString(dt.Rows[i]["(Account_Parent)"]);
                                sql = "SELECT c_elementvalue_id FROM c_elementvalue WHERE IsActive='Y' AND C_Element_ID=" + C_Elememt_ID + " AND value = '" + parent_ID + "' AND ad_client_id = " + client;
                                int C_ElementValue_ID_Parent = Util.GetValueOfInt(DB.ExecuteScalar(sql));
                                try
                                {
                                    C_ElementValue_ID_Parent = Util.GetValueOfInt(DB.ExecuteScalar(sql));
                                }
                                catch
                                {
                                    C_ElementValue_ID_Parent = 0;
                                }
                                //eleValue = new MElementValue(GetCtx(), 0, null);
                                //int C_ElementValue_ID = DB.GetNextID(GetAD_Client_ID(), "VACTWZ_ELEMENTVALUE", null);
                                string accSign = Util.GetValueOfString(dt.Rows[i]["(Account_Sign)"]);
                                if (accSign == "")
                                {
                                    eleValue.SetAccountSign("N");
                                }
                                else
                                {
                                    eleValue.SetAccountSign(accSign);
                                }
                                eleValue.SetC_Element_ID(C_Elememt_ID);
                                // eleValue.SetC_ElementValue_ID(C_ElementValue_ID);
                                eleValue.SetValue(Util.GetValueOfString(dt.Rows[i]["(Account_Value)"]));
                                eleValue.SetName(Util.GetValueOfString(dt.Rows[i]["(Account_Name)"]));
                                eleValue.SetDescription(Util.GetValueOfString(dt.Rows[i]["(Account_Description)"]));
                                eleValue.SetIsActive(true);
                                // For Summary
                                if (dt.Rows[i]["(Account_Summary)"].ToString().ToUpper() == "YES")
                                {
                                    eleValue.SetIsSummary(true);
                                }
                                else
                                {
                                    eleValue.SetIsSummary(false);
                                }
                                //For DefaultAccount
                                if (dt.Rows[i]["(Account_Document)"].ToString().ToUpper() == "YES")
                                {
                                    ///******************** Commented
                                    eleValue.SetIsDefault(true);
                                }
                                else
                                {
                                    ///******************** Commented
                                    eleValue.SetIsDefault(false);
                                }
                                //for MasterType
                                if (!string.IsNullOrEmpty(Util.GetValueOfString(dt.Rows[i]["(Master_Type)"])))
                                {
                                    eleValue.SetMasterAccountType(dt.Rows[i]["(Master_Type)"].ToString());
                                }

                                //For Primary Group
                                string primaryGroup = dt.Rows[i]["(Primary_Group)"].ToString();
                                if (!string.IsNullOrEmpty(primaryGroup))
                                {
                                    int primaryGroupID = Util.GetValueOfInt(DB.ExecuteScalar("select c_accountgroup_id from c_accountgroup where value='" + primaryGroup + "' AND AD_CLient_ID=" + GetCtx().GetAD_Client_ID()));
                                    if (primaryGroupID > 0)
                                    {
                                        eleValue.SetC_AccountGroup_ID(primaryGroupID);
                                    }

                                    //try
                                    //{
                                    //    eleValue.SetRef_C_AccountGroup_ID(Util.GetValueOfInt(primaryGroup));
                                    //}
                                    //catch { }
                                }
                                //For PrimarySub Group
                                string primarysubGroup = dt.Rows[i]["(Primary_Sub_Group)"].ToString();
                                if (!string.IsNullOrEmpty(primarysubGroup))
                                {
                                    int primarysubGroupID = Util.GetValueOfInt(DB.ExecuteScalar("select c_accountsubgroup_id from c_accountsubgroup where value='" + primarysubGroup + "' AND AD_CLient_ID=" + GetCtx().GetAD_Client_ID()));
                                    if (primarysubGroupID > 0)
                                    {
                                        eleValue.SetC_AccountSubGroup_ID(primarysubGroupID);
                                    }

                                    //eleValue.SetRef_C_AccountSubGroup_ID(Util.GetValueOfInt(primarysubGroup));
                                    //try
                                    //{
                                    //    eleValue.SetRef_C_AccountSubGroup_ID(Util.GetValueOfInt(primarysubGroup));
                                    //}
                                    //catch { }
                                }


                                // For Account Type
                                if (Util.GetValueOfString(dt.Rows[i]["(Account_Type)"]).ToUpper() == "ASSET")
                                {
                                    eleValue.SetAccountType("A");
                                }
                                else if (Util.GetValueOfString(dt.Rows[i]["(Account_Type)"]).ToUpper() == "LIABILITY")
                                {
                                    eleValue.SetAccountType("L");
                                }
                                else if (Util.GetValueOfString(dt.Rows[i]["(Account_Type)"]).ToUpper() == "OWNER'S EQUITY")
                                {
                                    eleValue.SetAccountType("O");
                                }
                                else if (Util.GetValueOfString(dt.Rows[i]["(Account_Type)"]).ToUpper() == "REVENUE")
                                {
                                    eleValue.SetAccountType("R");
                                }
                                else if (Util.GetValueOfString(dt.Rows[i]["(Account_Type)"]).ToUpper() == "EXPENSE")
                                {
                                    eleValue.SetAccountType("E");
                                }
                                else
                                {
                                    eleValue.SetAccountType("M");
                                }


                                //string memo = dt.Rows[i]["(Memo_Ledger)"].ToString();
                                //if (dt.Rows[i]["(Memo_Ledger)"] != null && dt.Rows[i]["(Memo_Ledger)"] != DBNull.Value)
                                //{
                                //    try
                                //    {
                                //        eleValue.SetRef_C_ElementValue_ID(Util.GetValueOfInt(memo));
                                //    }
                                //    catch { }
                                //}
                                //eleValue.SetParent_ID(C_ElementValue_ID_Parent);
                                if (!string.IsNullOrEmpty(parent_ID))
                                {
                                    ///******************** Commented
                                    //eleValue.SetParentSerachKey(parent_ID.ToString());
                                }



                                if (!eleValue.Save())
                                {
                                    log.SaveError("NotSaved", "");

                                    //return msg;
                                }
                                VAdvantage.Model.MTree obj = new VAdvantage.Model.MTree(GetCtx(), ad_tree_id, null);
                                //C_ElementValue_ID = C_ElementValue_ID + 1;
                                VAdvantage.Model.MTreeNode mNode = VAdvantage.Model.MTreeNode.Get(obj, eleValue.Get_ID());
                                if (mNode == null)
                                {
                                    mNode = new VAdvantage.Model.MTreeNode(tree, eleValue.Get_ID());
                                }
                                mNode.SetParent_ID(C_ElementValue_ID_Parent);
                                // ((PO)mNode).Set_Value("Parent_ID", C_ElementValue_ID_Parent);
                                if (!mNode.Save())
                                {
                                    log.SaveError("NodeNotSaved", "");
                                    return(msg);
                                }
                            }
                            else
                            {
                            }
                        }
                        /////////Set Memo Ledger
                        //int tempElementID = 0;
                        //for (int i = 0; i < dt.Rows.Count; i++)
                        //{
                        //    if (dt.Rows[i]["(Memo_Ledger)"] != null && dt.Rows[i]["(Memo_Ledger)"] != DBNull.Value)
                        //    {
                        //        if (!(string.IsNullOrEmpty(dt.Rows[i]["(Memo_Ledger)"].ToString())))
                        //        {
                        //            refElementValID = Util.GetValueOfInt(DB.ExecuteScalar("Select vactwz_elementvalue_ID from vactwz_elementvalue WHERE Value='" + dt.Rows[i]["(Memo_Ledger)"] + "'"));
                        //            if (refElementValID > 0)
                        //            {
                        //                tempElementID = Util.GetValueOfInt(DB.ExecuteScalar("Select vactwz_elementvalue_ID from vactwz_elementvalue WHERE Value='" + dt.Rows[i]["(Account_Value)"] + "'"));
                        //                eleValue = new MElementValue(GetCtx(), tempElementID, null);
                        //                eleValue.SetRef_C_ElementValue_ID(refElementValID);
                        //                eleValue.Save();
                        //            }
                        //        }
                        //    }
                        //}

                        //******************** Commented
                        //if (tree != null)
                        //{
                        //    sql = "Update C_Element SET TreeID=" + tree.Get_ID() + " WHERE C_Element_ID=" + C_Elememt_ID;
                        //    DB.ExecuteQuery(sql);
                        //}

                        if (path.Contains("_FileCtrl"))
                        {
                            Directory.Delete(path, true);
                        }
                    }

                    msg = Msg.GetMsg(GetCtx(), "ImportedSuccessfully");
                    return(msg);
                }
                catch
                {
                    if (_message != "")
                    {
                        msg = _message;
                    }
                    else
                    {
                        msg = Msg.GetMsg(GetCtx(), "ExcelSheetNotInProperFormat");
                    }
                    return(msg);
                }
            }
            else
            {
                msg = Msg.GetMsg(GetCtx(), "UseDefaultExcelSheet");
                return(msg);
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="AD_Tree_ID"></param>
        /// <param name="editable"></param>
        /// <returns></returns>

        public MTree GetMenuTree(int AD_Tree_ID, bool editable)
        {
            MTree vTree = new MTree(_ctx, AD_Tree_ID, editable, true, null);

            return(vTree);
        }
        public GridReportInfo GenerateReport(Ctx _ctx, int id, List <string> queryInfo, Object code, bool isCreateNew, Dictionary <string, string> nProcessInfo, int pageNo, int AD_PInstance_ID, string fileType, int?nodeID, int?treeID, bool showSummary)
        {
            GridReportInfo res = new GridReportInfo();

            VIS.Models.PageSetting ps = new Models.PageSetting();
            parentIDs.Clear();
            ProcessReportInfo rep    = null;
            ReportEngine_N    re     = null;
            Query             _query = null;
            int    Record_ID         = 0;
            object AD_tab_ID         = 0;

            // _ctx.SetContext("#TimeZoneName", "India Standard Time");
            if (queryInfo.Count > 0 || AD_PInstance_ID > 0)
            {
                string tableName = queryInfo[0];
                if (AD_PInstance_ID > 0)
                {
                    if ((code).GetType() == typeof(int))        //	Form = one record
                    {
                        _query = Query.GetEqualQuery(tableName, ((int)code));
                    }
                    else
                    {
                        _query = Query.Get(_ctx, AD_PInstance_ID, tableName);
                    }
                }
                else
                {
                    string wherClause = queryInfo[1];
                    _query = new Query(tableName);

                    if (!string.IsNullOrEmpty(wherClause))
                    {
                        _query.AddRestriction(wherClause);
                    }
                }

                if (_query.GetRestrictionCount() == 1 && (code).GetType() == typeof(int))
                {
                    Record_ID = ((int)code);
                }

                if (nodeID > 0)
                {
                    GetChildNodesID(_ctx, Convert.ToInt32(nodeID), Convert.ToInt32(treeID));
                    MTree  tree          = new MTree(_ctx, Convert.ToInt32(treeID), null);
                    string nodeTableName = tree.GetNodeTableName();
                    _query.AddRestriction(" " + tableName + "." + tableName + "_ID  IN (SELECT NODE_ID FROM " + nodeTableName + "  WHERE Parent_ID IN (" + parentIDs.ToString() + ") OR NODE_ID IN (" + parentIDs + ")) ");

                    if (!showSummary)
                    {
                        _query.AddRestriction(" " + tableName + "." + "IsSummary= 'N'");
                    }
                }
            }
            else
            {
                if (nodeID > 0)
                {
                    MTree  tree      = new MTree(_ctx, Convert.ToInt32(treeID), null);
                    string tableName = MTable.GetTableName(_ctx, tree.GetAD_Table_ID());

                    _query = new Query(tableName);

                    GetChildNodesID(_ctx, Convert.ToInt32(nodeID), Convert.ToInt32(treeID));
                    string nodeTableName = tree.GetNodeTableName();
                    _query.AddRestriction(" " + tableName + "." + tableName + "_ID  IN (SELECT NODE_ID FROM " + nodeTableName + "  WHERE Parent_ID IN (" + parentIDs.ToString() + ")) ");


                    if (!showSummary)
                    {
                        _query.AddRestriction(" " + tableName + "." + "IsSummary= 'N'");
                    }
                }
            }

            if (_query == null)
            {
                _query = new Query();
                _query.AddRestriction(" 1 = 1");
            }



            if (queryInfo.Count > 2)
            {
                if (queryInfo[2] != null && queryInfo[2] != "" && Convert.ToInt32(queryInfo[2]) > 0)
                {
                    AD_tab_ID = Convert.ToInt32(queryInfo[2]);
                }
            }
            //Context _ctx = new Context(ctxDic);
            //Env.SetContext(_ctx);
            string lang = _ctx.GetAD_Language().Replace("_", "-");


            System.Globalization.CultureInfo original = System.Threading.Thread.CurrentThread.CurrentCulture;

            System.Threading.Thread.CurrentThread.CurrentCulture   = new System.Globalization.CultureInfo(lang);
            System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(lang);



            byte[] b = null;
            try
            {
                MPrintFormat pf = null;

                if (!isCreateNew)
                {
                    bool isPFExist = Util.GetValueOfInt(DB.ExecuteScalar("SELECT Count(*) FROM AD_PrintFormat WHERE AD_PrintFormat_ID=" + id)) > 0;
                    if (isPFExist)
                    {
                        pf = MPrintFormat.Get(_ctx, id, true);
                    }
                    else
                    {
                        rep           = new ProcessReportInfo();
                        rep.ErrorText = "NoDocPrintFormat";
                        res.repInfo   = rep;
                        return(res);
                    }
                }
                else
                {
                    //   pf = MPrintFormat.CreateFromTable(_ctx, id);
                    if (Convert.ToInt32(AD_tab_ID) > 0)
                    {
                        pf = MPrintFormat.CreateFromTable(_ctx, id, AD_tab_ID, true);
                    }
                    else
                    {
                        pf = MPrintFormat.CreateFromTable(_ctx, id, true);
                    }
                }

                pf.IsGridReport = true;
                pf.PageNo       = pageNo;



                rep = new ProcessReportInfo();
                pf.SetName(Env.TrimModulePrefix(pf.GetName()));
                if (nProcessInfo == null || pageNo > 0 || (Util.GetValueOfInt(nProcessInfo["Record_ID"]) == 0 && Util.GetValueOfInt(nProcessInfo["Process_ID"]) == 0 &&
                                                           Util.GetValueOfInt(nProcessInfo["AD_PInstance_ID"]) == 0))
                {
                    PrintInfo info = new PrintInfo(pf.GetName(), pf.GetAD_Table_ID(), Record_ID);
                    info.SetDescription(_query == null ? "" : _query.GetInfo());
                    re = new ReportEngine_N(_ctx, pf, _query, info);
                }
                else
                {
                    ProcessInfo pi = new ProcessInfo().FromList(nProcessInfo);
                    pi.Set_AD_PrintFormat_ID(id);
                    ProcessCtl ctl = new ProcessCtl();
                    ctl.Process(pi, _ctx, out b, out re);
                    re.SetPrintFormat(pf);
                }
                lock (_lock)
                {
                    re.GetView();
                    if (fileType == ProcessCtl.ReportType_PDF)
                    {
                        rep.ReportFilePath = re.GetReportFilePath(true, out b);
                    }
                    else if (fileType == ProcessCtl.ReportType_CSV)
                    {
                        rep.ReportFilePath = re.GetCSVPath(_ctx);
                    }
                    else
                    {
                        rep.ReportFilePath    = re.GetReportFilePath(true, out b);
                        rep.HTML              = re.GetRptHtml().ToString();
                        rep.AD_PrintFormat_ID = re.GetPrintFormat().GetAD_PrintFormat_ID();
                        rep.ReportProcessInfo = null;
                        rep.Report            = re.CreatePDF();
                    }
                }

                ps.TotalPage   = pf.TotalPage;
                ps.CurrentPage = pageNo;
                // b = re.CreatePDF();
                //rep.Report = b;
                //rep.HTML = re.GetRptHtml().ToString();
                //rep.AD_PrintFormat_ID = re.GetPrintFormat().GetAD_PrintFormat_ID();
                //rep.ReportProcessInfo = null;
            }
            catch (Exception ex)
            {
                rep.IsError   = true;
                rep.ErrorText = ex.Message;
                log.Severe("ReportEngine_N_CreatePDF_" + ex.ToString());
            }
            //      VAdvantage.Classes.CleanUp.Get().Start();
            res.repInfo  = rep;
            res.pSetting = ps;
            return(res);
        }
Exemplo n.º 27
0
 void InitializeTree()
 {
     MtreeVersion = MtreeVariables.MtreeVersion;
     tree         = new MTree(transform);
 }
Exemplo n.º 28
0
 public void ListTree()
 {
     MTree.ListMergeTree();
 }
Exemplo n.º 29
0
        }       //	doIt

        /// <summary>
        /// Verify Tree
        /// </summary>
        /// <param name="tree">tree</param>
        /// <returns>message</returns>
        private String VerifyTree(MTree tree)
        {
            if (tree.GetAD_Table_ID(true) == 0)
            {
                tree.UpdateTrees();
            }
            String nodeTableName   = tree.GetNodeTableName();
            String sourceTableName = tree.GetSourceTableName(true);
            String sourceTableKey  = sourceTableName + "_ID";
            int    AD_Client_ID    = tree.GetAD_Client_ID();
            int    C_Element_ID    = 0;

            if (MTree.TREETYPE_ElementValue.Equals(tree.GetTreeType()))
            {
                String sql = "SELECT C_Element_ID FROM C_Element "
                             + "WHERE AD_Tree_ID=" + tree.GetAD_Tree_ID();
                C_Element_ID = DataBase.DB.GetSQLValue(null, sql);
                if (C_Element_ID <= 0)
                {
                    throw new Exception("No Account Element found");
                }
            }

            //	Delete unused
            StringBuilder sql1 = new StringBuilder();

            sql1.Append("DELETE FROM ").Append(nodeTableName)
            .Append(" WHERE AD_Tree_ID=").Append(tree.GetAD_Tree_ID())
            .Append(" AND Node_ID NOT IN (SELECT ").Append(sourceTableKey)
            .Append(" FROM ").Append(sourceTableName)
            .Append(" WHERE AD_Client_ID IN (0,").Append(AD_Client_ID).Append(")");
            if (C_Element_ID > 0)
            {
                sql1.Append(" AND C_Element_ID=").Append(C_Element_ID);
            }
            sql1.Append(")");
            log.Finer(sql1.ToString());
            //
            int deletes = DataBase.DB.ExecuteQuery(sql1.ToString(), null, Get_Trx());

            AddLog(0, null, new Decimal(deletes), tree.GetName() + " Deleted");
            if (!tree.IsAllNodes())
            {
                return(tree.GetName() + " OK");
            }

            //	Insert new
            int           inserts = 0;
            StringBuilder sql2    = new StringBuilder();

            sql2.Append("SELECT ").Append(sourceTableKey)
            .Append(" FROM ").Append(sourceTableName)
            .Append(" WHERE AD_Client_ID IN (0,").Append(AD_Client_ID).Append(")");
            if (C_Element_ID > 0)
            {
                sql2.Append(" AND C_Element_ID=").Append(C_Element_ID);
            }
            sql2.Append(" AND ").Append(sourceTableKey)
            .Append("  NOT IN (SELECT Node_ID FROM ").Append(nodeTableName)
            .Append(" WHERE AD_Tree_ID=").Append(tree.GetAD_Tree_ID()).Append(")")
            .Append(" ORDER BY Upper(name)");
            log.Finer(sql2.ToString());
            //
            Boolean     ok  = true;
            IDataReader idr = null;

            //PreparedStatement pstmt = null;
            try
            {
                //pstmt = DataBase.prepareStatement(sql.toString(), Get_Trx());
                //ResultSet rs = pstmt.executeQuery();
                idr = DataBase.DB.ExecuteReader(sql2.ToString(), null, Get_Trx());

                //Manish 8/06/2016

                int setSeqManually = -1;

                //End

                while (idr.Read())
                {
                    int Node_ID = Utility.Util.GetValueOfInt(idr[0]);// rs.getInt(1);
                    PO  node    = null;
                    if (nodeTableName.Equals("AD_TreeNode"))
                    {
                        // node = new MTreeNode(tree, Node_ID);

                        //Manish
                        setSeqManually += 1;
                        node            = new MTreeNode(tree, Node_ID, setSeqManually);
                        //end
                    }
                    else if (nodeTableName.Equals("AD_TreeNodeBP"))
                    {
                        //node = new MTreeNodeBP(tree, Node_ID);

                        //Manish
                        setSeqManually += 1;
                        node            = new MTreeNodeBP(tree, Node_ID, setSeqManually);
                        //end
                    }
                    else if (nodeTableName.Equals("AD_TreeNodePR"))
                    {
                        //node = new MTreeNodePR(tree, Node_ID);

                        //Manish
                        setSeqManually += 1;
                        node            = new MTreeNodePR(tree, Node_ID, setSeqManually);
                        //end
                    }
                    else if (nodeTableName.Equals("AD_TreeNodeCMC"))
                    {
                        //node = new MTreeNodeCMC(tree, Node_ID);

                        //Manish
                        setSeqManually += 1;
                        node            = new MTreeNodeCMC(tree, Node_ID, setSeqManually);
                        //end
                    }
                    else if (nodeTableName.Equals("AD_TreeNodeCMM"))
                    {
                        //node = new MTreeNodeCMM(tree, Node_ID);

                        //Manish
                        setSeqManually += 1;
                        node            = new MTreeNodeCMM(tree, Node_ID, setSeqManually);
                        //end
                    }
                    else if (nodeTableName.Equals("AD_TreeNodeCMS"))
                    {
                        // node = new MTreeNodeCMS(tree, Node_ID);

                        //Manish
                        setSeqManually += 1;
                        node            = new MTreeNodeCMS(tree, Node_ID, setSeqManually);
                        //end
                    }
                    else if (nodeTableName.Equals("AD_TreeNodeCMT"))
                    {
                        //node = new MTreeNodeCMT(tree, Node_ID);

                        //Manish
                        setSeqManually += 1;
                        node            = new MTreeNodeCMT(tree, Node_ID, setSeqManually);
                        //end
                    }
                    else if (nodeTableName.Equals("AD_TreeNodeMM"))
                    {
                        // node = new MTreeNodeMM(tree, Node_ID);

                        //Manish
                        setSeqManually += 1;
                        node            = new MTreeNodeMM(tree, Node_ID, setSeqManually);
                        //end
                    }

                    if (node == null)
                    {
                        log.Log(Level.SEVERE, "No Model for " + nodeTableName);
                    }
                    else
                    {
                        if (node.Save())
                        {
                            inserts++;
                        }
                        else
                        {
                            log.Log(Level.SEVERE, "Could not add to " + tree + " Node_ID=" + Node_ID);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                log.Log(Level.SEVERE, sql2.ToString(), e);
                ok = false;
            }
            finally
            {
                idr.Close();
            }
            AddLog(0, null, new Decimal(inserts), tree.GetName() + " Inserted");
            return(tree.GetName() + (ok ? " OK" : " Error"));
        } //	verifyTree
Exemplo n.º 30
0
        }       //	GetSQLValue

        /**
         *  Tree Operation
         *	@param columnName columnName
         *	@param cmp compare value
         *	@param op operation (only == or !=)
         *	@param value user value
         *	@return null if n/a otherwise evaluation
         */
        private Boolean?TreeOperation(String columnName, int?cmp, String op, int value, int AD_Client_ID)
        {
            String tableName = null;

            //	Is this a Tree capable column
            if (columnName.EndsWith("_ID") &&
                (op.Equals(OPERATION_Eq) || op.Equals(OPERATION_NotEq)))
            {
                String temp = columnName;
                if (temp.EndsWith("_ID"))
                {
                    temp = columnName.Substring(0, columnName.Length - 3);
                }
                if (MTree.HasTree(temp, GetCtx()))
                {
                    tableName = temp;
                }
            }
            if (tableName == null)
            {
                return(null);
            }

            //	Is the value a Summary node
            StringBuilder sql = new StringBuilder("SELECT ").Append(columnName)
                                .Append(" FROM ").Append(tableName)
                                .Append(" WHERE ").Append(columnName).Append("=@param1 AND IsSummary='Y'");
            int id = DataBase.DB.GetSQLValue(null, sql.ToString(), Utility.Util.GetValueOfInt(cmp));

            if (id <= 0)
            {
                return(null);
            }

            //	Get Tree
            int AD_Tree_ID = MTree.GetDefaultAD_Tree_ID(AD_Client_ID, tableName);

            if (AD_Tree_ID <= 0)
            {
                return(null);
            }

            MTree tree = new MTree(GetCtx(), AD_Tree_ID, false, true, null);

            //VTreeNode node = tree.GetRootNode().findNode(id);
            //log.Finest("Root=" + node);
            //
            //if (node != null && node.IsSummary)
            //{
            //Enumeration<?> en = node.preorderEnumeration();
            //while (en.hasMoreElements())
            //{
            //    CTreeNode nn = (CTreeNode)en.nextElement();
            //    if (!nn.isSummary())
            //    {
            //        int cmp1 = nn.GetNode_ID();
            //        if (op.Equals(OPERATION_Eq))
            //        {
            //            if (value.Equals(cmp1))
            //                return Boolean.TRUE;
            //        }
            //        else if (op.Equals(OPERATION_NotEq))
            //        {
            //            if (!value.Equals(cmp1))
            //                return Boolean.TRUE;
            //        }
            //    }
            //}
            //}	//	tree elements
            return(false);
        }       //	treeOperation