Example #1
0
        public static ushort GetFreePort()
        {
            var ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
            var tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections();

            var usedPorts = new HashSet<ushort>(tcpConnInfoArray.Select(x => (ushort)x.LocalEndPoint.Port));
            var availablePorts = new HashSet<ushort>(Enumerable.Range(1024, 65535 - 1024).Select(x => (ushort)x));
            availablePorts.ExceptWith(usedPorts);

            return availablePorts.Skip(new Random().Next(availablePorts.Count - 1)).First();
        }
Example #2
0
        /// <summary>
        /// Get all nodes that in its input ports's scope. A node is in its 
        /// scope if that node is one of its upstream nodes. 
        /// </summary>
        /// <param name="portIndex">Inport index</param>
        /// <param name="checkEscape">
        /// If need to exclude nodes that one of their downstream nodes are not 
        /// in the scope
        /// </param>
        /// <param name="isInclusive">
        /// If a upstream node is ScopedNodeModel, need to include all upstream 
        /// nodes of that node.
        /// </param>
        /// <returns></returns>
        public IEnumerable<NodeModel> GetInScopeNodesForInport(
            int portIndex, 
            bool checkEscape = true, 
            bool isInclusive = true, 
            bool forceToGetNodeForInport = false)
        {
            // The related test cases are in DynmoTest.ScopedNodeTest.
            var scopedNodes = new HashSet<NodeModel>();

            Tuple<int, NodeModel> inputTuple = null;
            if ((!forceToGetNodeForInport && !IsScopedInport(portIndex)) || 
                !this.TryGetInput(portIndex, out inputTuple))
            {
                return scopedNodes;
            }

            scopedNodes.Add(this);
            var inputNode = inputTuple.Item2;
            var workingList = new Queue<NodeModel>();
            if (!checkEscape || (checkEscape && IsNodeInScope(inputNode, scopedNodes)))
            {
                workingList.Enqueue(inputNode);
                scopedNodes.Add(inputNode);
            }

            // Collect all upstream nodes in BFS order
            while (workingList.Any())
            {
                var currentNode = workingList.Dequeue();
                if (!isInclusive && currentNode is ScopedNodeModel)
                {
                    continue;
                }

                foreach (int index in Enumerable.Range(0, currentNode.InPortData.Count))
                {
                    if (currentNode.TryGetInput(index, out inputTuple))
                    {
                        inputNode = inputTuple.Item2;
                        if (!checkEscape || (checkEscape && IsNodeInScope(inputNode, scopedNodes)))
                        {
                            workingList.Enqueue(inputNode);
                            scopedNodes.Add(inputNode);
                        }
                    }
                }
            }

            return scopedNodes.Skip(1);
        }
Example #3
0
        public virtual void GenerateVMTCode(HashSet<Type> aTypesSet, HashSet<MethodBase> aMethodsSet, Func<Type, uint> aGetTypeID, Func<MethodBase, uint> aGetMethodUID)
        {
            new Comment("---------------------------------------------------------");
            new Cosmos.Assembler.Label(InitVMTCodeLabel);
            new Push { DestinationReg = Registers.EBP };
            new Mov { DestinationReg = Registers.EBP, SourceReg = Registers.ESP };
            mSequences = new DebugInfo.SequencePoint[0];

            var xSetTypeInfoRef = VTablesImplRefs.SetTypeInfoRef;
            var xSetMethodInfoRef = VTablesImplRefs.SetMethodInfoRef;
            var xTypesFieldRef = VTablesImplRefs.VTablesImplDef.GetField("mTypes",
                                                                               BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance);
            string xTheName = DataMember.GetStaticFieldName(xTypesFieldRef);
            DataMember xDataMember = (from item in Cosmos.Assembler.Assembler.CurrentInstance.DataMembers
                                      where item.Name == xTheName
                                      select item).FirstOrDefault();
            if (xDataMember != null)
            {
                Cosmos.Assembler.Assembler.CurrentInstance.DataMembers.Remove((from item in Cosmos.Assembler.Assembler.CurrentInstance.DataMembers
                                                                               where item == xDataMember
                                                                               select item).First());
            }
            var xData = new byte[16 + (aTypesSet.Count * GetVTableEntrySize())];
            var xTemp = BitConverter.GetBytes(aGetTypeID(typeof(Array)));
            xTemp = BitConverter.GetBytes(0x80000002);
            Array.Copy(xTemp, 0, xData, 4, 4);
            xTemp = BitConverter.GetBytes(aTypesSet.Count);
            Array.Copy(xTemp, 0, xData, 8, 4);
            xTemp = BitConverter.GetBytes(GetVTableEntrySize());
            Array.Copy(xTemp, 0, xData, 12, 4);
            Cosmos.Assembler.Assembler.CurrentInstance.DataMembers.Add(new DataMember(xTheName + "__Contents", xData));
            Cosmos.Assembler.Assembler.CurrentInstance.DataMembers.Add(new DataMember(xTheName + "__Handle", ElementReference.New(xTheName + "__Contents")));
            Cosmos.Assembler.Assembler.CurrentInstance.DataMembers.Add(new DataMember(xTheName, Cosmos.Assembler.ElementReference.New(xTheName + "__Handle")));
#if VMT_DEBUG
        using (var xVmtDebugOutput = XmlWriter.Create(@"c:\data\vmt_debug.xml"))
        {
            xVmtDebugOutput.WriteStartDocument();
            xVmtDebugOutput.WriteStartElement("VMT");
#endif
            //Push((uint)aTypesSet.Count);
            foreach (var xType in aTypesSet)
            {
#if VMT_DEBUG
                xVmtDebugOutput.WriteStartElement("Type");
                xVmtDebugOutput.WriteAttributeString("TypeId", aGetTypeID(xType).ToString());
                if (xType.BaseType != null)
                {
                    xVmtDebugOutput.WriteAttributeString("BaseTypeId", aGetTypeID(xType.BaseType).ToString());
                }
                xVmtDebugOutput.WriteAttributeString("Name", xType.FullName);
#endif
                // value contains true if the method is an interface method definition
                SortedList<MethodBase, bool> xEmittedMethods = new SortedList<MethodBase, bool>(new MethodBaseComparer());
                foreach (MethodBase xMethod in xType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
                {
                    if (aMethodsSet.Contains(xMethod))
                    { //) && !xMethod.IsAbstract) {
                        if (!xEmittedMethods.ContainsKey(xMethod))
                        {
                            xEmittedMethods.Add(xMethod, false);
                        }
                    }
                }
                foreach (MethodBase xCtor in xType.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
                {
                    if (aMethodsSet.Contains(xCtor))
                    { // && !xCtor.IsAbstract) {
                        if (!xEmittedMethods.ContainsKey(xCtor))
                        {
                            xEmittedMethods.Add(xCtor, false);
                        }
                    }
                }
                foreach (var xIntf in xType.GetInterfaces())
                {
                    foreach (var xMethodIntf in xIntf.GetMethods())
                    {
                        var xActualMethod = xType.GetMethod(xIntf.FullName + "." + xMethodIntf.Name,
                                                            (from xParam in xMethodIntf.GetParameters()
                                                             select xParam.ParameterType).ToArray());

                        if (xActualMethod == null)
                        {
                            // get private implemenation
                            xActualMethod = xType.GetMethod(xMethodIntf.Name,
                                                            (from xParam in xMethodIntf.GetParameters()
                                                             select xParam.ParameterType).ToArray());
                        }
                        if (xActualMethod == null)
                        {
                            try
                            {
                                if (!xIntf.IsGenericType)
                                {
                                    var xMap = xType.GetInterfaceMap(xIntf);
                                    for (int k = 0; k < xMap.InterfaceMethods.Length; k++)
                                    {
                                        if (xMap.InterfaceMethods[k] == xMethodIntf)
                                        {
                                            xActualMethod = xMap.TargetMethods[k];
                                            break;
                                        }
                                    }
                                }
                            }
                            catch
                            {
                            }
                        }
                        if (aMethodsSet.Contains(xMethodIntf))
                        {
                            if (!xEmittedMethods.ContainsKey(xMethodIntf))
                            {
                                xEmittedMethods.Add(xMethodIntf, true);
                            }
                        }

                    }
                }
                int? xBaseIndex = null;
                if (xType.BaseType == null)
                {
                    xBaseIndex = (int)aGetTypeID(xType);
                }
                else
                {
                    for (int t = 0; t < aTypesSet.Count; t++)
                    {
                        // todo: optimize check
                        var xItem = aTypesSet.Skip(t).First();
                        if (xItem.ToString() == xType.BaseType.ToString())
                        {
                            xBaseIndex = (int)aGetTypeID(xItem);
                            break;
                        }
                    }
                }
                if (xBaseIndex == null)
                {
                    throw new Exception("Base type not found!");
                }
                for (int x = xEmittedMethods.Count - 1; x >= 0; x--)
                {
                    if (!aMethodsSet.Contains(xEmittedMethods.Keys[x]))
                    {
                        xEmittedMethods.RemoveAt(x);
                    }
                }
                if (!xType.IsInterface)
                {
                    Push(aGetTypeID(xType));
                    Move("VMT__TYPE_ID_HOLDER__" + DataMember.FilterStringForIncorrectChars(LabelName.GetFullName(xType) + " ASM_IS__" + xType.Assembly.GetName().Name), (int)aGetTypeID(xType));
                    Cosmos.Assembler.Assembler.CurrentInstance.DataMembers.Add(
                        new DataMember("VMT__TYPE_ID_HOLDER__" + DataMember.FilterStringForIncorrectChars(LabelName.GetFullName(xType) + " ASM_IS__" + xType.Assembly.GetName().Name), new int[] { (int)aGetTypeID(xType) }));
                    Push((uint)xBaseIndex.Value);
                    xData = new byte[16 + (xEmittedMethods.Count * 4)];
                    xTemp = BitConverter.GetBytes(aGetTypeID(typeof(Array)));
                    Array.Copy(xTemp, 0, xData, 0, 4);
                    xTemp = BitConverter.GetBytes(0x80000002); // embedded array
                    Array.Copy(xTemp, 0, xData, 4, 4);
                    xTemp = BitConverter.GetBytes(xEmittedMethods.Count); // embedded array
                    Array.Copy(xTemp, 0, xData, 8, 4);
                    xTemp = BitConverter.GetBytes(4); // embedded array
                    Array.Copy(xTemp, 0, xData, 12, 4);
                    string xDataName = "____SYSTEM____TYPE___" + DataMember.FilterStringForIncorrectChars(LabelName.GetFullName(xType) + " ASM_IS__" + xType.Assembly.GetName().Name) + "__MethodIndexesArray";
                    Cosmos.Assembler.Assembler.CurrentInstance.DataMembers.Add(new DataMember(xDataName, xData));
                    Cosmos.Assembler.Assembler.CurrentInstance.DataMembers.Add(new DataMember(xDataName + "_Handle", ElementReference.New(xDataName)));
                    Push(xDataName + "_Handle");
                    xDataName = "____SYSTEM____TYPE___" + DataMember.FilterStringForIncorrectChars(LabelName.GetFullName(xType) + " ASM_IS__" + xType.Assembly.GetName().Name) + "__MethodAddressesArray";
                    Cosmos.Assembler.Assembler.CurrentInstance.DataMembers.Add(new DataMember(xDataName, xData));
                    Cosmos.Assembler.Assembler.CurrentInstance.DataMembers.Add(new DataMember(xDataName + "_Handle", ElementReference.New(xDataName)));
                    Push(xDataName + "_Handle");
                    xData = new byte[16 + Encoding.Unicode.GetByteCount(xType.FullName + ", " + xType.Module.Assembly.GetName().FullName)];
                    xTemp = BitConverter.GetBytes(aGetTypeID(typeof(Array)));
                    Array.Copy(xTemp, 0, xData, 0, 4);
                    xTemp = BitConverter.GetBytes(0x80000002); // embedded array
                    Array.Copy(xTemp, 0, xData, 4, 4);
                    xTemp = BitConverter.GetBytes((xType.FullName + ", " + xType.Module.Assembly.GetName().FullName).Length);
                    Array.Copy(xTemp, 0, xData, 8, 4);
                    xTemp = BitConverter.GetBytes(2); // embedded array
                    Array.Copy(xTemp, 0, xData, 12, 4);
                    xDataName = "____SYSTEM____TYPE___" + DataMember.FilterStringForIncorrectChars(LabelName.GetFullName(xType) + " ASM_IS__" + xType.Assembly.GetName().Name);
                    Cosmos.Assembler.Assembler.CurrentInstance.DataMembers.Add(new DataMember(xDataName, xData));
                    Cosmos.Assembler.Assembler.CurrentInstance.DataMembers.Add(new DataMember(xDataName + "_Handle", ElementReference.New(xDataName)));
                    Push("0" + xEmittedMethods.Count.ToString("X") + "h");
                    Call(xSetTypeInfoRef);
                }
                for (int j = 0; j < xEmittedMethods.Count; j++)
                {
                    MethodBase xMethod = xEmittedMethods.Keys[j];
#if VMT_DEBUG
                    xVmtDebugOutput.WriteStartElement("Method");
                    xVmtDebugOutput.WriteAttributeString("Id", aGetMethodUID(xMethod).ToString());
                    xVmtDebugOutput.WriteAttributeString("Name", xMethod.GetFullName());
                    xVmtDebugOutput.WriteEndElement();
#endif
                    var xMethodId = aGetMethodUID(xMethod);
                    if (!xType.IsInterface)
                    {
                        if (xEmittedMethods.Values[j])
                        {
                            var xNewMethod = xType.GetMethod(xMethod.DeclaringType.FullName + "." + xMethod.Name,
                                                                (from xParam in xMethod.GetParameters()
                                                                 select xParam.ParameterType).ToArray());

                            if (xNewMethod == null)
                            {
                                // get private implementation
                                xNewMethod = xType.GetMethod(xMethod.Name,
                                                                (from xParam in xMethod.GetParameters()
                                                                 select xParam.ParameterType).ToArray());
                            }
                            if (xNewMethod == null)
                            {
                                try
                                {
                                    var xMap = xType.GetInterfaceMap(xMethod.DeclaringType);
                                    for (int k = 0; k < xMap.InterfaceMethods.Length; k++)
                                    {
                                        if (xMap.InterfaceMethods[k] == xMethod)
                                        {
                                            xNewMethod = xMap.TargetMethods[k];
                                            break;
                                        }
                                    }
                                }
                                catch
                                {
                                }
                            }
                            xMethod = xNewMethod;
                        }

                        Push((uint)aGetTypeID(xType));
                        Push((uint)j);

                        Push((uint)xMethodId);
                        if (xMethod.IsAbstract)
                        {
                            // abstract methods dont have bodies, oiw, are not emitted
                            Push(0);
                        }
                        else
                        {
                            Push(ILOp.GetMethodLabel(xMethod));
                        }
                        Push(0);
                        Call(VTablesImplRefs.SetMethodInfoRef);
                    }
                }
#if VMT_DEBUG
                xVmtDebugOutput.WriteEndElement(); // type
#endif
            }
#if VMT_DEBUG
                    xVmtDebugOutput.WriteEndElement(); // types
                    xVmtDebugOutput.WriteEndDocument();
        }
#endif

            new Cosmos.Assembler.Label("_END_OF_" + InitVMTCodeLabel);
            new Pop { DestinationReg = Registers.EBP };
            new Return();
        }
Example #4
0
        protected async Task FetchUrlInfos(Status[] ses)
        {
            if (ses == null || ses.Length == 0)
                return;
            var mem = MemoryCache.Default;

            var urls = new HashSet<string>();
            foreach (var s in ses)
            {
                var us = Utils.ExtractUrlFromWeibo(s.text);
                foreach(var url in us)
                {
                    if (mem.Get("http://t.cn/" + url) == null)
                        urls.Add(url);
                }
                //urls.Add(us);
                if (s.retweeted_status != null)
                {
                    var rus = Utils.ExtractUrlFromWeibo(s.retweeted_status.text);
                    foreach (var url in rus)
                    {
                        if (mem.Get("http://t.cn/" + url) == null)
                            urls.Add(url);
                    }
                }
            }
            if(urls.Count >= 20)
            {
                var tasks = new Task[2];
                var u1 = urls.Take(20);
                tasks[0] = FetchUrlInfosImp(u1);
                var u2 = urls.Skip(20);
                tasks[1] = FetchUrlInfosImp(u2);
                await Task.WhenAll(tasks);
            }else
            {
                await FetchUrlInfosImp(urls);
            }

        }
        //added by gremlin aggruthmanager
        private void DoAggRuthAgentManager()
        {
            string Names;

            float income = this.spyBudget;

            this.DesiredAgentsPerHostile = (int)(income * .08f) + 1;
            this.DesiredAgentsPerNeutral = (int)(income * .03f) + 1;

            //this.DesiredAgentsPerHostile = 5;
            //this.DesiredAgentsPerNeutral = 2;
            this.BaseAgents = empire.GetPlanets().Count / 2;
            this.DesiredAgentCount = 0;
            foreach (KeyValuePair<Empire, Ship_Game.Gameplay.Relationship> Relationship in this.empire.GetRelations())
            {
                if (!Relationship.Value.Known || Relationship.Key.isFaction || Relationship.Key.data.Defeated)
                {
                    continue;
                }
                if (Relationship.Value.Posture == Posture.Hostile)
                {
                    GSAI desiredAgentCount = this;
                    desiredAgentCount.DesiredAgentCount = desiredAgentCount.DesiredAgentCount + this.DesiredAgentsPerHostile;
                }
                if (Relationship.Value.Posture != Posture.Neutral)
                {
                    continue;
                }
                GSAI gSAI = this;
                gSAI.DesiredAgentCount = gSAI.DesiredAgentCount + this.DesiredAgentsPerNeutral;
            }
            GSAI desiredAgentCount1 = this;
            desiredAgentCount1.DesiredAgentCount = desiredAgentCount1.DesiredAgentCount + this.BaseAgents;

            int empirePlanetSpys = this.empire.GetPlanets().Count() / 3 + 3;// (int)(this.spyBudget / (this.empire.GrossTaxes * 3));
            int currentSpies = this.empire.data.AgentList.Count;
            if (this.spyBudget >= 250f && currentSpies < empirePlanetSpys)
            {
                Names = (!File.Exists(string.Concat("Content/NameGenerators/spynames_", this.empire.data.Traits.ShipType, ".txt")) ? File.ReadAllText("Content/NameGenerators/spynames_Humans.txt") : File.ReadAllText(string.Concat("Content/NameGenerators/spynames_", this.empire.data.Traits.ShipType, ".txt")));
                string[] Tokens = Names.Split(new char[] { ',' });
                Agent a = new Agent();
                a.Name = AgentComponent.GetName(Tokens);
                this.empire.data.AgentList.Add(a);
                this.spyBudget -= 250f;
            }
            int Defenders = 0;
            int Offense = 0;
            foreach (Agent a in this.empire.data.AgentList)
            {
                if (a.Mission == AgentMission.Defending)
                {
                    Defenders++;
                }
                else if (a.Mission != AgentMission.Undercover)
                {
                    Offense++;
                }
                if (a.Mission != AgentMission.Defending || a.Level >= 2 || this.spyBudget <= 50f)
                {
                    continue;
                }
                a.AssignMission(AgentMission.Training, this.empire, "");
            }
            int DesiredOffense = (int)(this.empire.data.AgentList.Count  * .3f);
            //int DesiredOffense = (int)(this.empire.data.AgentList.Count - empire.GetPlanets().Count * .33f); // (int)(0.33f * (float)this.empire.data.AgentList.Count);
            //int DesiredOffense = this.empire.data.AgentList.Count / 2;
            foreach (Agent agent in this.empire.data.AgentList)
            {
                if (agent.Mission != AgentMission.Defending && agent.Mission != AgentMission.Undercover || Offense >= DesiredOffense )
                {
                    continue;
                }
                List<Empire> PotentialTargets = new List<Empire>();
                foreach (KeyValuePair<Empire, Ship_Game.Gameplay.Relationship> Relation in this.empire.GetRelations())
                {
                    if (!Relation.Value.Known || Relation.Key.isFaction || Relation.Key.data.Defeated || Relation.Value.Posture != Posture.Neutral && Relation.Value.Posture != Posture.Hostile)
                    {
                        continue;
                    }
                    PotentialTargets.Add(Relation.Key);
                }
                if (PotentialTargets.Count <= 0)
                {
                    continue;
                }
                HashSet<AgentMission> PotentialMissions = new HashSet<AgentMission>();
                Empire Target = PotentialTargets[HelperFunctions.GetRandomIndex(PotentialTargets.Count)];
                if (this.empire.GetRelations()[Target].AtWar)
                {
                    if (agent.Level >= 8)
                    {
                        PotentialMissions.Add(AgentMission.InciteRebellion);
                        PotentialMissions.Add(AgentMission.Assassinate);

                        PotentialMissions.Add(AgentMission.StealTech);
                    }
                    if (agent.Level >= 4)
                    {
                        PotentialMissions.Add(AgentMission.StealTech);
                        PotentialMissions.Add(AgentMission.Robbery);
                        PotentialMissions.Add(AgentMission.Sabotage);
                    }
                    if (agent.Level < 4)
                    {
                        PotentialMissions.Add(AgentMission.Sabotage);
                        PotentialMissions.Add(AgentMission.StealTech);
                        PotentialMissions.Add(AgentMission.Robbery);
                        //PotentialMissions.Add(AgentMission.Infiltrate);
                    }
                }
                if (this.empire.GetRelations()[Target].Posture == Posture.Hostile)
                {
                    if (agent.Level >= 8)
                    {
                        PotentialMissions.Add(AgentMission.StealTech);
                        PotentialMissions.Add(AgentMission.Assassinate);
                    }
                    if (agent.Level >= 4)
                    {
                        PotentialMissions.Add(AgentMission.Robbery);
                        PotentialMissions.Add(AgentMission.Sabotage);

                    }
                    if (agent.Level < 4)
                    {
                        PotentialMissions.Add(AgentMission.Sabotage);

                    }
                }

                if (this.empire.GetRelations()[Target].SpiesDetected > 0)
                {
                    if (agent.Level >= 4) PotentialMissions.Add(AgentMission.Assassinate);
                }
                HashSet<AgentMission> remove = new HashSet<AgentMission>();
                foreach(AgentMission mission in PotentialMissions)
                {
                    switch (mission)
                    {
                        case AgentMission.Defending:
                        case AgentMission.Training:
                            break;
                        case AgentMission.Infiltrate:
                            if (ResourceManager.AgentMissionData.InfiltrateCost > this.spyBudget)
                            {
                                remove.Add(mission);
                            }
                            break;
                        case AgentMission.Assassinate:
                            if (ResourceManager.AgentMissionData.AssassinateCost > this.spyBudget)
                            {
                                remove.Add(mission);
                            }
                            break;
                        case AgentMission.Sabotage:
                            if (ResourceManager.AgentMissionData.SabotageCost > this.spyBudget)
                            {
                                remove.Add(mission);
                            }
                            break;
                        case AgentMission.StealTech:
                            if (ResourceManager.AgentMissionData.StealTechCost > this.spyBudget)
                            {
                                remove.Add(mission);
                            }
                            break;
                        case AgentMission.Robbery:
                            if (ResourceManager.AgentMissionData.RobberyCost > this.spyBudget)
                            {
                                remove.Add(mission);
                            }
                            break;
                        case AgentMission.InciteRebellion:
                            if (ResourceManager.AgentMissionData.RebellionCost > this.spyBudget)
                            {
                                remove.Add(mission);
                            }
                            break;
                        case AgentMission.Undercover:
                            if (ResourceManager.AgentMissionData.InfiltrateCost > this.spyBudget)
                            {
                                remove.Add(mission);
                            }
                            break;
                        case AgentMission.Recovering:
                            break;
                        default:
                            break;
                    }
                }
                foreach(AgentMission removeMission in remove)
                {
                    PotentialMissions.Remove(removeMission);
                }
                if (PotentialMissions.Count <= 0)
                {
                    continue;
                }
                AgentMission am = PotentialMissions.Skip(HelperFunctions.GetRandomIndex(PotentialMissions.Count)).FirstOrDefault();
                if(am !=null)
                agent.AssignMission(am, this.empire, Target.data.Traits.Name);
                Offense++;

            }
        }