Пример #1
0
        public static MeNode SanitizeMitigation(MeNode tree, Entity target, Entity caster, double amount)
        {
            List <MeNode> leaves = new List <MeNode>();

            foreach (MeNode leaf in tree.Leaves)
            {
                leaves.Add(SanitizeMitigation(leaf, caster, target, amount));
            }
            MeNode node = null;

            if (tree.Value.Type == VariableType.PlaceHolder)
            {
                if (tree.Value.ToPlaceholder().Equals(LConstants.TargetKeyword))
                {
                    node = new MeNode(target);
                }
                else if (tree.Value.ToPlaceholder().Equals(LConstants.SourceKeyword))
                {
                    node = new MeNode(caster);
                }
                else if (tree.Value.ToPlaceholder().Equals(LConstants.ValueKeyword))
                {
                    node = new MeNode(amount);
                }
            }
            else
            {
                node = new MeNode(tree.Value);
            }
            node.Leaves.AddRange(leaves);
            return(node);
        }
Пример #2
0
        public void EntityTestPropertyTypeUpdatesWithFunction()
        {
            //initial test
            string strKey            = "STR";
            string expression        = $"{LConstants.GET_PROP_F}({BaseEntity.Key},{strKey})";
            double expected          = BaseEntity.GetProperty(strKey).Value;
            MeNode tree              = TreeConverter.Build(expression, Engine);
            MeNode partiallyResolved = TreeResolver.ResolveGivenOperations(tree, new string[1] {
                LConstants.GET_PROP_F
            });

            Assert.AreEqual(expected, partiallyResolved.Value.ToDouble());

            //apply a status that modifies the value
            string expression2 = $"{LConstants.ADD_MOD_F}(STR,$0)";

            MeNode[]       statuses = Engine.GetSanitizer().SplitAndConvert(expression2);
            StatusTemplate test     = new StatusTemplate(statuses)
            {
                Interval = TreeConverter.Build("0", Engine)
            };

            test.Key = "TEST_STATUS_KEY33";
            double[] values = { 10 };

            BaseEntity.ApplyStatus(test, BaseEntity, 10, values);
            BaseEntity.Update();

            //test again
            expected = BaseEntity.GetProperty(strKey).Value;
            Assert.AreEqual(expected, partiallyResolved.Value.ToDouble());

            BaseEntity.Cleanse();
        }
Пример #3
0
        public void CastTestPushbackChannelSkill()
        {
            long       delay = 10;
            BaseEntity mob   = new MockEntity(Engine);

            double expectedMobHealth = mob.GetProperty(Entity.HP_KEY).Value - 50;

            _testPlayer.Cast(mob, _testChannelSkill.Key);
            _testPlayer.AddPushback(delay);

            MockTimer timer = (MockTimer)Engine.GetTimer();

            MeNode duration = _testChannelSkill.ByLevel[0].Duration;

            duration = Sanitizer.ReplaceTargetAndSource(duration, _testPlayer, _testPlayer);
            long skillDuration = duration.Resolve().Value.ToLong();

            for (int i = 0; i < skillDuration; ++i)
            {
                timer.ForceTick();
                _testPlayer.Update();
                mob.Update();
            }

            timer.ForceTick();
            _testPlayer.Update();
            mob.Update();
            Assert.AreEqual(expectedMobHealth, mob.GetProperty(Entity.HP_KEY).Value);
        }
Пример #4
0
        public MeVariable ResolveStatus(MeNode tree, double[] values)
        {
            Dictionary <string, double> valueMap = GetNumericValueMap(values);

            ReplaceNumericPlaceholders(tree, valueMap);
            return(TreeResolver.Resolve(tree).Value);
        }
Пример #5
0
        public void CastTestNonInterrupt()
        {
            BaseEntity mob = new MockEntity(Engine);


            double expectedMobHealth = mob.GetProperty(Entity.HP_KEY).Value - 10;

            _testPlayer.Cast(mob, _unpushable.Key);
            _testPlayer.InterruptCasting();

            MockTimer timer = (MockTimer)Engine.GetTimer();

            MeNode duration = _unpushable.ByLevel[0].Duration;

            duration = Sanitizer.ReplaceTargetAndSource(duration, _testPlayer, _testPlayer);
            long skillDuration = duration.Resolve().Value.ToLong();

            for (int i = 0; i < skillDuration; ++i)
            {
                timer.ForceTick();
            }

            timer.ForceTick();
            _testPlayer.Update();
            Assert.AreEqual(expectedMobHealth, mob.GetProperty(Entity.HP_KEY).Value);
        }
Пример #6
0
        public static MeNode ReplacePropeties(MeNode tree, Entity origin)
        {
            List <MeNode> leaves = new List <MeNode>();

            foreach (MeNode leaf in tree.Leaves)
            {
                leaves.Add(ReplacePropeties(leaf, origin));
            }
            MeNode node = null;

            if (tree.Value.Type == VariableType.String && origin.HasProperty(tree.Value.ToMeString()))
            {
                MeNode[] nodeLeaves = new MeNode[2] {
                    new MeNode(origin), tree
                };
                Operator prop = Definer.Instance().Operators[LConstants.PROP_OP];
                node = new MeNode(new MeVariable()
                {
                    Type = VariableType.Operator, Value = prop
                });
                node.Leaves.AddRange(nodeLeaves);
            }
            else
            {
                node = new MeNode(tree.Value);
            }
            node.Leaves.AddRange(leaves);
            return(node);
        }
Пример #7
0
        private void AddStatusFromTemplate(StatusTemplate status, Entity source, double duration, double[] values)
        {
            long          removeTime = GetRemoveTime(duration);
            AppliedStatus newStatus  = new AppliedStatus()
            {
                Source = source, LastTick = 0, RemovalTime = removeTime, Template = status, NumericValues = values
            };

            MeNode intervalTree = Sanitizer.ReplaceTargetAndSource(status.Interval, source, this);

            newStatus.Interval = intervalTree.Resolve().Value.ToLong();
            Statuses.Add(newStatus);
            foreach (MeNode tree in newStatus.Template.Modifiers)
            {
                StatModifier mod = Engine.GetSanitizer().ResolveStatus(tree, newStatus.NumericValues).ToModifier();
                newStatus.MyMods.Add(mod);
                Attributes[mod.StatKey].Modifiers.Add(mod);
            }
            RefreshProperties();
            int stackCount = 0;

            foreach (AppliedStatus sts in Statuses)
            {
                if (sts.Template.Key.Equals(newStatus.Template.Key))
                {
                    ++stackCount;
                }
            }
            Engine.Log().Log($"[{Name}] Affected by {status.Name}[{stackCount}].");
        }
Пример #8
0
        public static MeNode ReplaceExpValues(MeNode tree, double prev, long level)
        {
            List <MeNode> leaves = new List <MeNode>();

            foreach (MeNode leaf in tree.Leaves)
            {
                leaves.Add(ReplaceExpValues(leaf, prev, level));
            }
            MeNode node;

            if (tree.Value.Type == VariableType.PlaceHolder)
            {
                if (tree.Value.ToPlaceholder().Equals(LConstants.ExpPrevKeyword))
                {
                    node = new MeNode(prev);
                }
                else if (tree.Value.ToPlaceholder().Equals(LConstants.LevelKeyword))
                {
                    node = new MeNode(level);
                }
                else
                {
                    node = new MeNode(tree.Value);
                }
            }
            else
            {
                node = new MeNode(tree.Value);
            }
            node.Leaves.AddRange(leaves);

            return(node);
        }
Пример #9
0
        public void EntityTestHarmStatusIntervalIsFormula()
        {
            BaseEntity ent = new MockEntity(Engine)
            {
                Name = "MOCK_PLAYER", Key = "MOCK_KEY"
            };
            double damage     = 10;
            string expression = $"{LConstants.HARM_F}({LConstants.TargetKeyword},{LConstants.TargetKeyword},T,{damage})";

            MeNode[]       statuses           = Engine.GetSanitizer().SplitAndConvert(expression);
            string         intervalExpression = $"10-{LConstants.GET_PROP_F}({LConstants.SourceKeyword},INT)*2";
            MeNode         intervalNode       = TreeConverter.Build(intervalExpression, Engine);
            StatusTemplate test = new StatusTemplate(statuses)
            {
                Interval = intervalNode
            };

            test.Key = "TEST_STATUS_KEY2";
            ent.ApplyStatus(test, ent, 5, null);
            double    expectedHp  = ent.GetProperty(Entity.HP_KEY).Value - damage;
            double    expectedHp2 = ent.GetProperty(Entity.HP_KEY).Value - damage * 2;
            MockTimer timer       = (MockTimer)Engine.GetTimer();

            ent.Update();
            timer.ForceTick();
            Assert.AreEqual(expectedHp, ent.GetProperty(Entity.HP_KEY).Value);

            ent.Update();
            Assert.AreEqual(expectedHp2, ent.GetProperty(Entity.HP_KEY).Value);
        }
Пример #10
0
 public void ReplaceNumericPlaceholders(MeNode tree, double[] values)
 {
     if (values != null)
     {
         ReplaceNumericPlaceholders(tree, GetNumericValueMap(values));
     }
 }
Пример #11
0
        public static MeNode ReplaceTargetAndSource(MeNode tree, Entity caster, Entity target)
        {
            List <MeNode> leaves = new List <MeNode>();

            foreach (MeNode leaf in tree.Leaves)
            {
                leaves.Add(ReplaceTargetAndSource(leaf, caster, target));
            }
            MeNode node = null;

            if (tree.Value.Type == VariableType.PlaceHolder)
            {
                if (tree.Value.ToPlaceholder() == LConstants.TargetKeyword)
                {
                    node = new MeNode(target);
                }
                else if (tree.Value.ToPlaceholder() == LConstants.SourceKeyword)
                {
                    node = new MeNode(caster);
                }
                else
                {
                    node = new MeNode(tree.Value);
                }
            }
            else
            {
                node = new MeNode(tree.Value);
            }
            node.Leaves.Clear();
            node.Leaves.AddRange(leaves);
            return(node);
        }
Пример #12
0
        public void TreeResolverTestArrayProperty()
        {
            string expression = $"{LConstants.ARRAY_F}(10,11,12){LConstants.PROP_OP}{LConstants.ARR_LENGTH}";
            double expected   = 3;
            MeNode tree       = TreeConverter.Build(expression, Engine);
            MeNode result     = tree.Resolve();

            Assert.AreEqual(expected, result.Value.ToDouble());
        }
Пример #13
0
 public Entity(IGameEngine engine)
 {
     Engine         = engine;
     Attributes     = new Dictionary <string, EntityAttribute>();
     ResourceMap    = new Dictionary <string, ResourceInstance>();
     Stats          = new Dictionary <string, StatInstance>();
     BaseValueMap   = new Dictionary <string, BaseProperty>();
     ReviveDuration = new MeNode(0);
 }
Пример #14
0
        public void TreeResolverTestResolveOnlyFunctionsNamed()
        {
            string expression        = $"{LConstants.HARM_F}({MockPlayer.Key},{MockPlayer.Key},P,{LConstants.GET_PROP_F}({MockPlayer.Key},{LConstants.IF_F}({LConstants.GET_PROP_F}({MockPlayer.Key},STR) > {LConstants.GET_PROP_F}({MockPlayer.Key},AGI),STR,AGI)))";
            MeNode tree              = TreeConverter.Build(expression, Engine);
            MeNode partiallyResolved = TreeResolver.ResolveGivenOperations(tree, new string[1] {
                LConstants.GET_PROP_F
            });

            Assert.AreEqual(tree.Value.Type, partiallyResolved.Value.Type);
        }
Пример #15
0
        public DamageTypeTemplate(IGameEngine engine, string mitigation, string dodge, string crit, string critmod)
        {
            Mitigation = mitigation != null?TreeConverter.Build(mitigation, engine) : null;

            Dodge = dodge != null?TreeConverter.Build(dodge, engine) : null;

            CriticalChance = crit != null?TreeConverter.Build(crit, engine) : null;

            CriticalModifier = critmod != null?TreeConverter.Build(critmod, engine) : null;
        }
Пример #16
0
        public void TreeResolverTestEntityProperty()
        {
            string strKey     = "STR";
            string expression = $"{MockPlayer.Key}{LConstants.PROP_OP}{strKey}";
            double expected   = MockPlayer.GetProperty(strKey).Value;
            MeNode tree       = TreeConverter.Build(expression, Engine);
            MeNode result     = tree.Resolve();

            Assert.AreEqual(expected, result.Value.ToDouble());
        }
Пример #17
0
        public static ResourceTemplate getMockHP(IGameEngine engine)
        {
            MeNode           max   = TreeConverter.Build("VIT*20", engine);;
            MeNode           regen = TreeConverter.Build("0", engine);
            ResourceTemplate hp    = new ResourceTemplate();

            hp.Formula       = max;
            hp.RegenFormula  = regen;
            hp.Key           = Entity.HP_KEY;
            hp.RegenInterval = new MeNode(GcConstants.Resources.DEFAULT_INTERVAL);
            return(hp);
        }
Пример #18
0
        private void SetCurrentCD()
        {
            //set skill's cooldown]
            if (CurrentlyCasting == null)
            {
                return;
            }
            MeNode cd = CurrentlyCasting.Skill.Values().Cooldown;

            cd = Sanitizer.ReplaceTargetAndSource(cd, this, CurrentlyCasting.Target);
            CurrentlyCasting.Skill.CooldownFinishTime = Engine.GetTimer().GetFuture((long)cd.Resolve().Value.ToDouble());
        }
Пример #19
0
        public void VariableTestAssignOperatorWorks()
        {
            string varName    = "testVar";
            double number     = 3.14;
            string expression = $"{varName} {LConstants.ASSIGN_OP} {number}";
            MeNode tree       = TreeConverter.Build(expression, Engine);

            tree.Resolve();
            MeVariable result = Engine.GetVariable(varName);

            Assert.IsNotNull(result);
            Assert.AreEqual(number, result.ToDouble());
        }
Пример #20
0
        public void LevelingTestPowerOperator()
        {
            double prev = 500;

            for (int i = 0; i < 20; ++i)
            {
                MeNode ExpFormula = TreeConverter.Build($"{prev}+50*2^{LConstants.FLOOR_F}({i}/5.0)",
                                                        Engine);
                double res = ExpFormula.Resolve().Value.ToDouble();
                double exp = prev + 50 * Math.Pow(2, Math.Floor(i / 5.0));
                prev = exp;
                Assert.AreEqual(exp, res);
            }
        }
Пример #21
0
        public void SetHarmsToPeriodic(MeNode tree)
        {
            foreach (MeNode leaf in tree.Leaves)
            {
                SetHarmsToPeriodic(leaf);
            }
            MeNode node = new MeNode(tree.Value);

            if (tree.Value.Type == VariableType.Function && tree.Value.ToFunction().Key.Equals(LConstants.HARM_F))
            {
                MeNode periodic = new MeNode(true);
                periodic.Parent = tree;
                tree.Leaves.Add(periodic);
            }
        }
Пример #22
0
 public void ReplaceNumericPlaceholders(MeNode tree, Dictionary <string, double> valueMap)
 {
     foreach (MeNode leaf in tree.Leaves)
     {
         ReplaceNumericPlaceholders(leaf, valueMap);
     }
     if (tree.Value.Type == VariableType.PlaceHolder)
     {
         tree.Value = new MeVariable()
         {
             Value = valueMap[tree.Value.ToPlaceholder()], Type = VariableType.NumericValue
         }
     }
     ;
 }
Пример #23
0
        public void FunctionalTreeConverterTestCopy()
        {
            string expression = "11+10";

            double[] expected = { 11, 10 };
            MeNode   tree     = TreeConverter.Build(expression, Engine);
            MeNode   copy     = tree.Resolve();

            Assert.AreEqual(tree.Value.ToOperator().Key, "+");
            Assert.AreEqual(2, tree.Leaves.Count);
            for (int i = 0; i < expected.Length; ++i)
            {
                Assert.AreEqual(expected[i], tree.Leaves[i].Value.ToDouble());
            }
        }
Пример #24
0
        public void SanitizerTestReplacePropetyOperators()
        {
            string expected      = "AGI";
            string expression    = $"1 + {expected}";
            double expectedValue = MockPlayer.GetProperty(expected).Value + 1;

            MeNode result = Sanitizer.ReplacePropeties(TreeConverter.Build(expression, Engine), MockPlayer);

            Assert.AreEqual(LConstants.PROP_OP, result.Leaves[1].Value.GetString());
            Assert.AreEqual(expected, result.Leaves[1].Leaves[1].Value.ToMeString());

            MeNode resolved = result.Resolve();

            Assert.AreEqual(expectedValue, resolved.Value.ToDouble());
        }
Пример #25
0
        private void TickCurrentCast()
        {
            if (CurrentlyCasting == null)
            {
                return;
            }
            long now = Engine.GetTimer().GetNow();

            if (CurrentlyCasting.Skill.Skill.Type == SkillType.Cast)
            {
                if (CurrentlyCasting.CastFinishTime <= now)
                {
                    string castedFinish = Key.Equals(CurrentlyCasting.Target.Key)
                        ? ""
                        : $" on  {CurrentlyCasting.Target.Name}";
                    Engine.Log().Log($"[{Name}] Casted {CurrentlyCasting.Skill.Skill.Name}{castedFinish}.");
                    //casting has finished so resolve the formula
                    MeNode[] toResolve = CurrentlyCasting.Skill.Formulas;
                    foreach (MeNode node in toResolve)
                    {
                        MeNode sanitized = Sanitizer.ReplaceTargetAndSource(node, this, CurrentlyCasting.Target);
                        sanitized.Resolve();
                    }
                    FinishCasting();
                }
            }
            else if (CurrentlyCasting.Skill.Skill.Type == SkillType.Channel)
            {
                if (CurrentlyCasting.CastFinishTime <= now)
                {
                    Engine.Log().Log($"[{Name}] Finished channeling {CurrentlyCasting.Skill.Skill.Name}.");
                    FinishCasting();
                }
                else
                {
                    //apply the formulas if it's the case
                    if (CurrentlyCasting.NextInterval == 0 || CurrentlyCasting.NextInterval < now)
                    {
                        MeNode[] toResolve = CurrentlyCasting.Skill.Formulas;
                        foreach (MeNode node in toResolve)
                        {
                            Sanitizer.ReplaceTargetAndSource(node, this, CurrentlyCasting.Target).Resolve();
                        }
                        CurrentlyCasting.NextInterval = now + CurrentlyCasting.Interval * 1000;
                    }
                }
            }
        }
Пример #26
0
        public static MeNode Resolve(MeNode node, int index = 0)
        {
            for (int i = 0; i < node.Leaves.Count; ++i)
            {
                node.Leaves[i] = Resolve(node.Leaves[i], i);
            }

            if (node.Parent != null && node.Parent.Value.Type == VariableType.Function)
            {
                if (!node.Parent.Value.ToFunction().ExecuteSubNode(index))
                {
                    List <MeVariable> parameters = new List <MeVariable>();
                    foreach (MeNode subNode in node.Leaves)
                    {
                        parameters.Add(subNode.Value);
                    }
                    return(new MeNode(new MeFunction(node.Value, parameters.ToArray())));
                }
            }
            switch (node.Value.Type)
            {
            case VariableType.Function:
                List <MeVariable> parameters = new List <MeVariable>();
                foreach (MeNode subNode in node.Leaves)
                {
                    parameters.Add(subNode.Value);
                }
                return(new MeNode(node.Value.ToFunction().Execute(parameters.ToArray())));

            case VariableType.Operator:
            {
                List <MeVariable> opParameters = new List <MeVariable>();
                foreach (MeNode subNode in node.Leaves)
                {
                    opParameters.Add(subNode.Value);
                }
                MeNode amt = new MeNode(node.Value.ToOperator().Execute(opParameters.ToArray()));
                return(amt);
            }

            default:
            {
                return(node);
            }
            }
        }
Пример #27
0
 public long GetMaxExp(int level)
 {
     if (ExpFormula == null)
     {
         return(0);
     }
     if (ExpValues.Count <= level)
     {
         ExpValues.Capacity = level + 1;
         for (int i = ExpValues.Count - 1; i <= level; ++i)
         {
             double prev      = ExpValues[i];
             MeNode sanitized = Sanitizer.ReplaceExpValues(ExpFormula, (long)prev, i + 1);
             ExpValues.Add((long)Math.Floor(sanitized.Resolve().Value.ToDouble()));
         }
     }
     return(ExpValues[level]);
 }
Пример #28
0
        public static MeNode ResolveGivenOperations(MeNode node, string[] operationNames, int index = 0)
        {
            for (int i = 0; i < node.Leaves.Count; ++i)
            {
                node.Leaves[i] = ResolveGivenOperations(node.Leaves[i], operationNames, i);
            }

            if (node.Value.Type == VariableType.Function || node.Value.Type == VariableType.Operator)
            {
                foreach (string key in operationNames)
                {
                    if (node.Value.GetString().Equals(key))
                    {
                        return(node.Resolve());
                    }
                }
            }
            return(node);
        }
Пример #29
0
        public MockEntity(IGameEngine engine)
            : base(engine)
        {
            AddAttribute("VIT", 5);
            AddAttribute("STR", 5);
            AddAttribute("INT", 5);
            AddAttribute("AGI", 10);
            AddAttribute("DEF", 10);
            AddAttribute("MDEF", 10);
            AddResource(getMockHP(engine));
            MeNode           mpNode  = TreeConverter.Build("INT*10", engine);
            MeNode           mpRegen = TreeConverter.Build("INT/100", engine);
            ResourceTemplate resTemp = new ResourceTemplate();

            resTemp.Formula       = mpNode;
            resTemp.RegenFormula  = mpRegen;
            resTemp.Key           = "MP";
            resTemp.RegenInterval = new MeNode(GcConstants.Resources.DEFAULT_INTERVAL);
            AddResource(resTemp);
        }
Пример #30
0
        public double GetMitigatedAmount(double amount, Entity source, Entity target)
        {
            bool crited;

            if (CriticalChance != null)
            {
                MeNode resolvedCritChance = Sanitizer.ReplaceTargetAndSource(CriticalChance, source, target)
                                            .Resolve();

                crited = Utils.Utility.Chance(resolvedCritChance.Value.ToDouble());
            }
            else
            {
                crited = false;
            }

            double mutliplier = 1.0;

            if (crited)
            {
                if (CriticalModifier != null)
                {
                    mutliplier = Sanitizer.ReplaceTargetAndSource(CriticalModifier, source, target)
                                 .Resolve().Value.ToDouble();
                }
            }

            double finalAmount = mutliplier * amount;

            if (Mitigation != null)
            {
                MeNode mitigation = Sanitizer.SanitizeMitigation(Mitigation, target, source, finalAmount)
                                    .Resolve();
                return(mitigation.Value.ToDouble());
            }
            else
            {
                return(finalAmount);
            }
        }
Пример #31
0
 ///<summary>
 /// Recursive method to print an inventory tree node
 ///</summary>
 private static void printNode(MeNode node, int indent)
 {
     // Make it pretty
     for (int i = 0; i < indent; ++i)
     {
         Console.Write(' ');
     }
     Console.WriteLine(node.getName() +
             " (" + node.getNode().type + ")");
     if (node.getChildren().Count != 0)
     {
         for (int c = 0; c < node.getChildren().Count; ++c)
         {
             printNode((MeNode)
                     node.getChildren()[c], indent + 2);
         }
     }
 }
Пример #32
0
 ///<summary>
 /// Print the inventory tree retrieved from
 /// the PropertyCollector
 ///</summary>
 private static void printInventoryTree(ObjectContent[] ocs)
 {
     // Hashtable MoRef.Value -> MeNode
     Hashtable nodes = new Hashtable();
     // The root folder node
     MeNode root = null;
     for (int oci = 0; oci < ocs.Length; ++oci)
     {
         ObjectContent oc = ocs[oci];
         ManagedObjectReference mor = oc.obj;
         DynamicProperty[] dps = oc.propSet;
         if (dps != null)
         {
             ManagedObjectReference parent = null;
             String name = null;
             for (int dpi = 0; dpi < dps.Length; ++dpi)
             {
                 DynamicProperty dp = dps[dpi];
                 if (dp != null)
                 {
                     if ("name".Equals(dp.name))
                     {
                         name = (String)dp.val;
                     }
                     if ("parent".Equals(dp.name))
                     {
                         parent = (ManagedObjectReference)dp
                         .val;
                     }
                 }
             }
             // Create a MeNode to hold the data
             MeNode node = new MeNode(parent, mor, name);
             // The root folder has no parent
             if (parent == null)
             {
                 root = node;
             }
             // Add the node
             nodes.Add(node.getNode().Value, node);
         }
     }
     // Build the nodes into a tree
     foreach (String key in nodes.Keys)
     {
         MeNode meNode = nodes[key] as MeNode;
         if (meNode.getParent() != null)
         {
             MeNode parent = (MeNode)nodes[meNode.getParent().Value];
             parent.getChildren().Add(meNode);
         }
     }
     Console.WriteLine("Inventory Tree");
     printNode(root, 0);
 }
Пример #33
0
      void PrintNode(MeNode node, TextWriter file, String mobUrl, 
         String docRoot, Hashtable typeToDoc, Hashtable typeToImage)
      {
         String mobLink = mobUrl + System.Web.HttpUtility.UrlEncode(node.node.Value);
         String page = typeToDoc[node.node.type] as String;
         String image = typeToImage[node.node.type] as String;
         String link = null;
         if(page != null && docRoot != null)
         {
            link = docRoot + page;
         }
         if(node.children.Count > 0)
         {
            node.children.Sort(new MeNodeCompare());

            file.WriteLine("<li style=\"list-style-image:url("+image+")\"><a target=\"mob\" href=\""+mobLink+"\">"+node.name+"</a></li>");
            if(link != null) 
            {
               file.WriteLine("<a target=\"mob\" href=\""+link+"\">?</a>");
            }
            file.WriteLine("<ul>");
            foreach (MeNode lNode in node.children)
            {
               PrintNode(lNode, file, mobUrl, docRoot, typeToDoc, typeToImage);
            }
            file.WriteLine("</ul>");
         }
         else
         {
            file.WriteLine("<li style=\"list-style-image:url("+image+")\"><a target=\"mob\" href=\""+mobLink+"\">"+node.name+"</a></li>");
            if(link != null) 
            {
               file.WriteLine("<a target=\"mob\" href=\""+link+"\">?</a>");
            }
         }
      }
Пример #34
0
      /// <summary>
      /// Retrieve inventory from the given root 
      /// </summary>
      private void PrintInventory() {
         try {

            // Retrieve Contents recursively starting at the root folder 
            // and using the default property collector.            
            ObjectContent[] ocary = 
               cb.getServiceUtil().GetContentsRecursively(null, null, typeInfo, true);

            Hashtable nodes = new Hashtable();
            MeNode root = null;

            for (int oci = 0; oci < ocary.Length; oci++) {
               ObjectContent oc = ocary[oci];
               ManagedObjectReference mor = oc.obj;
               DynamicProperty[] pcary = oc.propSet;

               if (pcary != null) {
                  ManagedObjectReference parent = null;
                  String name = null;
                  for (int pci = 0; pci < pcary.Length; pci++) 
                  {
                     DynamicProperty pc = pcary[pci];
                     if (pc != null) {
                        if("name" == pc.name) 
                        {
                           name = pc.val as String;
                        }
                        if("parent" == pc.name)
                        {
                           parent = pc.val as ManagedObjectReference;
                        }
                     }
                  }
                  MeNode node = new MeNode(parent, mor, name);
                  if(parent == null)
                  {
                     root = node;
                  }
                  nodes.Add(node.node.Value, node);
               }
            }
            // Organize the nodes into a 'tree'
            foreach (String key in nodes.Keys)
            {
               MeNode meNode = nodes[key] as MeNode;
               if(meNode.parent != null)
               {
                  ((MeNode)nodes[meNode.parent.Value]).children.Add(meNode);
               }
            }
            
            String mobUrl = cb.getServiceUrl();
            mobUrl = mobUrl.Replace("/sdk", "/mob");
            if(mobUrl.IndexOf("mob") == -1)
            {
               mobUrl += "/mob";
            }
            mobUrl += "/?moid=";

            // Map of ManagedEntity to doc file
            Hashtable typeToDoc = new Hashtable();
            typeToDoc["ComputeResource"] = "/vim.ComputeResource.html";
            typeToDoc["ClusterComputeResource"] = "/vim.ClusterComputeResource.html";
            typeToDoc["Datacenter"] = "/vim.Datacenter.html";
            typeToDoc["Folder"] = "/vim.Folder.html";
            typeToDoc["HostSystem"] = "/vim.HostSystem.html";
            typeToDoc["ResourcePool"] = "/vim.ResourcePool.html";
            typeToDoc["VirtualMachine"] = "/vim.VirtualMachine.html";

            Hashtable typeToImage = new Hashtable();
            typeToImage["ComputeResource"] = "compute-resource.png";
            typeToImage["ClusterComputeResource"] = "compute-resource.png";
            typeToImage["Datacenter"] = "datacenter.png";
            typeToImage["Folder"] = "folder-open.png";
            typeToImage["HostSystem"] = "host.png";
            typeToImage["ResourcePool"] = "resourcePool.png";
            typeToImage["VirtualMachine"] = "virtualMachine.png";

            String docRoot = cb.get_option("docref");
            if (docRoot != null)
            {
                // Try to determine where we are in sample tree
                // SDK/samples_2_0/DotNet/cs/MobStartPage/bin/Debug
                String cDir = Directory.GetCurrentDirectory();
                if (cDir.EndsWith("Debug") || cDir.EndsWith("Release"))
                {
                    docRoot = "../../../../../../doc/ReferenceGuide";
                }
                else if (cDir.EndsWith("MobStartPage"))
                {
                    docRoot = "../../../../doc/ReferenceGuide";
                }
                else if (cDir.EndsWith("cs"))
                {
                    docRoot = "../../../doc/ReferenceGuide";
                }

                bool docsFound = docRoot != null;
                // Not Url?
                if (docsFound && docRoot.IndexOf("http") == -1)
                {
                    String testFile = docRoot.Replace("/", "\\") + "\\index.html";
                    docsFound = File.Exists(testFile);
                }
                if (!docsFound)
                {
                    //log.LogLine("Warning: Can't find docs at: " + docRoot);
                    docRoot = null;
                }

                // Write out as html into string
                StringWriter nodeHtml = new StringWriter();
                PrintNode(root, nodeHtml, mobUrl, docRoot, typeToDoc, typeToImage);
                nodeHtml.Close();

                Assembly assembly = Assembly.GetExecutingAssembly();

                CopyFileFromResource(assembly, "MobStartPage.index.html", "index.html");
                CopyFileFromResource(assembly, "MobStartPage.compute-resource.png", "compute-resource.png");
                CopyFileFromResource(assembly, "MobStartPage.datacenter.png", "datacenter.png");
                CopyFileFromResource(assembly, "MobStartPage.folder.png", "folder.png");
                CopyFileFromResource(assembly, "MobStartPage.folder-open.png", "folder-open.png");
                CopyFileFromResource(assembly, "MobStartPage.host.png", "host.png");
                CopyFileFromResource(assembly, "MobStartPage.resourcePool.png", "resourcePool.png");
                CopyFileFromResource(assembly, "MobStartPage.virtualMachine.png", "virtualMachine.png");

                // Get and write inventory.html
                Stream stream = assembly.GetManifestResourceStream("MobStartPage.inventory.html");
                StreamReader reader = new StreamReader(stream);
                String fileData = reader.ReadToEnd();

                using (StreamWriter file = new StreamWriter("inventory.html"))
                {
                    String serverName = cb.getServiceUrl();
                    int lastCharacter = serverName.LastIndexOfAny(":/".ToCharArray());
                    if (lastCharacter != -1)
                    {
                        serverName = serverName.Substring(0, lastCharacter);
                    }
                    int firstCharacter = serverName.LastIndexOf('/');
                    if (firstCharacter != -1)
                    {
                        serverName = serverName.Substring(firstCharacter + 1);
                    }

                    String output = String.Format(fileData, serverName, nodeHtml.ToString());
                    file.WriteLine(output);
                }

                System.Diagnostics.Process.Start("index.html");

                cb.log.LogLine("Done Printing Inventory");
            }
            else
            {
                System.Console.WriteLine("Please provide the valid reference-doc-location.");
            }
         } catch (Exception e) {            
            cb.log.LogLine("MobStartPage : Failed Getting Contents");
            throw e;
         }
      }