Beispiel #1
0
 public Mission(string name, string description, PriorityLevel priority, DateTime date)
 {
     this.Name        = name;
     this.Description = description;
     this.Priority    = priority;
     this.date        = date;
 }
 public void PrioritizeDish(string tableNumber, string itemId, PriorityLevel level)
 {
     if (PrioritizeDishEvent != null)
     {
         PrioritizeDishEvent(tableNumber, itemId, level);
     }
 }
        public static ITableStructure CGetStructure(this ITableSource table, PriorityLevel priority, bool behaveAsStack, Action guiCallback)
        {
            IPhysicalConnection conn = table.Connection;
            string key = CGetStructureKey(table);

            return((ITableStructure)conn.CacheGet(priority, behaveAsStack, key, () => table.LoadTableStructure(TableStructureMembers.All), guiCallback));
        }
Beispiel #4
0
        public static ConsoleColor GetColor(PriorityLevel priority)
        {
            switch (priority)
            {
            case PriorityLevel.Urgent:
                return(ConsoleColor.Red);

            case PriorityLevel.High:
                return(ConsoleColor.Yellow);

            case PriorityLevel.Medium:
                return(ConsoleColor.Cyan);

            case PriorityLevel.Low:
                return(ConsoleColor.Blue);

            case PriorityLevel.Sometime:
                return(ConsoleColor.Green);

            case PriorityLevel.None:
                return(ConsoleColor.Magenta);

            default:
                return(ConsoleColor.Gray);
            }
        }
Beispiel #5
0
        protected Message(PriorityLevel priority)
        {
            DecayInS = DefaultDecayInS;
            Priority = priority;

            timeStamp = DateTime.UtcNow;
        }
Beispiel #6
0
        public ActionResult DeleteConfirmed(int id)
        {
            PriorityLevel priorityLevel = db.PriorityLevels.Find(id);

            db.PriorityLevels.Remove(priorityLevel);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
 internal PriorityQueueDecumulator(LinkedPriorityQueue <T> queue)
 {
     m_queue                   = queue;
     m_enumerator              = m_queue.m_priorityLevels.Values.GetEnumerator();
     m_pendingLevelRemovals    = new List <int>();
     m_currentLevelDecumulator = null;
     m_currentLevel            = null;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="PriorityRecord"/> struct.
 /// </summary>
 /// <param name="l">Priority level.</param>
 /// <param name="on">Original file name.</param>
 public PriorityRecord(PriorityLevel l, string on)
 {
     this.Level = l;
     this.OriginalName = on;
     this.StreamId = 0;
     this.StreamOpened = false;
     this.StreamActive = false;
 }
Beispiel #9
0
 public void EnqueueMessage(PriorityLevel priority, Message message)
 {
     lock (messageQueue)
     {
         messageQueue.Enqueue(priority, message);
         //waitForResults.Set();
     }
 }
Beispiel #10
0
 public PriorityQueueDecumulator(LinkedPriorityQueue <T> queue)
 {
     this.m_queue                   = queue;
     this.m_enumerator              = (IEnumerator <PriorityLevel>)(object) this.m_queue.m_priorityLevels.Values.GetEnumerator();
     this.m_pendingLevelRemovals    = new List <int>();
     this.m_currentLevelDecumulator = null;
     this.m_currentLevel            = null;
 }
Beispiel #11
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PriorityRecord"/> struct.
 /// </summary>
 /// <param name="on">Original file name.</param>
 public PriorityRecord(string on)
 {
     this.Level        = PriorityLevel.HighPriority;
     this.OriginalName = on;
     this.StreamId     = 0;
     this.StreamOpened = false;
     this.StreamActive = false;
 }
Beispiel #12
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PriorityRecord"/> struct.
 /// </summary>
 /// <param name="sid">Stream Id.</param>
 public PriorityRecord(int sid)
 {
     this.Level        = PriorityLevel.HighPriority;
     this.OriginalName = string.Empty;
     this.StreamId     = sid;
     this.StreamOpened = false;
     this.StreamActive = false;
 }
Beispiel #13
0
 public static void Register(PriorityLevel priorityLevel, Func <DiscordClientEx, Task <string> > func)
 {
     _playingStatusItems.Enqueue(new PlayingStatusItem <Task <string> >(_idCounter++)
     {
         Priority = priorityLevel,
         Function = func,
         //Delay = delay
     });
 }
Beispiel #14
0
        public void AddSceneLoadCallBack(PriorityLevel priorityLevel, SceneLoadDelegation handler)
        {
            if (!mhtSceneLoadDelegation.ContainsKey(priorityLevel))
            {
                mhtSceneLoadDelegation[priorityLevel] = new SceneLoadDelegationObject();
            }

            mhtSceneLoadDelegation[priorityLevel].list.Add(handler);
        }
 public void RemoveCurrent()
 {
     m_currentLevelDecumulator.RemoveCurrent();
     if (m_currentLevel.Queue.Count == 0)
     {
         m_pendingLevelRemovals.Add(m_currentLevel.Priority);
         m_currentLevel = null;
     }
 }
Beispiel #16
0
        public void TestMappingValuesHighPriority()
        {
            PriorityLevel    priorityLevel = PriorityLevel.High;
            List <Seniority> seniorities   = CallEmployeeMapper.GetCompatibleSeniorities(priorityLevel);

            Assert.AreEqual(2, seniorities.Count);
            Assert.AreEqual(Seniority.Manager, seniorities[0]);
            Assert.AreEqual(Seniority.Director, seniorities[1]);
        }
        private BinaryNode EvaluateBinaryNodeLevel(BinaryNode input, PriorityLevel level)
        {
            if (!input.Rights.Any() || input.Rights.All(x => GetPriorityLevel(x.Operator) != level))
            {
                // nothing to evaluate
                return(input);
            }

            // create chain of expressions from the binary node for simpler functionality
            var wholeExpression = new List <BinaryNodeItem>(input.Rights);

            wholeExpression.Insert(0, input.Left);

            for (var i = 0; i < wholeExpression.Count - 1; ++i)
            {
                var op = wholeExpression[i + 1].Operator;
                if (GetPriorityLevel(op) != level)
                {
                    continue;
                }

                // get all items with same level operator
                var levelItems = new List <BinaryNodeItem> {
                    wholeExpression[i], wholeExpression[i + 1]
                };
                for (var j = i + 2; j < wholeExpression.Count; ++j)
                {
                    var item = wholeExpression[j];

                    // when next operator differs, stop
                    if (GetPriorityLevel(item.Operator) != level)
                    {
                        break;
                    }

                    levelItems.Add(item);
                }

                var resultItem = GetEvaluationOrder(op) == BinaryOperatorEvaluationOrder.Left
                    ? EvaluationBinaryNodeLevelInLeftOrder(levelItems)
                    : EvaluationBinaryNodeLevelInRightOrder(levelItems);

                // replace value in the expression chain
                wholeExpression[i] = resultItem;

                // remove evaluated items from expression
                // skip first which we replaced earlier
                var countToRemove = levelItems.Count - 1;
                for (var j = 0; j < countToRemove; ++j)
                {
                    wholeExpression.RemoveAt(i + 1);
                }
            }

            return(new BinaryNode(wholeExpression[0].Item, wholeExpression.Skip(1)));
        }
Beispiel #18
0
 public ActionResult Edit([Bind(Include = "PriorityLevelId,Description,Value")] PriorityLevel priorityLevel)
 {
     if (ModelState.IsValid)
     {
         db.Entry(priorityLevel).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(priorityLevel));
 }
 public void Update(string title, string note, PriorityLevel priority, bool done, DateTime?reminder)
 {
     Guard.Against.NullOrEmpty(title, nameof(title));
     Guard.Against.Null(priority, nameof(priority));
     Title    = title;
     Note     = note;
     Priority = priority;
     Done     = done;
     Reminder = reminder;
 }
Beispiel #20
0
        public void TestMappingValuesLowPriority()
        {
            PriorityLevel    priorityLevel = PriorityLevel.Low;
            List <Seniority> seniorities   = CallEmployeeMapper.GetCompatibleSeniorities(priorityLevel);

            Assert.AreEqual(3, seniorities.Count);
            Assert.AreEqual(Seniority.Junior, seniorities[0]);
            Assert.AreEqual(Seniority.Senior, seniorities[1]);
            Assert.AreEqual(Seniority.Manager, seniorities[2]);
        }
Beispiel #21
0
        public void TestCallCreationLowPriority()
        {
            int           callId       = 1;
            string        callerName   = "testCaller";
            PriorityLevel callPriority = PriorityLevel.Low;
            Call          call         = new Call(callPriority, callId, callerName);

            Assert.AreEqual(callId, call.CallId);
            Assert.AreEqual(callPriority, call.CallPriority);
            Assert.AreEqual(callerName, call.CallerName);
        }
Beispiel #22
0
 /// <summary>
 /// Get the Power Status of a given device
 /// </summary>
 /// <param name="deviceId">Identify of the target device</param>
 /// <param name="priority">WCS CM Priority level</param>
 /// <returns>SystemPowerState Class</returns>
 public static SystemStatus GetPowerStatus(byte deviceId, PriorityLevel priority = PriorityLevel.User)
 {
     if (clients.ContainsKey(deviceId))
     {
         return(clients[deviceId].GetChassisState());
     }
     else
     {
         return(new SystemStatus((byte)CompletionCode.InvalidDevice));
     }
 }
Beispiel #23
0
        public TrafficRobotUnity() : base()
        {
            TurnOnSupervisorTraffic(false);

            RobotUnitylist             = new List <RobotUnity>();
            prioritLevel               = new PriorityLevel();
            robotRegistryToWorkingZone = new RobotRegistryToWorkingZone();
            robotTag = RobotStatus.IDLE;
            //  robotTag = RobotStatus.WORKING;
            onFlagReadyGo = false;
        }
Beispiel #24
0
 /// <summary>
 /// Инициализирует новый экземпляр класса <see cref="EventItem"/>.
 /// </summary>
 /// <param name="title">Заголовок события.</param>
 /// <param name="text">Текст события.</param>
 /// <param name="alertLevel">Уровень оповещения о событии.</param>
 /// <param name="priority">Приоритет события.</param>
 /// <param name="tags">Метки для дополнительной информации.</param>
 /// <param name="hostname">Имя хоста.</param>
 /// <param name="sourceTypeName">Тип отправителя.</param>
 /// <param name="aggregationKey">Ключ для объединения с другими событиями.</param>
 public EventItem(string title, string text, AlertLevel alertLevel, PriorityLevel priority, string[] tags = null, string hostname = "", string sourceTypeName = "", string aggregationKey = "")
 {
     this.Title          = title;
     this.Text           = text;
     this.AlertLevel     = alertLevel;
     this.Priority       = priority;
     this.Tags           = tags;
     this.Hostname       = hostname;
     this.SourceTypeName = sourceTypeName;
     this.AggregationKey = aggregationKey;
 }
        public static async Task RaiseEventAsync(Notification notification, PriorityLevel priority, string resourcePath)
        {
            // ensure that we have a connection to the Redis server
            // NOTE: we could do this in our constructor, but we have intentionally avoided putting any code there which could block or throw an exception.  Instead we lazily load the redis client here.
            if (_redisClient == null)
            {
                // NOTE: this call will attempt to create the connection if it does not already exists (and will "block" in an async-friendly fashion)
                _redisClient = await Singletons.GetRedisClientAsync();
            }

            // make sure that the event priority is within the valid range
            if ((int)priority < 0 || (int)priority > 7)
            {
                throw new ArgumentOutOfRangeException("Priority must be in the range {0...7}", nameof(priority));
            }
            // make sure that our event has a name
            if (string.IsNullOrEmpty(notification.event_name))
            {
                throw new ArgumentException("Every event must have an event name", nameof(notification));
            }

            // set our event's timestamp
            // NOTE: the timestamp could alternatively be set by Redis (in an atomic transaction, using TIME followed by RPUSH, etc.)
            long createdTimestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();

            notification.notification_time = createdTimestamp;
            // make sure that the event has a data collection (even if it's empty)
            if (notification.data == null)
            {
                notification.data = new Dictionary <string, string>();
            }

            // encode event as JSON
            string jsonEncodedEvent = JsonConvert.SerializeObject(notification, Formatting.None, new JsonSerializerSettings()
            {
                NullValueHandling = NullValueHandling.Ignore
            });

            byte[] createdTimestampAsBytes     = System.BitConverter.GetBytes(createdTimestamp * 1000);
            byte[] resourcePathAndEventAsBytes = Encoding.UTF8.GetBytes(resourcePath + REDIS_SUFFIX_SEPARATOR + notification.event_name);
            byte[] jsonEncodedEventAsBytes     = System.Text.Encoding.UTF8.GetBytes(jsonEncodedEvent);
            byte[] valueAsBytes    = new byte[createdTimestampAsBytes.Length + resourcePathAndEventAsBytes.Length + 1 + jsonEncodedEventAsBytes.Length];
            int    valueAsBytesPos = 0;

            Array.Copy(createdTimestampAsBytes, 0, valueAsBytes, valueAsBytesPos, createdTimestampAsBytes.Length);
            valueAsBytesPos += createdTimestampAsBytes.Length;
            Array.Copy(resourcePathAndEventAsBytes, 0, valueAsBytes, valueAsBytesPos, resourcePathAndEventAsBytes.Length);
            valueAsBytesPos += resourcePathAndEventAsBytes.Length;
            valueAsBytes[valueAsBytesPos] = 0x00; // we insert a 0x00 byte between the resource path and the event json as a marker (NOTE: 0x00 should never naturally occur in the middle of a UTF8 string)
            valueAsBytesPos++;
            Array.Copy(jsonEncodedEventAsBytes, 0, valueAsBytes, valueAsBytesPos, jsonEncodedEventAsBytes.Length);

            await _redisClient.ListPushRightAsync <string, byte[]>(REDIS_PREFIX_SERVICE + REDIS_PREFIX_SEPARATOR + REDIS_ASTERISK + REDIS_SLASH + EVENT_SERVICE_NAME + REDIS_SUFFIX_SEPARATOR + REDIS_SUFFIX_INCOMING_NOTIFICATIONS + ((int)priority).ToString(), new byte[][] { valueAsBytes });
        }
Beispiel #26
0
        public ActionResult Create([Bind(Include = "PriorityLevelId,Description,Value")] PriorityLevel priorityLevel)
        {
            if (ModelState.IsValid)
            {
                db.PriorityLevels.Add(priorityLevel);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(priorityLevel));
        }
Beispiel #27
0
        /// <summary>
        /// This method will be used to log exceptions
        /// </summary>
        /// <param name="eGlobalErr">Global Error thrown by Custom Code</param>
        /// <param name="priorityLevel">Priority Level of the Error Low,Medium,High,Critical</param>
        /// <param name="inputFriendlyMessage">Needed if the message is a customized error message thrown from a plugin or custom step</param>
        /// <param name="service">Organization Service</param>
        /// <returns>Returns the friendly message to be shown to the user</returns>

        internal static string LogException(Exception ex, PriorityLevel priorityLevel, IOrganizationService service)
        {
            string result = string.Empty;

            try
            {
                //set log exception request
                OrganizationRequest logExceptionRequest = new OrganizationRequest("e4d_LogException");
                logExceptionRequest["message"]    = ex.Message;
                logExceptionRequest["priority"]   = new OptionSetValue((int)priorityLevel);
                logExceptionRequest["stackTrace"] = ex.StackTrace;

                //set ExecuteMultipleRequest request to wrap log Exception Request
                //this is required to escape the Plugin transaction which if rolled back, will delete the Exception record
                ExecuteMultipleRequest executeMultipleRequest = new ExecuteMultipleRequest()
                {
                    Requests = new OrganizationRequestCollection(),
                    Settings = new ExecuteMultipleSettings()
                    {
                        ContinueOnError = true,
                        ReturnResponses = true
                    }
                };

                //add logExceptionRequest to multiple requests collection
                executeMultipleRequest.Requests.Add(logExceptionRequest);

                //execute ExecuteMultipleRequest
                ExecuteMultipleResponse resp = (ExecuteMultipleResponse)service.Execute(executeMultipleRequest);

                //parse ExecuteMultipleRequest response
                foreach (var responseItem in resp.Responses)
                {
                    //valid response returned
                    if (responseItem.Response != null)
                    {
                        OrganizationResponse response = (OrganizationResponse)responseItem.Response;
                        result = (string)response["friendlyMessage"];
                    }
                    //error occurred
                    else if (responseItem.Fault != null)
                    {
                        result = responseItem.Fault.Message;
                    }
                }
            }
            catch (FaultException <OrganizationServiceFault> fault)
            {
                result = fault.Message;
            }

            return(result);
        }
Beispiel #28
0
 /// <summary>
 /// Constructor for easily creating entries.
 /// </summary>
 /// <param name="id">The ID for the entry. </param>
 /// <param name="year">The year (1 through 9999) for the entry year.</param>
 /// <param name="month">The month (1 through 12) for the entry month.</param>
 /// <param name="day">The day (1 through the number of days for the month) for the entry day.</param>
 /// <param name="bugType">The bug type for the entry.</param>
 /// <param name="currentStatus">The status of the entry.</param>
 /// <param name="priority">The priority of the entry.</param>
 /// <param name="exclude">Whether or not the entry should be excluded from the list of known issues.</param>
 /// <param name="notes">The notes for the entry.</param>
 public Entry(int id, int year, int month, int day, Bug.BugType bugType, CurrentStatus currentStatus = CurrentStatus.Open,
              PriorityLevel priority = PriorityLevel.Medium,
              bool exclude           = false, string notes = null)
 {
     Id       = id;
     Date     = new DateTime(year, month, day);
     BugId    = (int)bugType;
     Status   = currentStatus;
     Priority = priority;
     Exclude  = exclude;
     Notes    = notes;
 }
 internal void Enqueue(T item, int priority)
 {
     Global.Tracer.Assert(!m_pendingDecumulatorCommit, "Cannot perform operations on the queue until the open enumerator is Disposed");
     if (!m_priorityLevels.TryGetValue(priority, out PriorityLevel value))
     {
         value                      = new PriorityLevel();
         value.Priority             = priority;
         value.Queue                = new LinkedBucketedQueue <T>(100);
         m_priorityLevels[priority] = value;
     }
     value.Queue.Enqueue(item);
 }
Beispiel #30
0
 private void DoPut(PriorityLevel priority, bool behaveAsStack, T element)
 {
     if (behaveAsStack)
     {
         m_queue[priority].AddFirst(element);
     }
     else
     {
         m_queue[priority].AddLast(element);
     }
     m_length++;
     m_onPutEvent.Set();
 }
Beispiel #31
0
        private bool BeInRange(PriorityLevel priority)
        {
            if (priority == 0 ||
                priority == PriorityLevel.None ||
                priority == PriorityLevel.Low ||
                priority == PriorityLevel.Medium ||
                priority == PriorityLevel.High)
            {
                return(true);
            }

            return(false);
        }
 public InternalNodeSettings(System.Windows.Forms.CheckState enabled,
     PriorityLevel priority,
     Int32 repeat,
     Int32 offsetX,
     Int32 offsetY,
     MouseSpeed mouseSpeed)
 {
     _enabled = enabled;
     _priority = priority;
     _runs = repeat;
     _offsetX = offsetX;
     _offsetY = offsetY;
     _mouseSpeed = mouseSpeed;
 }
 public static string ToString(object instance,
                               PriorityLevel verbosity)
 {
     return ToString(instance, (int) verbosity);
 }
Beispiel #34
0
            public ProcessTuneSection(PriorityLevel Priority)
            {
                HighPriority = (PriorityLevel.High == Priority);
                UseAuxLowPriorityThreadPool = (PriorityLevel.Low == Priority);

                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

                //Console.WriteLine(config.FilePath);
                // Add configuration information to the
                // configuration file.
                if (null != config.Sections.Get(SECTION_NAME))
                {
                    config.Sections.Remove(SECTION_NAME);
                }
                config.Sections.Add(SECTION_NAME, this);
                config.Save();
                // Force a reload of the changed section.
                // This makes the new values available for reading.
                //ConfigurationManager.RefreshSection(sectionName);
            }
 /// <summary>
 /// Get the Power Status of a given device
 /// </summary>
 /// <param name="deviceId">Identify of the target device</param>
 /// <param name="priority">WCS CM Priority level</param>
 /// <returns>SystemPowerState Class</returns>
 public static SystemStatus GetPowerStatus(byte deviceId, PriorityLevel priority = PriorityLevel.User)
 {
     if (clients.ContainsKey(deviceId))
     {
         return clients[deviceId].GetChassisState();
     }
     else
     {
         return new SystemStatus((byte)CompletionCode.InvalidDevice);
     }
 }
Beispiel #36
0
 /// <summary>
 /// Get the work queue associated a given priority level
 /// Return value can be null and the caller must check
 /// </summary>
 /// <param name="priorityLevel"></param>
 /// <returns></returns>
 private Queue GetWorkQueue(PriorityLevel priorityLevel)
 {
     if (priorityLevel == PriorityLevel.System)
     {
         return workQueues[0];
     }
     else if (priorityLevel == PriorityLevel.User)
     {
         return workQueues[1];
     }
     else
     {
         Tracer.WriteError("[Error] Invalid prioirty level ({0})", priorityLevel);
         return null;
     }
 }
Beispiel #37
0
        /// <summary>
        /// Add a work item into a work queue.
        /// Return fail if the parameter is not valid and/or
        /// the target queue is currently full
        /// The caller must check the return value
        /// </summary>
        /// <param name="priorityLevel"></param>
        /// <param name="workItem"></param>
        /// <returns></returns>
        internal bool SendReceive(PriorityLevel priorityLevel, WorkItem workItem)
        {
            Queue workQueue = GetWorkQueue(priorityLevel);

            // Invalid priority level
            if (workQueue == null)
            {
                return false;
            }

            // Must be thread-safe as other user-level thread or the device-level thread
            // can concurrently access the queue
            lock (workQueue.SyncRoot)
            {
                if (workQueue.Count > maxQueueLength)
                {
                    // Invalid execution path: should not reach here
                    Tracer.WriteError("[Error, PortManager: {0}, priorityLevel: {1}] Queue (size: {2}) overflowed",
                        logicalPortId, priorityLevel, workQueue.Count);
                    return false;
                }
                else if (workQueue.Count == maxQueueLength)
                {
                    // The work queue is current full and cannot serve the request
                    Tracer.WriteWarning("[PortManager: {0}, priorityLevel: {1}] Full", logicalPortId, priorityLevel);
                    return false;
                }

                // Insert the work item
                workQueue.Enqueue(workItem);
            }

            // Signal the worker thread to process the work item that has been just inserted
            autoEvent.Set();

            // The work item has been successfully inserted
            return true;
        }
 public static SensorReading GetSensorReading(byte deviceId, byte sensorNumber, PriorityLevel priority = PriorityLevel.User)
 {
     if (clients.ContainsKey(deviceId))
     {
         return clients[deviceId].GetSensorReading(sensorNumber, priority);
     }
     else
     {
         return new SensorReading((byte)CompletionCode.InvalidDevice);
     }
 }
        private static void SendReceiveDevices(PriorityLevel priority, byte deviceType, ref byte[] request, int numDevices)
        {
            byte deviceId;
            byte[] response;

            for (byte i = 1; i <= numDevices; i++)
            {
                response = null;
                deviceId = i;
                CommunicationDevice.SendReceive(priority, deviceType, deviceId, request, out response);
                CheckAndPrintResponsePacket(deviceId, ref response);
            }
        }
        /// <summary>
        /// Every component in the higher level of the stack should call this method
        /// to send/receive data to/from actual hardware devices
        /// </summary>
        /// <param name="priorityLevel"></param>
        /// <param name="deviceType"></param>
        /// <param name="deviceId"></param>
        /// <param name="request">
        /// Input
        /// [0]: function code
        /// [1:2]: byte count (N)
        /// [3:N+2]: payload
        /// </param>
        /// <param name="response">
        /// Output
        /// [0]: completion code
        /// [1:2]: byte count (N)
        /// [3:N+2]: payload
        /// Note: response can be null
        /// </param>
        internal static void SendReceive(PriorityLevel priorityLevel, byte deviceType, byte deviceId, byte[] request, out byte[] response)
        {
            Tracer.WriteInfo("CommunicationDevice.SendReceive({0})", deviceType);
            ushort sessionId = IncrementTimeStampAndGetSessionId();
            byte physicalId;

            // If CM is terminating, do not accept any more new requests
            if (isTerminating == true)
            {
                ResponsePacketUtil.GenerateResponsePacket(CompletionCode.ServiceTerminating, out response);
                return;
            }

            if (IsValidRequest(deviceType, deviceId, ref request) == false)
            {
                ResponsePacketUtil.GenerateResponsePacket(CompletionCode.InvalidCommand, out response);
                return;
            }

            physicalId = GetPhysicalIdFromLogicalId(deviceType, deviceId);
            Tracer.WriteInfo("CommunicationDevice.SendReceive PhysicalID ({0})", physicalId);

            using (WorkItem workItem = new WorkItem(deviceType, physicalId, request, sessionId))
            {
                byte logicalPortId = (byte)LogicalPortId.InvalidLogicalPortId;
                byte functionCode = RequestPacketUtil.GetFunctionCode(ref request);

                switch (deviceType)
                {
                    case (byte)DeviceType.Server:
                        logicalPortId = (byte)LogicalPortId.SerialPortServers;
                        break;
                    case (byte)DeviceType.SerialPortConsole:
                        // TODO: Extend the code for more serial consoles
                        if (deviceId == 1)
                        {
                            logicalPortId = (byte)LogicalPortId.SerialPortConsole1;
                        }
                        else if (deviceId == 2)
                        {
                            logicalPortId = (byte)LogicalPortId.SerialPortConsole2;
                        }
                        else if (deviceId == 3)
                        {
                            logicalPortId = (byte)LogicalPortId.SerialPortConsole3;
                        }
                        else if (deviceId == 4)
                        {
                            logicalPortId = (byte)LogicalPortId.SerialPortConsole4;
                        }
                        break;
                    default:
                        logicalPortId = (byte)LogicalPortId.SerialPortOtherDevices;
                        break;
                }

                if (logicalPortId == (byte)LogicalPortId.InvalidLogicalPortId)
                {
                    ResponsePacketUtil.GenerateResponsePacket(CompletionCode.InvalidCommand, out response);
                    return;
                }

                if (portManagers[logicalPortId].SendReceive(priorityLevel, workItem) == true)
                {
                    // Successfully added the request in the work queue
                    Tracer.WriteInfo("[logicalPortId: {0}, priorityLevel: {1}] SendReceive succeeded and wait", logicalPortId, priorityLevel);

                    // Sleep until signaled by the device worker thread
                    // Wait time: wait time in the queue + worker thread processing time
                    workItem.Wait();

                    // Copy the response to the output buffer
                    workItem.GetResponse(out response);
                }
                else
                {
                    // Could not add the reuqest in the work queue
                    Tracer.WriteWarning("[logicalPortId: {0}, priorityLevel: {1}] SendReceive failed", logicalPortId, priorityLevel);
                    ResponsePacketUtil.GenerateResponsePacket(CompletionCode.OutOfSpace, out response);
                }
            }
        }
 public CustomRule(string description, string details, PriorityLevel priorityLevel, int certainty)
 {
     this.description = description;
     this.details = details;
     this.priorityLevel = priorityLevel;
     this.certainty = certainty;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="PriorityRecord"/> struct.
 /// </summary>
 /// <param name="sid">Stream Id.</param>
 public PriorityRecord(int sid)
 {
     this.Level = PriorityLevel.HighPriority;
     this.OriginalName = string.Empty;
     this.StreamId = sid;
     this.StreamOpened = false;
     this.StreamActive = false;
 }
 public SelfDescribingPriorityAttribute(PriorityLevel priority)
 {
     this.level = (int) priority;
 }