private void Channel_ConditionOrError(object sender, ConditionOrErrorEventArgs e)
 {
     Status = new ExtendedStatus
     {
         Status      = StatusEnum.COMMUNICATION_ERROR,
         Description = string.Format("Received event from {0} with ErrorCode {1} NativeCode {2} SubSystemReason {3}", e.ChannelName, e.ErrorCode, e.NativeCode, e.SubSystemReason)
     };
     if (!String.IsNullOrEmpty(LogFileName))
     {
         File.AppendAllText(LogFileName, String.Format("Timestamp: {0} Received event from: {1} ErrorCode: {2} NativeCode: {3} SubSystemReason: {4} {5}", DateTime.Now, e.ChannelName, e.ErrorCode, e.NativeCode, e.SubSystemReason, Environment.NewLine));
     }
 }
 void InternalDeactivate()
 {
     lock (CriticalSection)
     {
         if (Status.Status == StatusEnum.DEACTIVATED ||
             Status.Status == StatusEnum.ERROR ||
             Status.Status == StatusEnum.INITIALIZED ||
             Status.Status == StatusEnum.UNDEFINED
             )
         {
             return;
         }
         dataDistribution.LoggingEvent -= DataDistribution_LoggingEvent;
         Channel.DataAvailable         -= Channel_DataAvailable;
         Channel.ConditionOrError      -= Channel_ConditionOrError;
         OPERATION_RESULT Res = Channel.StopChannel(10000);
         if (Res.Succeeded)
         {
             Status = new ExtendedStatus
             {
                 Status      = StatusEnum.INITIALIZED,
                 Description = "Channel Stopped"
             };
         }
         else
         {
             Status = new ExtendedStatus
             {
                 Status      = StatusEnum.DEACTIVATION_ERROR,
                 Description = "Error in channel deactivation"
             };
         }
         Res = dataDistribution.Stop(10000);
         if (Res.Succeeded)
         {
             Status = new ExtendedStatus
             {
                 Status      = StatusEnum.DEACTIVATED,
                 Description = "Communication module Stopped"
             };
         }
         else
         {
             Status = new ExtendedStatus
             {
                 Status      = StatusEnum.DEACTIVATION_ERROR,
                 Description = "Error in communication module deactivation"
             };
         }
         //dataDistribution = null;
     }
 }
 async Task InternalSendMessage <T>(T message, string key = null)
 {
     await Task.Run(() =>
     {
         if (!(Status.Status == StatusEnum.CONNECTED ||
               Status.Status == StatusEnum.COMMUNICATING ||
               Status.Status == StatusEnum.COMMUNICATION_ERROR))
         {
             throw new Exception("Unable to send messages in status: " + Status.Status);
         }
         if (Id == null)
         {
             throw new Exception("Id not configured");
         }
         if (!(message is string))
         {
             throw new NotImplementedException("Only string messages are implemented");
         }
         byte[] msg           = ASCIIEncoding.ASCII.GetBytes(message as string);
         string strMessage    = message as string;
         OPERATION_RESULT res = Channel.WriteOnChannel(key, message as string);
         //OPERATION_RESULT res = Channel.WriteOnChannel(key, msg);
         if (res.Failed)
         {
             Status = new ExtendedStatus
             {
                 Status      = StatusEnum.COMMUNICATION_ERROR,
                 Description = "Error sending message"
             };
         }
         else
         {
             Status = new ExtendedStatus
             {
                 Status      = StatusEnum.COMMUNICATING,
                 Description = "Ok"
             };
         }
     });
 }
        private void Channel_DataAvailable(object sender, DataAvailableEventArgs e)
        {
            MsgEventArgs mea = new MsgEventArgs();

            mea.Timestamp = DateTime.Now;
            //TODO: REMOVE
            //Guid guid;
            //mea.SenderId = Guid.TryParse(e.Key,out guid)? guid: Guid.Empty;
            //mea.EventType = (mea.SenderId == Id) ? EventTypeEnum.SENT : EventTypeEnum.RECEIVED;
            if (!String.IsNullOrEmpty(e.DecodedString))
            {
                mea.DataType = typeof(String);
                mea.Data     = e.DecodedString;
            }
            else
            {
                mea.DataType = typeof(byte[]);
                mea.Data     = e.Buffer;
            }

            Status = new ExtendedStatus
            {
                Status      = StatusEnum.COMMUNICATING,
                Description = "Ok"
            };
            // Make a temporary copy of the event to avoid possibility of
            // a race condition if the last subscriber unsubscribes
            // immediately after the null check and before the event is raised.
            EventHandler <MsgEventArgs> raiseEvent = MessageEvent;

            // Event will be null if there are no subscribers
            if (raiseEvent != null)
            {
                //raise the event.
                raiseEvent(this, mea);
            }
        }
        void InternalActivate()
        {
            lock (CriticalSection)
            {
                if (Status.Status == StatusEnum.CONNECTED ||
                    Status.Status == StatusEnum.COMMUNICATING ||
                    Status.Status == StatusEnum.COMMUNICATION_ERROR ||
                    Status.Status == StatusEnum.INITIALIZED ||
                    Status.Status == StatusEnum.COMMUNICATION_ERROR
                    )
                {
                    return;
                }
                OPERATION_RESULT Res = new OPERATION_RESULT();
                //dataDistribution = new SmartDataDistribution();

                dataDistribution.LoggingEvent += DataDistribution_LoggingEvent;
                try
                {
                    if (Status.Status == StatusEnum.UNDEFINED)
                    {
                        Res = dataDistribution.Initialize(Configuration);
                    }
                    Status = new ExtendedStatus {
                        Status = StatusEnum.INITIALIZED, Description = "INITIALIZED"
                    };
                    if (Res.Failed)
                    {
                        Status = new ExtendedStatus
                        {
                            Status      = StatusEnum.ERROR,
                            Description = "Initialization error"
                        };
                    }
                    Res = dataDistribution.Start(uint.MaxValue);
                    if (Res.Failed)
                    {
                        Status = new ExtendedStatus
                        {
                            Status      = StatusEnum.ERROR,
                            Description = "Start error"
                        };
                    }

                    Channel = dataDistribution.CreateSmartChannel <SmartDataDistributionChannel>(ChannelName, Configuration);
                    Channel.DataAvailable    += Channel_DataAvailable;
                    Channel.ConditionOrError += Channel_ConditionOrError;
                    Res = Channel.StartChannel(uint.MaxValue);
                    if (Res.Succeeded)
                    {
                        Status = new ExtendedStatus
                        {
                            Status      = StatusEnum.CONNECTED,
                            Description = "Channel connection OK"
                        };
                    }
                    if (Res.Failed)
                    {
                        Status = new ExtendedStatus
                        {
                            Status      = StatusEnum.ERROR,
                            Description = "Channel Start error"
                        };
                    }
                    Channel.SeekChannel(0);
                }
                catch (Exception ex)
                {
                    Status = new ExtendedStatus
                    {
                        Status      = StatusEnum.ERROR,
                        Description = ex.Message
                    };
                }
            }
        }