Пример #1
0
        private void HandleModelShutdown(string channelName, List <MessageQueue> queues)
        {
            if (!_Terminate)
            {
                ChannelHandler handler = null;
                lock (_ChannelHandlers)
                {
                    if (_ChannelHandlers.TryGetValue(channelName, out handler))
                    {
                        lock (_Queues)
                        {
                            foreach (MessageQueue item in queues)
                            {
                                _SubscriptionToAdd.Enqueue(item);
                            }
                        }
                        _ChannelHandlers.Remove(channelName);
                    }
                }
                _TriggerSubscriptionRequest.Set();
            }
            int openChannel = Interlocked.Decrement(ref _OpenChannels);

            if (openChannel == 0)
            {
                ApplicationEventLog.WriteEntry("Flow", string.Concat("RabbitMQSubscription - HandleModelShutdown recovery, channel = ", channelName), System.Diagnostics.EventLogEntryType.Warning);
                _ConnectionShutdown = true;
                _TriggerSubscriptionRequest.Set();
            }
        }
Пример #2
0
        private void DeleteMessageFile(string fileName)
        {
            bool deleted = false;

            try
            {
                File.Delete(fileName);
                deleted = true;
            }
            catch
            {
            }
            if (!deleted)
            {
                try
                {
                    string messageFilename = Path.ChangeExtension(fileName, ".del");
                    File.Move(fileName, messageFilename);
                }
                catch (Exception ex)
                {
                    ApplicationEventLog.WriteEntry("Flow", string.Format("DALRabbitMQ::DeleteMessageFile - Exception\n{0}", ex), System.Diagnostics.EventLogEntryType.Error);
                }
            }
        }
Пример #3
0
        private void InvokeCallBack(IAsyncResult asyncResult)
        {
            MessageArrivedState state = asyncResult.AsyncState as MessageArrivedState;

            if (state != null)
            {
                ServiceEventMessage message = state.Message;
                try
                {
                    state.Handler.EndInvoke(asyncResult);
                }
                catch (Exception ex)
                {
                    ApplicationEventLog.WriteEntry("Flow", ex.ToString(), System.Diagnostics.EventLogEntryType.Error);
                    message.QueueAfterTime = DateTime.UtcNow.AddSeconds(1.0);
                    NackMessage(message);
                }
                lock (state.AckMessageInfo)
                {
                    state.AckMessageInfo.Total = state.AckMessageInfo.Total + 1;
                    if (state.AckMessageInfo.Total == state.AckMessageInfo.TotalExpected)
                    {
                        RespondToMessage(message, state.Queue, state.AckMessageInfo);
                        state.AckMessageInfo.ChannelHandler.ProcessedMessage();
                    }
                }
            }
        }
Пример #4
0
        private void DoAcceptCallback(IAsyncResult asyncResult)
        {
            Socket listener = (Socket)asyncResult.AsyncState;
            Socket client   = null;

            try
            {
                if (!_Terminate)
                {
                    client = listener.EndAccept(asyncResult);
                }
            }
            catch (Exception ex)
            {
                ApplicationEventLog.WriteEntry(ex.ToString(), System.Diagnostics.EventLogEntryType.Error);
            }
            if (!_Terminate)
            {
                listener.BeginAccept(new AsyncCallback(DoAcceptCallback), listener);
            }
            if (client != null)
            {
                ReceiveStateObject stateObject = new ReceiveStateObject();
                stateObject.Client = client;
                SocketError socketError;
                stateObject.StartReceive = DateTime.Now;
                client.BeginReceive(stateObject.Buffer, 0, ReceiveStateObject.BufferSize, SocketFlags.None, out socketError, new AsyncCallback(DoReceiveCallback), stateObject);
            }
        }
Пример #5
0
        public void Start()
        {
            _Terminate = false;
            bool       socketOpened = false;
            IPEndPoint endPoint;

            try
            {
                _Socket = new Socket(_AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                if (_AddressFamily == AddressFamily.InterNetworkV6)
                {
                    endPoint = new IPEndPoint(IPAddress.IPv6Any, _Port);
                    _Socket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, true);
                }
                else
                {
                    endPoint = new IPEndPoint(IPAddress.Any, _Port);
                }

                BindSocket(_Socket, endPoint);
                socketOpened = true;
            }
            catch (SocketException ex)
            {
                ApplicationEventLog.WriteEntry(string.Concat("Socket error - ", ex.SocketErrorCode.ToString(), Environment.NewLine, ex.StackTrace), System.Diagnostics.EventLogEntryType.Warning);
            }
            if (!socketOpened)
            {
                throw new Exception("No socket opened");
            }
        }
Пример #6
0
        private void ProcessUpdateRequest(Exchange exchange)
        {
            Request  request = exchange.Request;
            Guid     clientID;
            Response response;

            if (StringUtils.GuidTryDecode(request.UriPath.Substring(4), out clientID))
            {
                LWM2MClient client = BusinessLogicFactory.Clients.GetClient(clientID);
                if (client == null)
                {
                    response = Response.CreateResponse(request, StatusCode.NotFound);
                }
                else
                {
                    client.Parse(request.UriQueries);
                    BusinessLogicFactory.Clients.UpdateClientActivity(client);
                    client.Address  = request.Source;
                    client.EndPoint = exchange.EndPoint;
                    bool updatedLifeTime = false;
                    if ((request.ContentType == (int)MediaType.ApplicationLinkFormat) || (request.ContentType == -1))
                    {
                        if (request.PayloadSize > 0)
                        {
                            ObjectTypes objectTypes = new ObjectTypes();
                            objectTypes.Parse(request.PayloadString);
                            if (ObjectTypes.Compare(client.SupportedTypes, objectTypes) != 0)
                            {
                                client.SupportedTypes = objectTypes;
                                if (client.ClientID != Guid.Empty)
                                {
                                    DataAccessFactory.Clients.SaveClient(client, TObjectState.Add);
                                    updatedLifeTime = true;
                                }
                                BusinessLogicFactory.Clients.ClientChangedSupportedTypes(client);
                            }
                        }
                    }
                    if (!updatedLifeTime)
                    {
                        BusinessLogicFactory.Clients.UpdateClientLifetime(client.ClientID, client.Lifetime);
                    }
                    response = Response.CreateResponse(request, StatusCode.Changed);

                    ApplicationEventLog.Write(LogLevel.Information, string.Concat("Client update ", client.Name, " address ", client.Address.ToString()));
                }
            }
            else
            {
                ApplicationEventLog.WriteEntry(string.Concat("Invalid update location", request.UriPath));
                response = Response.CreateResponse(request, StatusCode.BadRequest);
            }
            exchange.SendResponse(response);
        }
        private void SendChangeNotification(Notification notification)
        {
            List <NotificationTcpClient> clients;

            if (_NotificationClients.TryGetValue(notification.Table, out clients))
            {
                string messageText;
                messageText = string.Concat(MESSAGE_NOTIFY, notification.Table, ",", notification.Purge.ToString(), ",", notification.ID, "\n");
                byte[] buffer = Encoding.ASCII.GetBytes(messageText);
                for (int index = 0; index < clients.Count; index++)
                {
                    if (clients[index].ClientSocket == null)
                    {
                        clients.RemoveAt(index);
                        index--;
                    }
                    else
                    {
                        try
                        {
                            SocketAsyncEventArgs parameters = new SocketAsyncEventArgs();
                            parameters.SetBuffer(buffer, 0, buffer.Length);
                            parameters.UserToken  = clients[index];
                            parameters.Completed += SendCompleted;
                            if (!clients[index].ClientSocket.SendAsync(parameters))
                            {
                                if (parameters.SocketError != SocketError.Success)
                                {
#if DEBUG
                                    ApplicationEventLog.WriteEntry("Flow", string.Format("SendChangeNotification: Error sending notification for table {0} - error ={1}", notification.Table, parameters.SocketError), System.Diagnostics.EventLogEntryType.Error);
                                    Trace.WriteLine(TTracePriority.High, string.Format("SendChangeNotification: Error sending notification for table {0} - error ={1}", notification.Table, parameters.SocketError));
#endif
                                    clients.RemoveAt(index);
                                    index--;
                                }
                            }
                        }
#pragma warning disable 168
                        catch (Exception ex)
#pragma warning restore 168
                        {
#if DEBUG
                            ApplicationEventLog.WriteEntry("Flow", string.Format("SendChangeNotification: Exception sending notification for table {0} Client Count={1}\n{2}", notification.Table, clients.Count, ex), System.Diagnostics.EventLogEntryType.Error);
                            Trace.WriteLine(TTracePriority.High, ex.ToString());
#endif
                            clients.RemoveAt(index);
                            index--;
                        }
                    }
                }
            }
        }
Пример #8
0
        private void ProcessRequests()
        {
            while (!_Terminate)
            {
                _TriggerProcessRequests.Reset();
                while (_Requests.Count > 0)
                {
                    ClientRequest clientRequest = null;
                    try
                    {
                        lock (_Requests)
                        {
                            if (_Requests.Count > 0)
                            {
                                clientRequest = _Requests.Dequeue();
                            }
                        }
                        if (clientRequest != null)
                        {
                            switch (clientRequest.RequestType)
                            {
                            case TRequestType.NotSet:
                                break;

                            case TRequestType.Register:
                                ProcessRegisterRequest(clientRequest.Exchange);
                                break;

                            case TRequestType.Update:
                                ProcessUpdateRequest(clientRequest.Exchange);
                                break;

                            case TRequestType.Deregister:
                                ProcessDeregisterRequest(clientRequest.Exchange);
                                break;

                            default:
                                break;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        ApplicationEventLog.WriteEntry("Flow", ex.ToString(), System.Diagnostics.EventLogEntryType.Error);
                    }
                }
                if (!_Terminate)
                {
                    _TriggerProcessRequests.WaitOne();
                }
            }
        }
Пример #9
0
        public bool ExecuteResource(Guid clientID, Guid objectDefinitionID, string instanceID, Guid propertyDefinitionID)
        {
            bool result = false;

            try
            {
                LWM2MClient client = BusinessLogicFactory.Clients.GetClient(clientID);
                if (client != null)
                {
                    ObjectDefinitionLookups lookups          = BusinessLogicFactory.Clients.GetLookups();
                    ObjectDefinition        objectDefinition = lookups.GetObjectDefinition(objectDefinitionID);
                    if (objectDefinition != null)
                    {
                        int objectID;
                        if (int.TryParse(objectDefinition.ObjectID, out objectID))
                        {
                            Model.ObjectType objectType = client.SupportedTypes.GetObjectType(objectID);
                            if (objectType != null)
                            {
                                PropertyDefinition propertyDefinition = objectDefinition.GetProperty(propertyDefinitionID);
                                if (propertyDefinition != null)
                                {
                                    Request  request  = client.NewPostRequest(objectType, instanceID, propertyDefinition.PropertyID, -1, null);
                                    Response response = client.SendRequest(request).WaitForResponse(LWM2MClient.REQUEST_TIMEOUT);
                                    if (response == null)
                                    {
                                        throw new TimeoutException();
                                    }
                                    else
                                    {
                                        if (response.StatusCode == StatusCode.Changed)
                                        {
                                            result = true;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ApplicationEventLog.WriteEntry("Flow", ex.ToString(), System.Diagnostics.EventLogEntryType.Error);
            }
            return(result);
        }
Пример #10
0
 private void RespondToMessage(ServiceEventMessage message, MessageQueue messageQueue, AckMessageInfo ackMessageInfo)
 {
     try
     {
         messageQueue.Messages.Remove(ackMessageInfo.DeliveryID);
         if (ackMessageInfo.TotalNack == 0)
         {
             if (ackMessageInfo.TotalAck == 0)
             {
                 _DALRabbitMQ.Reject(message);
             }
             if (messageQueue.Channel != null && messageQueue.Channel.IsOpen)
             {
                 messageQueue.Channel.BasicAck(ackMessageInfo.DeliveryTag, false);
             }
         }
         else
         {
             if (message.Parameters.ContainsKey("RequeueCount"))
             {
                 message.Parameters["RequeueCount"] = (int)((long)(message.Parameters["RequeueCount"])) + 1;
             }
             else
             {
                 message.Parameters.Add("RequeueCount", (int)1);
             }
             _DALRabbitMQ.Requeue(message);
             if (!message.QueueAfterTime.HasValue)
             {
                 Thread.Sleep(50);
             }
             if (messageQueue.Channel != null && messageQueue.Channel.IsOpen)
             {
                 messageQueue.Channel.BasicAck(ackMessageInfo.DeliveryTag, false);
             }
             //_Model.BasicReject(ackMessageInfo.DeliveryTag, true);
         }
     }
     catch (Exception ex)
     {
         _ConnectionShutdown = true;
         _TriggerSubscriptionRequest.Set();
         ApplicationEventLog.WriteEntry("Flow", string.Concat("Failed to Ack/Nack", messageQueue.QueueName, ":\r\n", ex.ToString()), System.Diagnostics.EventLogEntryType.Error);
     }
 }
Пример #11
0
        private void BindSocket(Socket socket, EndPoint endPoint)
        {
            bool     bound   = false;
            DateTime timeOut = DateTime.Now.AddSeconds(3);

            while (!bound && DateTime.Now < timeOut)
            {
                try
                {
                    socket.Bind(endPoint);
                    bound = true;
                }
                catch (SocketException)
                {
                    Thread.Sleep(100);
                }
            }
            if (!bound)
            {
                ApplicationEventLog.WriteEntry("Failed to start listening - could not bind to " + endPoint.ToString(), System.Diagnostics.EventLogEntryType.Error);
            }
            else
            {
                socket.NoDelay = true;
                bool connected = false;
                timeOut = DateTime.Now.AddSeconds(3);
                while (!connected && DateTime.Now < timeOut)
                {
                    try
                    {
                        socket.Listen(100);
                        socket.BeginAccept(new AsyncCallback(DoAcceptCallback), socket);
                        connected = true;
                    }
                    catch (SocketException)
                    {
                        Thread.Sleep(100);
                    }
                }
                if (!connected)
                {
                    ApplicationEventLog.WriteEntry("Failed to start listening", System.Diagnostics.EventLogEntryType.Error);
                }
            }
        }
Пример #12
0
        private bool SetupNotification(NotificationClient notificationClient, int attemptsCount)
        {
            bool result = false;
            NotificationServer notificationServer = null;
            int count = 0;

            while ((notificationServer == null) && (count < attemptsCount))
            {
                notificationServer = GetNextNotificationServer();
                if ((notificationServer != null) && (notificationServer.AllowConnectionAfter > DateTime.Now))
                {
                    notificationServer = null;
                }
                else if ((notificationServer == null) || !notificationServer.Connected || !notificationServer.TcpClient.Connected)
                {
                    if (!Connect(notificationServer, true))
                    {
                        notificationServer = null;
                    }
                }
                if (notificationServer != null)
                {
                    byte[] buffer = Encoding.ASCII.GetBytes(string.Concat(SETUP_NOTIFICATION, notificationClient.TableName, "|"));
                    try
                    {
                        Send(notificationServer.TcpClient, buffer);
                        Interlocked.Increment(ref _NotificationClientCount);
                        notificationClient.Enabled = true;
                        lock (notificationServer)
                        {
                            notificationServer.AddClient(notificationClient);
                        }
                        result = true;
                    }
                    catch (Exception ex)
                    {
                        ApplicationEventLog.WriteEntry("Flow", string.Format("DALChangeNotification::SetupNotification {0}", ex), System.Diagnostics.EventLogEntryType.Error);
                        notificationServer = null;
                    }
                }
                count = (count + 1) % int.MaxValue;
            }
            return(result);
        }
Пример #13
0
        public Property GetObjectProperty(Guid clientID, Guid objectDefinitionID, string instanceID, Guid propertyDefinitionID)
        {
            Property result = null;

            try
            {
                LWM2MClient client = BusinessLogicFactory.Clients.GetClient(clientID);
                if (client != null)
                {
                    ObjectDefinitionLookups lookups          = BusinessLogicFactory.Clients.GetLookups();
                    ObjectDefinition        objectDefinition = lookups.GetObjectDefinition(objectDefinitionID);
                    if (objectDefinition != null)
                    {
                        int objectID;
                        if (int.TryParse(objectDefinition.ObjectID, out objectID))
                        {
                            Model.ObjectType objectType = client.SupportedTypes.GetObjectType(objectID);
                            if (objectType != null)
                            {
                                PropertyDefinition propertyDefinition = objectDefinition.GetProperty(propertyDefinitionID);
                                if (propertyDefinition != null)
                                {
                                    Request  request  = client.NewGetRequest(objectType, instanceID, propertyDefinition.PropertyID);
                                    Response response = client.SendRequest(request).WaitForResponse(LWM2MClient.REQUEST_TIMEOUT);
                                    if (response != null && response.StatusCode == StatusCode.Content)
                                    {
                                        BusinessLogicFactory.Clients.UpdateClientActivity(client);
                                        result = ParseProperty(objectDefinition, propertyDefinition, request.Accept, response);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ApplicationEventLog.WriteEntry("Flow", ex.ToString(), System.Diagnostics.EventLogEntryType.Error);
            }
            return(result);
        }
Пример #14
0
 public void CancelObserveObjectProperty(Guid clientID, Guid objectDefinitionID, string instanceID, Guid propertyDefinitionID, bool useReset)
 {
     try
     {
         LWM2MClient client = BusinessLogicFactory.Clients.GetClient(clientID);
         if (client != null)
         {
             ObjectDefinitionLookups lookups          = BusinessLogicFactory.Clients.GetLookups();
             ObjectDefinition        objectDefinition = lookups.GetObjectDefinition(objectDefinitionID);
             if (objectDefinition != null)
             {
                 int objectID;
                 if (int.TryParse(objectDefinition.ObjectID, out objectID))
                 {
                     Model.ObjectType objectType = client.SupportedTypes.GetObjectType(objectID);
                     if (objectType != null)
                     {
                         if (propertyDefinitionID != Guid.Empty)
                         {
                             PropertyDefinition propertyDefinition = objectDefinition.GetProperty(propertyDefinitionID);
                             if (propertyDefinition != null)
                             {
                                 client.CancelObserve(objectType, instanceID, propertyDefinition.PropertyID, useReset);
                             }
                         }
                         else
                         {
                             client.CancelObserve(objectType, instanceID, null, useReset);
                         }
                     }
                 }
             }
         }
     }
     catch (Exception ex)
     {
         ApplicationEventLog.WriteEntry("Flow", ex.ToString(), System.Diagnostics.EventLogEntryType.Error);
     }
 }
Пример #15
0
        private void NotifyClients(string tableName, bool purge, string id)
        {
            if (_TableChangeClients.ContainsKey(tableName))
            {
                List <NotificationClient> handlers = _TableChangeClients[tableName];
                NotificationEventArgs     e        = new NotificationEventArgs();
                e.Purge = purge;
                e.ID    = id;
                for (int index = 0; index < handlers.Count; index++)
                {
                    try
                    {
                        if (handlers[index].Enabled)
                        {
                            if (_Async)
                            {
                                handlers[index].EventHandler.BeginInvoke(null, e, _NotifyClientsCallback, handlers[index]);
                            }
                            else
                            {
                                handlers[index].EventHandler.Invoke(null, e);
                            }
                        }
#if UNITTEST_DEBUG
                        else if (!handlers[index].Enabled)
                        {
                            ApplicationEventLog.WriteEntry("Flow", string.Format("NotifyClients: Failed to send notification for table {0}.\n{1}\n{2}\n{3}", tableName, handlers[index].Enabled, handlers[index].Server, handlers[index].ConnnectionString), EventLogEntryType.Error);
                        }
#endif
                    }
                    catch (Exception ex)
                    {
                        ApplicationEventLog.WriteEntry("Flow", string.Format("NotifyClients: Exception sending notification for table {0}.\n{1}", tableName, ex), EventLogEntryType.Error);
                    }
                }
            }
        }
Пример #16
0
        private void ReceiveCallback(IAsyncResult asyncResult)
        {
            ReceiveStateObject stateObject = asyncResult.AsyncState as ReceiveStateObject;

            try
            {
                int  readCount       = stateObject.Client.EndReceive(asyncResult);
                bool continueReceive = true;
                if (readCount > 0)
                {
                    string text = Encoding.ASCII.GetString(stateObject.Buffer, 0, readCount);
#if UNITTEST_DEBUG
                    string        logFileName = System.IO.Path.Combine(_LogFolder, string.Format("ReceiveMessage_{0:yyyyMMdd}.log", DateTime.Now));
                    StringBuilder sb          = new StringBuilder();
                    sb.AppendFormat(string.Format("RX {0:yyyyMMdd_HHmmss.fffff} {1}\r\n", DateTime.Now, text));
                    lock (this)
                    {
                        System.IO.File.AppendAllText(logFileName, sb.ToString());
                    }
#endif
                    stateObject.Data.Append(text);
                    if (text.Contains("\n"))
                    {
                        string data  = stateObject.Data.ToString();
                        int    count = 0;
                        while (!string.IsNullOrEmpty(data))
                        {
                            int index = data.IndexOf("\n");
                            if (index == -1)
                            {
                                // partial message - break out and get the rest in the following response
                                //count = 0;
                                break;
                            }
                            else
                            {
                                count += (index + 1);
                                string message = data.Substring(0, index);
                                ProcessMessage(message);
                                index++;
                                if (index < data.Length)
                                {
                                    data = data.Substring(index);
                                }
                                else
                                {
                                    data = null;
                                }
                            }
                        }
                        if (count > 0)
                        {
                            stateObject.Data.Remove(0, count);
                        }
                    }
                }
                else
                {
                    if (stateObject.Client.ReceiveTimeout <= 0)
                    {
                        continueReceive = false;
                    }
                    else
                    {
                        TimeSpan diff = DateTime.Now.Subtract(stateObject.StartReceive);
                        if (diff.TotalMilliseconds < stateObject.Client.ReceiveTimeout)
                        {
                            continueReceive = false;
                        }
                    }
                }
                if (continueReceive)
                {
                    stateObject.StartReceive = DateTime.Now;
                    SocketError socketError;
                    stateObject.Client.BeginReceive(stateObject.Buffer, 0, ReceiveStateObject.BufferSize, SocketFlags.None, out socketError, _ReceiveCallback, stateObject);
                }
                else
                {
                    ApplicationEventLog.WriteEntry("Flow", string.Format("DALChangeNotification::ReceiveCallback continueReceive false - Reconnecting to serve {0} port {1}", stateObject.NotificationServer.ServerName, stateObject.NotificationServer.Port), EventLogEntryType.Error);
                    stateObject.NotificationServer.Connected = false;
                    stateObject.Client.Close();
                    Connect(stateObject.NotificationServer, true);
                }
            }
            catch (Exception ex)
            {
                ApplicationEventLog.WriteEntry("Flow", string.Format("DALChangeNotification::ReceiveCallback Exception\n{0}", ex), EventLogEntryType.Error);
                stateObject.NotificationServer.Connected = false;
                stateObject.Client.Close();
                Connect(stateObject.NotificationServer, true);
            }
        }
Пример #17
0
        public bool SetNotificationParameters(Guid clientID, Guid objectDefinitionID, string instanceID, Guid propertyDefinitionID, NotificationParameters notificationParameters)
        {
            bool result = false;

            try
            {
                LWM2MClient client = BusinessLogicFactory.Clients.GetClient(clientID);
                if (client != null)
                {
                    ObjectDefinitionLookups lookups          = BusinessLogicFactory.Clients.GetLookups();
                    ObjectDefinition        objectDefinition = lookups.GetObjectDefinition(objectDefinitionID);
                    if (objectDefinition != null)
                    {
                        int objectID;
                        if (int.TryParse(objectDefinition.ObjectID, out objectID))
                        {
                            Model.ObjectType objectType = client.SupportedTypes.GetObjectType(objectID);
                            if (objectType != null)
                            {
                                PropertyDefinition propertyDefinition = objectDefinition.GetProperty(propertyDefinitionID);
                                if (propertyDefinition != null)
                                {
                                    Request request = client.NewPutRequest(objectType, instanceID, propertyDefinition.PropertyID, -1, null);
                                    if (notificationParameters.MinimumPeriod.HasValue)
                                    {
                                        request.AddUriQuery(string.Concat("pmin=", notificationParameters.MinimumPeriod.Value.ToString()));
                                    }
                                    if (notificationParameters.MaximumPeriod.HasValue)
                                    {
                                        request.AddUriQuery(string.Concat("pmax=", notificationParameters.MaximumPeriod.Value.ToString()));
                                    }
                                    if (notificationParameters.GreaterThan.HasValue)
                                    {
                                        request.AddUriQuery(string.Concat("gt=", notificationParameters.GreaterThan.Value.ToString("0.0")));
                                    }
                                    if (notificationParameters.LessThan.HasValue)
                                    {
                                        request.AddUriQuery(string.Concat("lt=", notificationParameters.LessThan.Value.ToString("0.0")));
                                    }
                                    if (notificationParameters.Step.HasValue)
                                    {
                                        request.AddUriQuery(string.Concat("stp=", notificationParameters.Step.Value.ToString("0.0")));
                                    }
                                    Response response = client.SendRequest(request).WaitForResponse(LWM2MClient.REQUEST_TIMEOUT);
                                    if (response == null)
                                    {
                                        throw new TimeoutException();
                                    }
                                    else
                                    {
                                        if (response.StatusCode == StatusCode.Changed)
                                        {
                                            result = true;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ApplicationEventLog.WriteEntry("Flow", ex.ToString(), System.Diagnostics.EventLogEntryType.Error);
            }
            return(result);
        }
Пример #18
0
 private void ProcessRequests()
 {
     while (!_Terminate)
     {
         _TriggerProcessRequests.Reset();
         while (_NewClients.Count > 0)
         {
             LWM2MClient client = null;
             try
             {
                 lock (_NewClients)
                 {
                     if (_NewClients.Count > 0)
                     {
                         client = _NewClients.Dequeue();
                     }
                 }
                 if (client != null)
                 {
                     if ((client.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) || (client.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6))
                     {
                         Server server = BusinessLogicFactory.Servers.GetServer();
                         System.Net.IPEndPoint ipEndPoint = client.Address as System.Net.IPEndPoint;
                         CoapClient            coapClient = new CoapClient();
                         coapClient.EndPoint = client.EndPoint;
                         coapClient.Timeout  = REQUEST_TIMEOUT;
                         ushort objectInstanceID = 1;
                         foreach (Model.Security item in server.EndPoints)
                         {
                             Request request = new Request(Method.PUT);
                             request.ContentType = TlvConstant.CONTENT_TYPE_TLV;// (int)MediaType.ApplicationOctetStream;
                             request.Destination = client.Address;
                             request.UriPath     = "/0";
                             request.Payload     = SerialiseObject(item, objectInstanceID);
                             objectInstanceID++;
                             coapClient.SendAsync(request, (response) =>
                             {
                                 if (response != null && response.StatusCode == StatusCode.Changed)
                                 {
                                     request             = new Request(Method.PUT);
                                     request.ContentType = TlvConstant.CONTENT_TYPE_TLV;    //(int)MediaType.ApplicationOctetStream;
                                     request.Destination = client.Address;
                                     request.UriPath     = "/1";
                                     request.Payload     = SerialiseObject(server, 1);
                                     coapClient.SendAsync(request, (response2) =>
                                     {
                                         if (response2 != null && response2.StatusCode == StatusCode.Changed)
                                         {
                                             request             = new Request(Method.POST);
                                             request.Destination = client.Address;
                                             request.UriPath     = "/bs";
                                             coapClient.SendAsync(request);
                                         }
                                     });
                                 }
                             }
                                                  );
                         }
                     }
                 }
             }
             catch (Exception ex)
             {
                 ApplicationEventLog.WriteEntry("Flow", ex.ToString(), System.Diagnostics.EventLogEntryType.Error);
             }
         }
         if (!_Terminate)
         {
             _TriggerProcessRequests.WaitOne();
         }
     }
 }
Пример #19
0
        private void ReceiveCompleted(object sender, SocketAsyncEventArgs e)
        {
            Socket             client      = (Socket)sender;
            ReceiveStateObject stateObject = e.UserToken as ReceiveStateObject;

            try
            {
                int  readCount       = e.BytesTransferred;
                bool continueReceive = true;
                if (readCount > 0)
                {
                    string text = Encoding.ASCII.GetString(stateObject.Buffer, 0, readCount);
                    stateObject.Data.Append(text);
                    if (text.Contains("|"))
                    {
                        string data  = stateObject.Data.ToString();
                        int    count = 0;
                        while (!string.IsNullOrEmpty(data))
                        {
                            int index = data.IndexOf("|");
                            if (index == -1)
                            {
                                break;
                            }
                            else
                            {
                                count += (index + 1);
                                string table = data.Substring(0, index);
                                index++;
                                if (index < data.Length)
                                {
                                    data = data.Substring(index);
                                }
                                else
                                {
                                    data = null;
                                }
                                string   id          = null;
                                string[] fields      = table.Split(',');
                                int      fieldLength = fields.Length;
                                if (fields[0] == BROADCAST_PURGE_NOTIFICATION)
                                {
                                    bool purge = false;
                                    if (fieldLength >= 3)
                                    {
                                        if (!bool.TryParse(fields[2], out purge))
                                        {
                                            purge = false;
                                        }
                                        if (fieldLength >= 4)
                                        {
                                            id = fields[3];
                                        }
                                    }
                                    if (fieldLength >= 4)
                                    {
                                        BusinessLogicFactory.NotificationOrchestrator.SendChangeNotification(fields[1], purge, id);
                                    }
                                }
                                else if (fields[0] == BROADCAST_NOTIFICATION)
                                {
                                    if (fieldLength >= 4)
                                    {
                                        id = fields[3];
                                    }
                                    if (fieldLength >= 4)
                                    {
                                        BusinessLogicFactory.NotificationOrchestrator.SendChangeNotification(fields[1], false, id);
                                    }
                                }
                                else if (fields[0] == SETUP_NOTIFICATION)
                                {
                                    if (fieldLength >= 2)
                                    {
                                        BusinessLogicFactory.NotificationOrchestrator.AddNotifcationClient(fields[1], client);
                                    }
                                }
                            }
                        }
                        stateObject.Data.Remove(0, count);
                    }
                }
                else
                {
                    if (client.ReceiveTimeout <= 0)
                    {
                        continueReceive = false;
                    }
                    else
                    {
                        TimeSpan diff = DateTime.Now.Subtract(stateObject.StartReceive);
                        if (diff.TotalMilliseconds < client.ReceiveTimeout)
                        {
                            continueReceive = false;
                        }
                    }
                }
                if (continueReceive)
                {
                    stateObject.StartReceive = DateTime.Now;
                    if (!client.ReceiveAsync(e))
                    {
                        ReceiveCompleted(sender, e);
                    }
                }
                else
                {
#if DEBUG
                    ApplicationEventLog.WriteEntry("Flow", string.Format("DBNotificationTCPServer::DoReceiveCallback: closing client socket {0}", client), System.Diagnostics.EventLogEntryType.Information);
#endif
                    client.Close();
                }
            }
#pragma warning disable 168
            catch (Exception ex)
#pragma warning restore 168
            {
#if DEBUG
                ApplicationEventLog.WriteEntry("Flow", string.Format("DBNotificationTCPServer::DoReceiveCallback: Exception\n{0}", ex), System.Diagnostics.EventLogEntryType.Error);
#endif
            }
        }
Пример #20
0
 void IBasicConsumer.HandleBasicDeliver(string consumerTag, ulong deliveryTag, bool redelivered, string exchange, string routingKey, IBasicProperties properties, byte[] body)
 {
     try
     {
         if (_ProcessMessages)
         {
             Interlocked.Increment(ref _MessageHandlingCount);
             MessageFormatter    messageFormatter = new MessageFormatter();
             ServiceEventMessage message          = messageFormatter.Deserialise(new MemoryStream(body));
             lock (_Queues)
             {
                 if (_Queues.ContainsKey(consumerTag))
                 {
                     MessageQueue queue = _Queues[consumerTag];
                     message.DeliveryID = Guid.NewGuid();
                     AckMessageInfo ackMessageInfo = new AckMessageInfo();
                     ackMessageInfo.DeliveryID     = message.DeliveryID;
                     ackMessageInfo.QueueName      = queue.QueueName;
                     ackMessageInfo.DeliveryTag    = deliveryTag;
                     ackMessageInfo.TotalExpected  = queue.Handlers.Count;
                     ackMessageInfo.ChannelHandler = this;
                     queue.AddAckMessageInfo(message.DeliveryID, ackMessageInfo);
                     message.Queue = queue.QueueName;
                     for (int index = 0; index < queue.Handlers.Count; index++)
                     {
                         try
                         {
                             MessageArrivedEventHandler handler = queue.Handlers[index];
                             handler.BeginInvoke(_ConnectionFactory.HostName, message, _Subscription.InvokeCallBack, new MessageArrivedState(handler, message, queue, ackMessageInfo));
                         }
                         catch (Exception ex)
                         {
                             _Subscription.NackMessage(message);
                             ApplicationEventLog.WriteEntry("Flow", ex.ToString(), System.Diagnostics.EventLogEntryType.Error);
                         }
                     }
                     if (queue.Handlers.Count == 0)
                     {
                         Thread.Sleep(500);
                         _Model.BasicReject(deliveryTag, true);
                         Interlocked.Decrement(ref _MessageHandlingCount);
                         ApplicationEventLog.WriteEntry("Flow", string.Format("No handlers to process message {0}", consumerTag), System.Diagnostics.EventLogEntryType.Error);
                     }
                 }
                 else
                 {
                     Thread.Sleep(500);
                     _Model.BasicReject(deliveryTag, true);
                     Interlocked.Decrement(ref _MessageHandlingCount);
                     ApplicationEventLog.WriteEntry("Flow", string.Format("HandleBasicDeliver: Failed to locate queue {0}", consumerTag), System.Diagnostics.EventLogEntryType.Error);
                 }
             }
         }
     }
     catch (System.Runtime.Serialization.SerializationException)
     {
         string path = GetBadMessageDirectory();
         File.WriteAllBytes(Path.Combine(path, string.Concat(consumerTag, "_", Guid.NewGuid().ToString())), body);
         _Model.BasicReject(deliveryTag, false);
         Interlocked.Decrement(ref _MessageHandlingCount);
     }
     catch (Exception ex)
     {
         Thread.Sleep(500);
         try
         {
             if (_Model != null)
             {
                 _Model.BasicReject(deliveryTag, true);
             }
             Interlocked.Decrement(ref _MessageHandlingCount);
         }
         catch { }
         ApplicationEventLog.WriteEntry("Flow", ex.ToString(), System.Diagnostics.EventLogEntryType.Error);
     }
 }
Пример #21
0
        private void PublishTransactionalMessages()
        {
            bool         connectionError = false;
            MemoryStream stream          = new MemoryStream(32768);

            while (!_Terminate)
            {
                try
                {
                    if (connectionError)
                    {
                        CheckForUnSentMessage(_TransactionalMessagePath);
                        CheckForUnSentMessage(_TransactionalRequeueMessagePath);
                    }
                    connectionError = false;
                    RabbitMQConnection server = _Servers[_CurrentHostIndex];
                    _CurrentHostIndex = (_CurrentHostIndex + 1) % _ServerCount;
                    ConnectionFactory connectionFactory = new ConnectionFactory();
                    connectionFactory.uri = server.Uri;
                    if (!string.IsNullOrEmpty(server.Username))
                    {
                        connectionFactory.UserName = server.Username;
                    }
                    if (!string.IsNullOrEmpty(server.Password))
                    {
                        connectionFactory.Password = server.Password;
                    }
                    string hostname = server.Uri.DnsSafeHost;
                    using (IConnection connection = connectionFactory.CreateConnection())
                    {
                        using (IModel transactionalChannel = connection.CreateModel())
                        {
                            transactionalChannel.BasicReturn += new EventHandler <BasicReturnEventArgs>(Channel_BasicReturn);
                            transactionalChannel.ExchangeDeclare(EXCHANGE_NAME, ExchangeType.Topic, true, false, null);
                            while (!_Terminate)
                            {
                                _TriggerPublishTransactionalMessages.Reset();
                                PublishTransactionalMessages(transactionalChannel, hostname, EXCHANGE_NAME, _TransactionalMessagePath, false);
                                TimeSpan delay = PublishTransactionalMessages(transactionalChannel, hostname, string.Empty, _TransactionalRequeueMessagePath, true);
                                if (!_Terminate)
                                {
                                    if (delay == TimeSpan.MaxValue)
                                    {
                                        _TriggerPublishTransactionalMessages.WaitOne();
                                    }
                                    else
                                    {
                                        _TriggerPublishTransactionalMessages.WaitOne(delay);
                                    }
                                }
                            }
                            transactionalChannel.Close(200, "Goodbye");
                        }
                        connection.Close();
                    }
                }
                catch (ThreadAbortException)
                {
                    break;
                }
                catch (Exception ex)
                {
                    connectionError = true;
                    ApplicationEventLog.WriteEntry("Flow", string.Format("DALRabbitMQ::PublishMessages - Exception\n{0}", ex), System.Diagnostics.EventLogEntryType.Error);
                }
                if (connectionError)
                {
                    Thread.Sleep(500);
                }
            }
        }
Пример #22
0
        private void PublishFireAndForgetMessages()
        {
            bool         connectionError = false;
            MemoryStream stream          = new MemoryStream(32768);

            while (!_Terminate)
            {
                try
                {
                    connectionError = false;
                    RabbitMQConnection server = _Servers[_CurrentHostIndex];
                    _CurrentHostIndex = (_CurrentHostIndex + 1) % _ServerCount;
                    ConnectionFactory connectionFactory = new ConnectionFactory();
                    connectionFactory.uri = server.Uri;
                    if (!string.IsNullOrEmpty(server.Username))
                    {
                        connectionFactory.UserName = server.Username;
                    }
                    if (!string.IsNullOrEmpty(server.Password))
                    {
                        connectionFactory.Password = server.Password;
                    }
                    string hostname = server.Uri.DnsSafeHost;

                    MessageFormatter messageFormatter = new MessageFormatter(stream);
                    using (IConnection connection = connectionFactory.CreateConnection())
                    {
                        using (IModel asyncChannel = connection.CreateModel())
                        {
                            //asynchronousChannel.BasicReturn += new RabbitMQ.Client.Events.BasicReturnEventHandler(Channel_BasicReturn);
                            asyncChannel.ExchangeDeclare(EXCHANGE_NAME, ExchangeType.Topic, true, false, null);
                            while (!_Terminate)
                            {
                                _TriggerPublishFireAndForgetMessages.Reset();
                                int      skipCount = 0;
                                TimeSpan delay     = TimeSpan.MaxValue;
                                Dictionary <Guid, Object> skippedMessages = new Dictionary <Guid, object>();
                                while (_FireAndForgetMessages.Count > skipCount)
                                {
                                    QueuedMessage queuedMessage;
                                    lock (_FireAndForgetMessages)
                                    {
                                        queuedMessage = _FireAndForgetMessages.Dequeue();
                                    }
                                    if (queuedMessage.Message.QueueAfterTime.HasValue && (queuedMessage.Message.QueueAfterTime.Value > DateTime.UtcNow))
                                    {
                                        TimeSpan messageDelay = queuedMessage.Message.QueueAfterTime.Value.Subtract(DateTime.UtcNow);
                                        if (messageDelay < delay)
                                        {
                                            delay = messageDelay;
                                        }
                                        lock (_FireAndForgetMessages)
                                        {
                                            _FireAndForgetMessages.Enqueue(queuedMessage);
                                        }
                                        if (skippedMessages.ContainsKey(queuedMessage.Message.MessageID))
                                        {
                                            skippedMessages.Add(queuedMessage.Message.MessageID, null);
                                            skipCount++;
                                        }
                                        continue;
                                    }
                                    stream.Position = 0;
                                    messageFormatter.Serialise(queuedMessage.Message);
                                    stream.SetLength(stream.Position);
                                    stream.Position = 0;
                                    byte[]           data       = stream.ToArray();
                                    IBasicProperties properties = asyncChannel.CreateBasicProperties();
                                    properties.CorrelationId = hostname;
                                    properties.DeliveryMode  = 2;
                                    properties.MessageId     = queuedMessage.Message.MessageID.ToString();
                                    properties.ContentType   = messageFormatter.ContentType;

                                    //Transaction was only about ~14 messages a second whereas non is ~1300
                                    if (queuedMessage.Requeued)
                                    {
                                        asyncChannel.BasicPublish(string.Empty, queuedMessage.RoutingKey, properties, data);
                                    }
                                    else
                                    {
                                        asyncChannel.BasicPublish(EXCHANGE_NAME, queuedMessage.RoutingKey, properties, data);
                                    }
                                }
                                if (!_Terminate)
                                {
                                    if (delay == TimeSpan.MaxValue)
                                    {
                                        _TriggerPublishFireAndForgetMessages.WaitOne();
                                    }
                                    else
                                    {
                                        _TriggerPublishFireAndForgetMessages.WaitOne(delay);
                                    }
                                }
                            }
                            asyncChannel.Close(200, "Goodbye");
                        }
                        connection.Close();
                    }
                }
                catch (ThreadAbortException)
                {
                    break;
                }
                catch (Exception ex)
                {
                    connectionError = true;
                    ApplicationEventLog.WriteEntry("Flow", string.Format("DALRabbitMQ::PublishMessages - Exception\n{0}", ex), System.Diagnostics.EventLogEntryType.Error);
                }
                if (connectionError)
                {
                    Thread.Sleep(500);
                }
            }
        }
Пример #23
0
        private void ProcessSubscriptionRequests()
        {
            bool     connectionError  = false;
            DateTime?nextErrorLogTime = null;

            while (!_Terminate)
            {
                try
                {
                    connectionError     = false;
                    _ConnectionShutdown = false;
                    ConnectionFactory connectionFactory = new ConnectionFactory();
                    connectionFactory.uri = _Server.Uri;
                    if (!string.IsNullOrEmpty(_Server.Username))
                    {
                        connectionFactory.UserName = _Server.Username;
                    }
                    if (!string.IsNullOrEmpty(_Server.Password))
                    {
                        connectionFactory.Password = _Server.Password;
                    }
                    _OpenChannels = 0;
                    using (IConnection connection = connectionFactory.CreateConnection())
                    {
                        while (!_Terminate && !_ConnectionShutdown)
                        {
                            _TriggerSubscriptionRequest.Reset();
                            while (_SubscriptionToAdd.Count > 0)
                            {
                                lock (_ChannelHandlers)
                                {
                                    ChannelHandler handler;
                                    IModel         channel;
                                    MessageQueue   queue;
                                    lock (_Queues)
                                    {
                                        queue = _SubscriptionToAdd.Dequeue();
                                    }
                                    if (queue != null)
                                    {
                                        if (!_ChannelHandlers.TryGetValue(queue.ChannelName, out handler))
                                        {
                                            channel = connection.CreateModel();
                                            channel.BasicQos(0, 1, false);
                                            channel.ExchangeDeclare(DALRabbitMQ.EXCHANGE_NAME, ExchangeType.Topic, true, false, null);
                                            handler = new ChannelHandler(queue.ChannelName, channel, connectionFactory, this);
                                            _ChannelHandlers.Add(queue.ChannelName, handler);
                                            Interlocked.Increment(ref _OpenChannels);
                                        }
                                        channel       = handler.Channel;
                                        queue.Channel = channel;
                                        handler.AddQueue(queue);
                                        channel.QueueDeclare(queue.QueueName, queue.Durable, queue.Temporary, false, null);
                                        channel.QueueBind(queue.QueueName, DALRabbitMQ.EXCHANGE_NAME, queue.RoutingKey);
                                        channel.BasicConsume(queue.QueueName, false, queue.QueueName, handler);
                                    }
                                }
                            }
                            _TriggerSubscriptionRequest.WaitOne();
                        }

                        // Handle shutdown
                        lock (_ChannelHandlers)
                        {
                            foreach (ChannelHandler item in _ChannelHandlers.Values)
                            {
                                item.StopProcessingMessages();
                                item.WaitForIdle(TimeSpan.FromSeconds(10));
                                if (item.Channel.IsOpen)
                                {
                                    item.Channel.Close(200, "Goodbye");
                                }
                            }
                            _ChannelHandlers.Clear();
                        }
                        if (connection.IsOpen)
                        {
                            connection.Close();
                        }
                    }
                    if (_ConnectionShutdown)
                    {
                        connectionError = true;
                    }
                }
                catch (ThreadAbortException)
                {
                    break;
                }
                catch (Exception ex)
                {
                    connectionError = true;
                    if (!nextErrorLogTime.HasValue || nextErrorLogTime.Value < DateTime.UtcNow)
                    {
                        StringBuilder errorMessage = new StringBuilder();
                        errorMessage.AppendLine(ex.ToString());
                        if (ex.InnerException != null)
                        {
                            errorMessage.AppendLine("\r\nInnerException:");
                            errorMessage.AppendLine(ex.InnerException.ToString());
                        }
                        ApplicationEventLog.WriteEntry("Flow", string.Concat("ProcessSubscriptionRequests (", _Server.Uri.DnsSafeHost, "):\r\n", errorMessage.ToString()), System.Diagnostics.EventLogEntryType.Error);
                        nextErrorLogTime = DateTime.UtcNow.Add(TimeSpan.FromSeconds(60));
                    }
                }
                if (connectionError)
                {
                    lock (_Queues)
                    {
                        _SubscriptionToAdd.Clear();
                        foreach (KeyValuePair <string, MessageQueue> item in _Queues)
                        {
                            _SubscriptionToAdd.Enqueue(item.Value);
                        }
                    }
                    lock (_ChannelHandlers)
                    {
                        _ChannelHandlers.Clear();
                    }
                    Thread.Sleep(500);
                }
            }
        }
Пример #24
0
        private void ProcessNotificationsToRepair()
        {
            Dictionary <string, object> servers = new Dictionary <string, object>();

            while (!_Terminate)
            {
                while (!_Terminate && (_NotificationsToRepair.Count > 0))
                {
                    try
                    {
                        NotificationClient notificationSetupInfo;
                        lock (_NotificationsToRepair)
                        {
                            notificationSetupInfo = _NotificationsToRepair.Dequeue();
                        }
                        bool successful = SetupNotification(1, notificationSetupInfo.TableName, notificationSetupInfo.EventHandler);
                        if (!successful)
                        {
                            Thread.Sleep(100);
                        }
                    }
                    catch (Exception ex)
                    {
                        ApplicationEventLog.WriteEntry("Flow", string.Format("ProcessNotificationsToRepair:Exception processing notifications {0}", ex), EventLogEntryType.Error);
                    }
                }
                int index = 0;
                servers.Clear();
                while (index < _NotificationServersToReconnect.Count)
                {
                    bool connected = false;
                    if (_NotificationServersToReconnect[index].Connected)
                    {
                        connected = true;
                    }
                    else
                    {
                        if (!servers.ContainsKey(_NotificationServersToReconnect[index].ServerName))
                        {
                            servers.Add(_NotificationServersToReconnect[index].ServerName, null);
                            Connect(_NotificationServersToReconnect[index], false);
                        }
                    }
                    if (connected)
                    {
                        lock (_NotificationServersToReconnect)
                        {
                            _NotificationServersToReconnect.RemoveAt(index);
                        }
                    }
                    else
                    {
                        index++;
                    }
                }
                _TriggerNotificationRepair.Reset();
                int timeout = Timeout.Infinite;
                if (_NotificationServersToReconnect.Count > 0)
                {
                    timeout = 5000;
                }
                if (_NotificationsToRepair.Count == 0)
                {
                    _TriggerNotificationRepair.WaitOne(timeout);
                }
            }
        }