Example #1
0
        private static void ConvertReport(string inputTxt, string outputTsv)
        {
            var funcNames = new List<string>();
            var result =
                new ConcurrentDictionary<string, ConcurrentDictionary<int, double>>();

            using (var input = File.OpenText(inputTxt))
            {
                var line = input.ReadLine();
                while (line != null)
                {
                    var len = int.Parse(line.Split()[2]);
                    while ((line = input.ReadLine()) != null && !line.Trim().StartsWith("Len -"))
                    {
                        var funcName = line.Trim();
                        var times = new List<double>();
                        for (var i = 0; i < 4; ++i)
                        {
                            var tokens = input.ReadLine().Split(':');
                            times.Add(double.Parse(tokens[1].Trim().Split()[0]));
                        }
                        result.GetOrAdd(funcName,
                            s =>
                            {
                                funcNames.Add(s);
                                return new ConcurrentDictionary<int, double>();
                            })
                            .TryAdd(len, times.Average());
                    }
                }
            }

            using (var output = File.CreateText(outputTsv))
            {
                output.WriteLine("#\t" + string.Join("\t", funcNames));

                foreach (var len in result.First().Value.Keys.OrderBy(v => v))
                {
                    output.WriteLine(string.Format("{0:f3} KB\t", len / 1000.0) + string.Join("\t", funcNames.Select(func => result[func][len])));
                }
            }
        }
Example #2
0
 internal UserProfile GetFirst()
 {
     return(_profiles.First().Value);
 }
Example #3
0
        private void HandleLogin(HttpListenerContext context)
        {
            LoginRequest request;

            try
            {
                request = RestMethods.ReadBody <LoginRequest>(context.Request);
            }
            catch (ArgumentException e)
            {
                RestMethods.WriteError(context.Response, HttpStatusCode.BadRequest, e.Message);
                return;
            }

            if (_usernames.TryGetValue(request.Username, out int id))
            {
                if (_users[id].Online)
                {
                    context.Response.AppendHeader(HttpResponseHeader.WwwAuthenticate.ToString(), "Token realm = 'Username is already in use'");
                    RestMethods.WriteError(context.Response, HttpStatusCode.Unauthorized, "username is already in use");
                    return;
                }
                else
                {
                    _users.TryRemove(id, out _);
                    _usernames.TryRemove(request.Username, out id);
                    _tokens.TryRemove(_tokens.First(tokenId => tokenId.Value == id).Key, out id);
                }
            }

            lock (this)
            {
                id = ++_userId;
            }
            var token = Convert.ToBase64String(Guid.NewGuid().ToByteArray());

            var loginResponse = new LoginResponse
            {
                Username = request.Username,
                Id       = id,
                Online   = true,
                Token    = token
            };

            lock (_usernames)
            {
                if (!_usernames.TryAdd(loginResponse.Username, id))
                {
                    context.Response.AppendHeader(HttpResponseHeader.WwwAuthenticate.ToString(), "Token realm = 'Username is already in use'");
                    RestMethods.WriteError(context.Response, HttpStatusCode.Unauthorized, "username is already in use");
                }
                _users.TryAdd(id, new User
                {
                    Username = loginResponse.Username,
                    Id       = id,
                    Online   = true
                });
                _tokens.TryAdd(token, id);
            }

            CountAndDecrement(_userEvent);

            RestMethods.WriteToResponse(context.Response, loginResponse);
        }
        private async Task MessageReceivedAsync(QueueMessage <TMessage> message, CancellationToken cancellationToken)
        {
            if (!cancellationToken.IsCancellationRequested && !_tasks.Any(t => t.Value.IsFaulted))
            {
                if (Behaviour == AcknowledgeBehaviour.BeforeProcess)
                {
                    _queueConsumer.AcknowledgeMessage(message.DeliveryTag);
                }

                string processingSequenceIdentifier = GetProcessingSequenceIdentifier(message.RoutingKey);

                if (_processingQueues.ContainsKey(processingSequenceIdentifier))
                {
                    // Add a message to the processing queue, and signal the processing thread to alert it to the new message.
                    var processingQueue = _processingQueues[processingSequenceIdentifier];
                    processingQueue.Queue.Enqueue(message);
                    processingQueue.AutoResetEvent.Set();
                }
                else
                {
                    // create a new processing queue and kick off a task to process it.
                    var processingQueue = new ProcessingQueue <TMessage>();
                    processingQueue.Queue.Enqueue(message);
                    _processingQueues[processingSequenceIdentifier] = processingQueue;
                    var t = Task.Run(RunSequentialProcessor(processingQueue, cancellationToken));
                    _tasks.TryAdd(processingSequenceIdentifier, t);
                }

                _logger.Info($"Received new message {message.DeliveryTag}, processor queue length {_processingQueues.First().Value.Queue.Count()}");
            }

            // Remove completed queues
            var processingQueuesToRemove = new List <string>();

            foreach (var processingQueue in _processingQueues)
            {
                if (!processingQueue.Value.Queue.Any())
                {
                    processingQueue.Value.AutoResetEvent.Set();
                    processingQueuesToRemove.Add(processingQueue.Key);
                }
            }

            foreach (var processingQueueToRemove in processingQueuesToRemove)
            {
                _processingQueues.TryRemove(processingQueueToRemove, out _);
                _tasks.TryRemove(processingQueueToRemove, out _);
            }

            // TODO: is it possible to remove executed tasks from the Task list and processingqueues from the processing queues

            _logger.Info($"Number of tasks {_tasks.Count()}, number of queues {_processingQueues.Count()}.");
        }
        private void MergeLocalWorldMaps()
        {
            //Fusion des World Map locales pour construire la world map globale

            //Génération de la carte fusionnée à partir des perceptions des robots de l'équipe
            //La fusion porte avant tout sur la balle et sur les adversaires.

            //TODO : faire un algo de fusion robuste pour la balle
            globalWorldMap = new WorldMap.GlobalWorldMap(TeamId);

            //Pour l'instant on prend la position de balle vue par le robot 1 comme vérité, mais c'est à améliorer !
            if (localWorldMapDictionary.Count > 0)
            {
                globalWorldMap.ballLocationList = localWorldMapDictionary.First().Value.ballLocationList;
            }
            globalWorldMap.teammateLocationList            = new Dictionary <int, Location>();
            globalWorldMap.teammateGhostLocationList       = new Dictionary <int, Location>();
            globalWorldMap.teammateDestinationLocationList = new Dictionary <int, Location>();
            globalWorldMap.teammateBallHandlingStateList   = new Dictionary <int, BallHandlingState>();
            globalWorldMap.teammateWayPointList            = new Dictionary <int, Location>();
            globalWorldMap.opponentLocationList            = new List <Location>();
            globalWorldMap.obstacleLocationList            = new List <LocationExtended>();
            globalWorldMap.teammateRoleList           = new Dictionary <int, RoboCupRobotRole>();
            globalWorldMap.teammateDisplayMessageList = new Dictionary <int, string>();
            globalWorldMap.teammatePlayingSideList    = new Dictionary <int, PlayingSide>();

            //On place tous les robots de l'équipe dans la global map
            foreach (var localMap in localWorldMapDictionary)
            {
                //On ajoute la position des robots de l'équipe dans la WorldMap
                globalWorldMap.teammateLocationList.Add(localMap.Key, localMap.Value.robotLocation);
                //On ajoute le rôle des robots de l'équipe dans la WorldMap
                globalWorldMap.teammateRoleList.Add(localMap.Key, localMap.Value.robotRole);
                //On ajoute l'état de Ball Handling des robots de l'équipe dans la WorldMap
                globalWorldMap.teammateBallHandlingStateList.Add(localMap.Key, localMap.Value.ballHandlingState);
                //On ajoute le message à afficher des robots de l'équipe dans la WorldMap
                globalWorldMap.teammateDisplayMessageList.Add(localMap.Key, localMap.Value.messageDisplay);
                //On ajoute le playing Side des robots de l'équipe dans la WorldMap
                globalWorldMap.teammatePlayingSideList.Add(localMap.Key, localMap.Value.playingSide);
                //On ajoute le ghost (position théorique) des robots de l'équipe dans la WorldMap
                globalWorldMap.teammateGhostLocationList.Add(localMap.Key, localMap.Value.robotGhostLocation);
                //On ajoute la destination des robots de l'équipe dans la WorldMap
                globalWorldMap.teammateDestinationLocationList.Add(localMap.Key, localMap.Value.destinationLocation);
                //On ajoute le waypoint courant des robots de l'équipe dans la WorldMap
                globalWorldMap.teammateWayPointList.Add(localMap.Key, localMap.Value.waypointLocation);
            }

            try
            {
                //TODO : Fusion des obstacles vus par chacun des robots
                foreach (var localMap in localWorldMapDictionary)
                {
                    foreach (var obstacle in localMap.Value.obstaclesLocationList)
                    {
                        if (obstacle != null)
                        {
                            bool skipNext = false;
                            /// On itère sur chacun des obstacles perçus par chacun des robots
                            /// On commence regarde pour chaque obstacle perçu si il ne correspond pas à une position de robot de l'équipe
                            ///     Si c'est le cas, on abandonne cet obstacle
                            ///     Si ce n'est pas le cas, on regarde si il ne correspond pas à un obstacle déjà présent dans la liste des obstacles
                            ///         Si ce n'est pas le cas, on l'ajoute à la liste des obtacles
                            ///         Si c'est le cas, on le fusionne en moyennant ses coordonnées de manière pondérée
                            ///             et on renforce le poids de cet obstacle
                            foreach (var teamMateRobot in globalWorldMap.teammateLocationList)
                            {
                                if (Toolbox.Distance(new PointD(obstacle.X, obstacle.Y), new PointD(teamMateRobot.Value.X, teamMateRobot.Value.Y)) < distanceMaxFusionTeamMate)
                                {
                                    /// L'obstacle est un robot, on abandonne
                                    skipNext = true;
                                    break;
                                }
                            }
                            if (skipNext == false)
                            {
                                /// Si on arrive ici c'est que l'obstacle n'est pas un robot de l'équipe
                                foreach (var obstacleConnu in globalWorldMap.obstacleLocationList)
                                {
                                    if (Toolbox.Distance(new PointD(obstacle.X, obstacle.Y), new PointD(obstacleConnu.X, obstacleConnu.Y)) < distanceMaxFusionObstacle)
                                    {
                                        //L'obstacle est déjà connu, on le fusionne /TODO : améliorer la fusion avec pondération
                                        obstacleConnu.X = (obstacleConnu.X + obstacle.X) / 2;
                                        obstacleConnu.Y = (obstacleConnu.Y + obstacle.Y) / 2;
                                        skipNext        = true;
                                        break;
                                    }
                                }
                            }
                            if (skipNext == false)
                            {
                                /// Si on arrive ici, c'est que l'obstacle n'était pas connu, on l'ajoute
                                globalWorldMap.obstacleLocationList.Add(obstacle);
                            }
                        }
                    }
                }
            }
            catch { }

            /// Transfert de la globalworldmap via le Multicast UDP
            //var s = ZeroFormatterSerializer.Serialize<WorldMap.ZeroFormatterMsg>(globalWorldMap);
            OnGlobalWorldMap(globalWorldMap);
            //OnMulticastSendGlobalWorldMap(s);
            //GWMEmiseMonitoring.GWMEmiseMonitor(s.Length);
        }
Example #6
0
 public object AnyContext() => Contexts.First().Value;
Example #7
0
 public object AnyContext()
 {
     return(Contexts.First().Value);
 }
Example #8
0
        public void Screenshot(Player player)
        {
            var coordinates = (BlockCoordinates)player.KnownPosition;

            BlockCoordinates direction = Vector3.Normalize(player.KnownPosition.GetHeadDirection()) * 1.5f;

            string pluginDirectory = Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath);

            //byte[] skinBytes = Encoding.ASCII.GetBytes(new string('Z', 64*64*4));
            byte[] skinBytes = Skin.GetTextureFromFile(Path.Combine(pluginDirectory, "test_skin.png"));
            Log.Warn($"Size {skinBytes.Length}");

            for (int x = 0; x < _width; x++)
            {
                for (int y = 0; y < _height; y++)
                {
                    var skinGeometryName = "geometry.flat." + Guid.NewGuid();
                    var model            = new GeometryModel()
                    {
                        FormatVersion = "1.12.0",
                        Geometry      = new List <Geometry>
                        {
                            new Geometry
                            {
                                Description = new Description
                                {
                                    Identifier          = skinGeometryName,
                                    TextureHeight       = 64,
                                    TextureWidth        = 64,
                                    VisibleBoundsHeight = 0,
                                    VisibleBoundsWidth  = 0,
                                    VisibleBoundsOffset = new int[3]
                                },
                                Name  = skinGeometryName,
                                Bones = new List <Bone>
                                {
                                    new Bone
                                    {
                                        Name  = BoneName.Body,
                                        Cubes = new List <Cube>()
                                        {
                                            new Cube
                                            {
                                                Origin = new float[3],
                                                //Size = new float[] {68.4f, 68.4f, 0.1f},
                                                Size = new float[] { 62, 62, 1 },
                                                Uv   = new float[2] {
                                                    0, 0
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        },
                    };


                    //string fileName = Path.GetTempPath() + "Geometry_" + Guid.NewGuid() + ".json";
                    //File.WriteAllText(fileName, Skin.ToJson(model));

                    var fake = new PlayerMob(string.Empty, player.Level)
                    {
                        Scale  = 1.1,
                        Width  = 0.01,
                        Length = 0.01,
                        Height = 0.01,
                        Skin   = new Skin
                        {
                            SkinId            = "testing" + new Guid(),
                            Slim              = false,
                            Height            = 64,
                            Width             = 64,
                            Data              = skinBytes,
                            GeometryName      = skinGeometryName,
                            GeometryData      = Skin.ToJson(model),
                            SkinResourcePatch = new SkinResourcePatch()
                            {
                                Geometry = new GeometryIdentifier()
                                {
                                    Default = skinGeometryName
                                }
                            }
                        },
                        KnownPosition = new PlayerLocation(coordinates.X + direction.X + (x * 4), coordinates.Y + (y * 4), coordinates.Z + direction.Z, 0, 0)
                    };
                    mobs.TryAdd(new Tuple <int, int>(x, y), fake);
                    fake.SpawnEntity();
                    //fake.AddToPlayerList();
                    //Thread.Sleep(500);
                }
            }
            mobs.First().Value.Ticking += PlayerOnTicking;
        }
        public void On_Connection_Message(object MsgObj)
        {
            try
            {
                string Msg = (string)MsgObj;
                //if (Vendor.ToUpper().Equals("ACDT"))
                //{
                //    byte[] byteAry = Encoding.ASCII.GetBytes(Msg);


                //    logger.Debug(DeviceName + " Recieve:" + BitConverter.ToString(byteAry));
                //}
                //else
                //{

                //}
                //Node Target = null;

                List <CommandReturnMessage> ReturnMsgList = _Decoder.GetMessage(Msg);
                foreach (CommandReturnMessage ReturnMsg in ReturnMsgList)
                {
                    //logger.Info(DeviceName + " Recieve:" + ReturnMsg.OrgMsg);
                    if (!this.Vendor.ToUpper().Equals("MITSUBISHI_PLC"))
                    {
                        _ReportTarget.On_Message_Log("CMD", DeviceName + " Recieve:" + ReturnMsg.OrgMsg);
                    }
                    try
                    {
                        Transaction Txn  = null;
                        Node        Node = null;
                        if (ReturnMsg != null)
                        {
                            lock (TransactionList)
                            {
                                if (ReturnMsg.Command != null)
                                {
                                    if (ReturnMsg.Command.Equals("PAUSE"))
                                    {
                                        foreach (Transaction t in TransactionList.Values)
                                        {
                                            t.SetTimeOutMonitor(false);
                                        }
                                    }
                                    if (ReturnMsg.Command.Equals("CONT_"))
                                    {
                                        foreach (Transaction t in TransactionList.Values)
                                        {
                                            t.SetTimeOutMonitor(true);
                                        }
                                    }
                                }


                                string key = "";
                                if (Vendor.ToUpper().Equals("KAWASAKI"))
                                {
                                    key = ReturnMsg.Seq;
                                }
                                else if (Vendor.ToUpper().Equals("HST") || Vendor.ToUpper().Equals("COGNEX"))
                                {
                                    key = "1" + ReturnMsg.Command;
                                }

                                else if (Vendor.ToUpper().Equals("SANWA") || Vendor.ToUpper().Equals("ATEL_NEW"))
                                {
                                    key = ReturnMsg.NodeAdr + ReturnMsg.Command;
                                    for (int seq = 0; seq <= 99; seq++)
                                    {
                                        string tmpKey = key + seq.ToString("00");

                                        if (TransactionList.ContainsKey(tmpKey))
                                        {
                                            key = tmpKey;
                                            break;
                                        }
                                        if (seq == 99)
                                        {
                                            logger.Error("seq is run out!");
                                        }
                                    }
                                }
                                else if (Vendor.ToUpper().Equals("SANWA_MC"))
                                {
                                    //if (ReturnMsg.Command.Equals("MCR__"))
                                    //{
                                    if (ReturnMsg.Command.Equals("RESET"))
                                    {
                                        key = "0";
                                    }
                                    else
                                    {
                                        key = ReturnMsg.NodeAdr;
                                    }
                                    //}
                                    //else
                                    //{
                                    //    key = "0" + ReturnMsg.Command;
                                    //}
                                }
                                else if (DeviceType.Equals("SMARTTAG"))
                                {
                                    key = "00";
                                }
                                else
                                {
                                    key = (ReturnMsg.NodeAdr + ReturnMsg.Command).Equals("") ? "0" : ReturnMsg.NodeAdr + ReturnMsg.Command;
                                }

                                if (Vendor.ToUpper().Equals("KAWASAKI"))
                                {
                                    if (TransactionList.TryGetValue(key, out Txn))
                                    {
                                        Node = NodeManagement.Get(Txn.NodeName);

                                        if (!Txn.CommandType.Equals("CMD"))
                                        {
                                            if (ReturnMsg.Type.Equals(CommandReturnMessage.ReturnType.Excuted))
                                            {
                                                continue;
                                            }
                                            else if (ReturnMsg.Type.Equals(CommandReturnMessage.ReturnType.Finished))
                                            {
                                                ReturnMsg.Type = CommandReturnMessage.ReturnType.Excuted;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        logger.Debug("Transaction not exist:key=" + key);
                                        return;
                                    }
                                }
                                else if (Vendor.ToUpper().Equals("TDK"))
                                {
                                    if (TransactionList.TryGetValue(key, out Txn))
                                    {
                                        Node = NodeManagement.Get(Txn.NodeName);
                                        if (Txn.CommandType.Equals("SET") && ReturnMsg.Type.Equals(CommandReturnMessage.ReturnType.Excuted))
                                        {
                                            //continue;
                                        }
                                    }
                                    else
                                    {
                                        Node = NodeManagement.GetByController(DeviceName, ReturnMsg.NodeAdr);
                                    }
                                }
                                else
                                {
                                    //if (ReturnMsg.NodeAdr.Equals("") || ReturnMsg.Command.Equals("RESET") || ReturnMsg.Command.Equals("SP___") || ReturnMsg.Command.Equals("PAUSE") || ReturnMsg.Command.Equals("CONT_") || ReturnMsg.Command.Equals("STOP_") || ReturnMsg.Command.Equals("TGEVT"))
                                    //{
                                    //    Node = NodeManagement.GetFirstByController(DeviceName);
                                    //}
                                    //else
                                    //{
                                    //    Node = NodeManagement.GetByController(DeviceName, ReturnMsg.NodeAdr);
                                    //}
                                    Node = NodeManagement.GetByController(DeviceName, ReturnMsg.NodeAdr.Equals("") ? "0" : ReturnMsg.NodeAdr);
                                    if (Node == null)
                                    {
                                        Node = NodeManagement.GetOCRByController(DeviceName);
                                    }
                                    if (Node == null)
                                    {
                                        Node = NodeManagement.GetFirstByController(DeviceName);
                                    }
                                }
                                //lock (TransactionList)
                                //{
                                //lock (Node)
                                //{
                                //Target = Node;
                                if (Node.Vendor.ToUpper().Equals("COGNEX"))
                                {
                                    if (ReturnMsg.Type == CommandReturnMessage.ReturnType.UserName)
                                    {
                                        conn.Send("admin\r\n");
                                        continue;
                                    }
                                    if (ReturnMsg.Type == CommandReturnMessage.ReturnType.Password)
                                    {
                                        conn.Send("\r\n");
                                        continue;
                                    }
                                }
                                if (ReturnMsg.Type == CommandReturnMessage.ReturnType.Event)
                                {
                                    //_ReportTarget.On_Event_Trigger(Node, ReturnMsg);
                                }
                                else if ((ReturnMsg.Type == CommandReturnMessage.ReturnType.Information && Node.Vendor.ToUpper().Equals("TDK") && !TransactionList.ContainsKey(key)))
                                {
                                    if (ReturnMsg.Type.Equals(CommandReturnMessage.ReturnType.Information))
                                    {
                                        //ThreadPool.QueueUserWorkItem(new WaitCallback(conn.Send), ReturnMsg.FinCommand);
                                        conn.Send(ReturnMsg.FinCommand);
                                        //isWaiting = false;
                                        logger.Debug(DeviceName + " Send:" + ReturnMsg.FinCommand);
                                    }
                                }
                                else if (TransactionList.TryRemove(key, out Txn))
                                {
                                    // Node.InitialComplete = false;
                                    switch (ReturnMsg.Type)
                                    {
                                    case CommandReturnMessage.ReturnType.Excuted:
                                        if (!Txn.CommandType.Equals("CMD") && !Txn.CommandType.Equals("MOV") && !Txn.CommandType.Equals("HCS"))
                                        {
                                            logger.Debug("Txn timmer stoped.");
                                            Txn.SetTimeOutMonitor(false);
                                            lock (Node.ExcuteLock)
                                            {
                                                Node.IsExcuting = false;
                                            }
                                        }
                                        else
                                        {
                                            //if (Txn.Method.Equals(Transaction.Command.LoadPortType.Reset))
                                            //{
                                            //    logger.Debug("Txn timmer stoped.");
                                            //    Txn.SetTimeOutMonitor(false);

                                            //}
                                            //else if (Txn.Method.Equals(Transaction.Command.RobotType.OrginSearch))
                                            //{
                                            //    logger.Debug("Txn timmer stoped.");
                                            //    Txn.SetTimeOutMonitor(false);
                                            //    //Node.IsExcuting = false;
                                            //    TransactionList.TryAdd(key, Txn);
                                            //}
                                            //else
                                            //{
                                            Txn.SetTimeOutMonitor(false);
                                            Txn.SetTimeOut(Txn.MotionTimeOut);
                                            Txn.SetTimeOutMonitor(true);
                                            TransactionList.TryAdd(key, Txn);

                                            //}
                                        }
                                        //_ReportTarget.On_Command_Excuted(Node, Txn, ReturnMsg);
                                        break;

                                    case CommandReturnMessage.ReturnType.Finished:
                                        logger.Debug("Txn timmer stoped.");
                                        Txn.SetTimeOutMonitor(false);
                                        lock (Node.ExcuteLock)
                                        {
                                            Node.IsExcuting = false;
                                        }
                                        //_ReportTarget.On_Command_Finished(Node, Txn, ReturnMsg);
                                        break;

                                    case CommandReturnMessage.ReturnType.Error:
                                        logger.Debug("Txn timmer stoped.");
                                        Txn.SetTimeOutMonitor(false);
                                        lock (Node.ExcuteLock)
                                        {
                                            Node.IsExcuting = false;
                                        }
                                        //_ReportTarget.On_Command_Error(Node, Txn, ReturnMsg);
                                        if (Vendor.ToUpper().Equals("TDK") || DeviceType.ToUpper().Equals("SMARTTAG"))
                                        {
                                            conn.Send(ReturnMsg.FinCommand);
                                            logger.Debug(DeviceName + " Send:" + ReturnMsg.FinCommand);
                                        }
                                        break;

                                    case CommandReturnMessage.ReturnType.Information:
                                        logger.Debug("Txn timmer stoped.");
                                        Txn.SetTimeOutMonitor(false);
                                        lock (Node.ExcuteLock)
                                        {
                                            Node.IsExcuting = false;
                                        }
                                        if (Vendor.ToUpper().Equals("TDK") && Txn.CommandType.Equals("SET"))
                                        {
                                            ReturnMsg.Type = CommandReturnMessage.ReturnType.Excuted;
                                        }
                                        else
                                        {
                                            ReturnMsg.Type = CommandReturnMessage.ReturnType.Finished;
                                            //Node.IsExcuting = false;
                                        }
                                        SpinWait.SpinUntil(() => false, 50);
                                        //ThreadPool.QueueUserWorkItem(new WaitCallback(conn.Send), ReturnMsg.FinCommand);
                                        conn.Send(ReturnMsg.FinCommand);

                                        logger.Debug(DeviceName + " Send:" + ReturnMsg.FinCommand);

                                        break;
                                    }
                                }
                                else
                                {
                                    if (ReturnMsg.Type != null)
                                    {
                                        if (ReturnMsg.Type.Equals(CommandReturnMessage.ReturnType.Information))
                                        {
                                            //ThreadPool.QueueUserWorkItem(new WaitCallback(conn.Send), ReturnMsg.FinCommand);
                                            conn.Send(ReturnMsg.FinCommand);

                                            logger.Debug(DeviceName + " Send:" + ReturnMsg.FinCommand);
                                        }
                                        else
                                        {
                                            if (ReturnMsg.Type == CommandReturnMessage.ReturnType.Error)
                                            {
                                                Txn = TransactionList.First().Value;

                                                logger.Debug("Txn timmer stoped.");
                                                Txn.SetTimeOutMonitor(false);
                                                lock (Node.ExcuteLock)
                                                {
                                                    Node.IsExcuting = false;
                                                }
                                                //_ReportTarget.On_Command_Error(Node, Txn, ReturnMsg);
                                                if (Vendor.ToUpper().Equals("TDK") || DeviceType.ToUpper().Equals("SMARTTAG"))
                                                {
                                                    conn.Send(ReturnMsg.FinCommand);
                                                    logger.Debug(DeviceName + " Send:" + ReturnMsg.FinCommand);
                                                }

                                                TransactionList.TryRemove(TransactionList.First().Key, out Txn);
                                            }
                                            else
                                            {
                                                logger.Debug(DeviceName + "(On_Connection_Message Txn is not found. msg:" + Msg);
                                                continue;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        logger.Debug(DeviceName + "(On_Connection_Message Return type is null. msg:" + Msg);
                                        continue;
                                    }
                                }
                                //}
                            }
                            switch (ReturnMsg.Type)
                            {
                            case CommandReturnMessage.ReturnType.Information:
                            case CommandReturnMessage.ReturnType.Event:
                                Transaction t = new Transaction();
                                t.NodeName         = Node.Name;
                                t.NodeType         = Node.Type;
                                t.Value            = ReturnMsg.Value;
                                t.CommandEncodeStr = ReturnMsg.OrgMsg;
                                t.Method           = ReturnMsg.Command;

                                //TransactionRecord.AddDetail(TransactionRecord.GetUUID(), Node.Name,Node.Type,ReturnMsg.Type,ReturnMsg.Value);
                                _ReportTarget.On_Event_Trigger(Node, ReturnMsg);
                                break;

                            case CommandReturnMessage.ReturnType.Excuted:

                                _ReportTarget.On_Command_Excuted(Node, Txn, ReturnMsg);
                                if (Txn.CommandType.Equals("CMD") && !Node.Type.Equals("LOADPORT"))
                                {
                                    _ReportTarget.On_Node_State_Changed(Node, "Busy");
                                }
                                break;

                            case CommandReturnMessage.ReturnType.Finished:

                                //if (Node.Type.Equals("LOADPORT"))
                                //{
                                //    Node.InterLock = false;
                                //}

                                _ReportTarget.On_Command_Finished(Node, Txn, ReturnMsg);
                                if (!Node.Type.Equals("LOADPORT"))
                                {
                                    _ReportTarget.On_Node_State_Changed(Node, "StandBy");
                                }


                                break;

                            case CommandReturnMessage.ReturnType.Error:

                                //if (Node.Type.Equals("LOADPORT"))
                                //{
                                //    Node.InterLock = false;
                                //}
                                _ReportTarget.On_Command_Error(Node, Txn, ReturnMsg);

                                break;
                            }
                        }
                        else
                        {
                            logger.Debug(DeviceName + "(On_Connection_Message Message decode fail:" + Msg);
                        }
                    }
                    catch (Exception e)
                    {
                        logger.Error(DeviceName + "(On_Connection_Message " + IPAdress + ":" + Port.ToString() + ")" + e.Message + "\n" + e.StackTrace);
                    }
                }
            }
            catch (Exception e)
            {
                logger.Error(DeviceName + "(On_Connection_Message " + IPAdress + ":" + Port.ToString() + ")" + e.Message + "\n" + e.StackTrace);
            }
        }
Example #10
0
        public void StartTimers()
        {
            // Generally a good idea to put a cap in place
            ThreadPool.SetMaxThreads(50, 50);
            _applicationIsRunning = true;

            //
            GetSubmittedTasksTimer.Elapsed += GetSubmittedTasksTimer_Elapsed;
            GetSubmittedTasksTimer.Interval = 10000; // Every 10 seconds
            GetSubmittedTasksTimer.Start();

            // todo: connection pool cleanup task?

            // Dirty Updater
            Task.Run(() =>
            {
                while (_applicationIsRunning)
                {
                    SubmittedTask task;
                    if (_concurrentDirtyTasks.Any() && _concurrentDirtyTasks.TryRemove(_concurrentDirtyTasks.First().Key, out task))
                    {
                        Task.Run(() =>
                        {
                            switch (task.Status)
                            {
                            case TaskStatus.Queued:
                                task.Status        = TaskStatus.Processing;
                                task.StartDateTime = DateTime.UtcNow;
                                task.UpdateExistingTask();

                                // "Process" Task
                                task.Status      = ProcessSubmittedTask(task);
                                task.EndDateTime = DateTime.UtcNow;
                                task.UpdateExistingTask();

                                break;

                            case TaskStatus.Processing:     // Should never hit
                                task.Status      = TaskStatus.Error;
                                task.EndDateTime = DateTime.UtcNow;
                                break;

                            default:     // Finished or Error
                                Console.WriteLine("Task is in finished or error status");
                                break;
                            }

                            SubmittedTask throwAway;
                            _concurrentSubmittedTasks.TryRemove(task.Id, out throwAway); // We use this to stop duplicates from entering dirty queue
                        });
                    }

                    Thread.Sleep(100);
                }
            });
        }
Example #11
0
        /// <summary>
        /// Create powershell instance for each Job and run it on Ruspacepool.
        /// Use Tasks to create threads and collect the results.
        /// If Force parameter is not used and first Job, perform Error check before Queuing remaining Jobs
        /// </summary>
        protected override void ProcessRecord()
        {
            try
            {
                jobNum++;

                do
                {
                    try
                    {
                        //Create a powershell instance for each input object and it will be processed on a seperate thread
                        PowerShell  powerShell = PowerShell.Create();
                        IDictionary psParams   = RunspaceMethods.FindParams(proxyFunction, ScriptToRun, commandName, InputObject);

                        //If command supplied doesn't take any input, bail out.
                        //This check can be removed if this cmdlet needs to run 'something' in parallel, but just didn't find a use case yet
                        if (psParams.Count <= 0)
                        {
                            throw new Exception("No Parameters were used on the command, Please verify the command.");
                        }

                        if (jobNum == 1)
                        {
                            LogHelper.LogProgress("Queuing First Job", this, quiet: Quiet.IsPresent);
                            LogHelper.Log(fileVerboseLogTypes, "Paramaters used for the first job:", this, NoFileLogging.IsPresent);
                            foreach (DictionaryEntry param in psParams)
                            {
                                string paramValues = null;
                                if (param.Value is Array)
                                {
                                    foreach (var val in param.Value as Array)
                                    {
                                        paramValues += val?.ToString() + ", ";
                                    }
                                }
                                else
                                {
                                    paramValues = param.Value?.ToString();
                                }
                                LogHelper.Log(fileVerboseLogTypes, string.Format("{0} - {1}", param.Key.ToString(), paramValues), this, NoFileLogging.IsPresent);
                            }
                        }

                        if (cmdInfo.CommandType == CommandTypes.ExternalScript)
                        {
                            powerShell.AddScript(((ExternalScriptInfo)cmdInfo).ScriptContents).AddParameters(psParams);
                        }
                        else
                        {
                            powerShell.AddCommand(commandName).AddParameters(psParams);
                        }

                        powerShell.RunspacePool = runspacePool;
                        //Creates the task and the continuation tasks
                        Task <PSDataCollection <PSObject> > task = Task <PSDataCollection <PSObject> > .Factory.FromAsync(powerShell.BeginInvoke(), r => powerShell.EndInvoke(r));

                        task.ContinueWith(t =>
                        {
                            var currentJob = CheckandCreateJob(
                                jobName: InputObject.ToString(),
                                task: t,
                                jobID: jobNum,
                                ps: powerShell);
                            currentJob.IsFaulted  = true;
                            currentJob.Exceptions = t.Exception;
                        }, TaskContinuationOptions.OnlyOnFaulted);

                        //Continuation tasks may have already created the Job, check before creating it.
                        Job job = CheckandCreateJob(
                            jobName: InputObject.ToString(),
                            task: task,
                            jobID: jobNum,
                            ps: powerShell);

                        if (!jobs.TryAdd(job.ID, job))
                        {
                            if (jobNum == 1)
                            {
                                //We might retry the Job 1 during Error Check, so ignore the error and replace the first job
                                jobs.TryRemove(jobs.First().Key, out Job removedJob);
                                jobs.TryAdd(job.ID, job);
                            }
                            else
                            {
                                throw new Exception(string.Format("Unable to add job ID: {0}", job.ID));
                            }
                        }

                        if (!Async.IsPresent &&
                            (jobs.Count == BatchSize || (!this.Force.IsPresent && (jobNum == 1))))
                        {
                            CollectJobs(this, jobs, jobNum, ProgressBarStage, Force, ReturnasJobObject, AppendJobNameToResult, jobNum);
                        }

                        if (Async.IsPresent)
                        {
                            WriteObject(job);
                        }
                    }
                    catch (AggregateException ae) when(jobNum == 1 && ae.InnerExceptions.Where(ie => ie is CommandNotFoundException).Count() > 0)
                    {
                        IEnumerable <Exception> exceptions   = ae.InnerExceptions.Where(ie => ie is CommandNotFoundException);
                        List <string>           debugStrings = new List <string>();

                        foreach (Exception exception in exceptions)
                        {
                            CommandInfo commandInfo = RunspaceMethods.GetCommandInfo(((CommandNotFoundException)exception).CommandName);
                            if (commandInfo == null)
                            {
                                throw (CommandNotFoundException)exception;
                            }

                            RunspaceMethods.ModuleDetails moduleDetails = RunspaceMethods.GetModuleDetails(commandInfo, debugStrings);
                            LogHelper.LogDebug(debugStrings, this);
                            LogHelper.Log(fileVerboseLogTypes, exception.Message, this, NoFileLogging);

                            if (moduleDetails.IsFromRemotingModule)
                            {
                                LogHelper.Log(fileVerboseLogTypes, "The command is from a remotePS connection, cannot load local and remote runspaces together", this, NoFileLogging);
                                throw exception;
                            }

                            RunspaceMethods.LoadISSWithModuleDetails(moduleDetails, runspacePool.InitialSessionState);
                        }
                        runspacePool = RunspaceMethods.ResetRunspacePool(1, MaxThreads, runspacePool.InitialSessionState.Clone(), new DummyCustomPSHost());
                        LogHelper.LogDebug("Resetting Runspace to load the new modules", this);
                        LogHelper.Log(fileVerboseLogTypes, "Retrying first job", this, NoFileLogging);
                        runspacePool.Open();
                    }
                } while (!Force.IsPresent && jobNum == 1 && jobs.FirstOrDefault().Value?.IsFaulted == true);

                if (!Force.IsPresent &&
                    (jobs.Values.Where(f => f.IsFaulted == true).Count() / jobNum * 100) > promptOnPercentFaults)
                {
                    if (!ShouldContinue(string.Format("More than {0}% of the jobs are faulted, Do you want to continue with processing rest of the Inputs?", promptOnPercentFaults), "Most Jobs Faulted"))
                    {
                        throw new Exception("Most jobs faulted");
                    }
                }
            }
            catch (Exception e)
            {
                ErrorRecord error = new ErrorRecord(e, e.GetType().Name, ErrorCategory.InvalidData, this);
                LogHelper.Log(fileVerboseLogTypes, error.Exception.ToString(), this, NoFileLogging.IsPresent);
                CleanupObjs(this, proxyFunction, runspacePool, e is PipelineStoppedException);
                ThrowTerminatingError(error);
            }
        }
        private void StopService()
        {
            Debug.WriteLine("StopService has arrived!");

            try
            {
                TheService.Stop();
            }
            catch (InvalidOperationException) {
                Debug.WriteLine("StopService: Service was not running");
            }

            bool isSuccess = false;

            for (int i = 0; i < 3; i++)
            {
                try
                {
                    TheService.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromMilliseconds(timeoutMilliseconds));
                    isSuccess = true;
                    break;
                }
                catch (System.ServiceProcess.TimeoutException)
                {
                    Debug.WriteLine("StopService: Service is not stopped!");
                    continue;
                }
            }

            if (!isSuccess)
            {
                Debug.WriteLine("StopService: Could not stop the service!");
                Program.TheMainAppContext.trayIcon.ShowBalloonTip(0, "GFE could not be stopped!", " ", System.Windows.Forms.ToolTipIcon.Error);
            }
            else
            {
                Program.TheMainAppContext.trayIcon.ShowBalloonTip(0, "GFE has been stopped!", "Triggered By: " + RunningApps.First().Value, System.Windows.Forms.ToolTipIcon.Info);
            }
        }
 public Task <ClientStatistics> GetClientStatisticsAsync()
 {
     return(Task.FromResult(_clientStatistics.First().Value));
 }
Example #14
0
 public T Find <T>(string name) where T : IObject
 {
     return((T)_sceneObjects.First(pair => pair.Value.Name == name).Value);
 }