コード例 #1
0
 /// <summary>
 ///     Send local shared dll for the sync to the partner request
 /// </summary>
 /// <param name="Partner">Partner request to send</param>
 public static void SyncSendLocalDLLList(string DestinationPartner)
 {
     try
     {
         EventsEngine.UpdateAssemblyEventListShared();
         foreach (var jitgAssemblyEvent in EventsEngine.AssemblyEventListShared)
         {
             LogEngine.ConsoleWriteLine(
                 string.Format("SENT EVENT - {0} to {1}", jitgAssemblyEvent.FileName, DestinationPartner),
                 ConsoleColor.Green);
             OffRampEngineSending.SendMessageOnRamp(jitgAssemblyEvent, Configuration.MessageDataProperty.SyncSendLocalDLL,
                                                    DestinationPartner, null);
         }
     }
     catch (InvalidOperationException eoe)
     {
         LogEngine.ConsoleWriteLine(
             string.Format("Syncronization and Dictionaries rebuilded, Excpetion controlled - {0}", eoe.HResult),
             ConsoleColor.DarkRed);
     }
     catch (Exception ex)
     {
         LogEngine.WriteLog(Configuration.General_Source,
                            string.Format("Error in {0}", MethodBase.GetCurrentMethod().Name),
                            Constant.Error_EventID_High_Critical_,
                            Constant.TaskCategories_,
                            ex,
                            EventLogEntryType.Error);
     }
 }
コード例 #2
0
        /// <summary>
        ///     Sync a single configuration file
        /// </summary>
        public static void SyncLocalConfigurationFile(SyncConfigurationFile jitgSyncConfigurationFile)
        {
            try
            {
                //invia il file con tutta la di e metti nelle prop che e un evento o trigger e la dir, il contenuto nel body eventdata
                //fai il replace della dir

                var newFilenameDir =
                    jitgSyncConfigurationFile.Name.Replace(jitgSyncConfigurationFile.DirectoryOperativeRoot_ExeName, "");
                newFilenameDir = string.Concat(Configuration.DirectoryEndPoints(), "\\",
                                               jitgSyncConfigurationFile.Name, newFilenameDir);
                Directory.CreateDirectory(Path.GetDirectoryName(newFilenameDir));

                File.WriteAllBytes(newFilenameDir, jitgSyncConfigurationFile.FileContent);
            }
            catch (IOException ioException)
            {
                LogEngine.ConsoleWriteLine("-SYNC CONF. BUBBLING -", ConsoleColor.Red);
            }
            catch (UnauthorizedAccessException unauthorizedAccessException)
            {
                LogEngine.ConsoleWriteLine("-SYNC CONF. BUBBLING -", ConsoleColor.Red);
            }

            catch (Exception ex)
            {
                LogEngine.WriteLog(Configuration.General_Source,
                                   string.Format("Error in {0}", MethodBase.GetCurrentMethod().Name),
                                   Constant.Error_EventID_High_Critical_,
                                   Constant.TaskCategories_,
                                   ex,
                                   EventLogEntryType.Error);
            }
        }
コード例 #3
0
        /// <summary>
        ///     Sync the local DLL trigger and events to the table storage
        /// </summary>
        public static void SyncLocalDLL(AssemblyEvent jitgAssemblyEvent)
        {
            try
            {
                var BubblingDirectory = Configuration.DirectoryOperativeRoot_ExeName();

                var assemblyFile = Path.Combine(BubblingDirectory, string.Concat(jitgAssemblyEvent.Type, "s"),
                                                jitgAssemblyEvent.FileName);
                //Set the primary key, if equal then check the assembly version
                if (!File.Exists(assemblyFile))
                {
                    LogEngine.ConsoleWriteLine("-NEW EVENT RECEIVED-", ConsoleColor.Green);
                    File.WriteAllBytes(assemblyFile, jitgAssemblyEvent.AssemblyContent);
                    LogEngine.ConsoleWriteLine("-NEW EVENT CREATED-", ConsoleColor.Green);
                }
                else
                {
                    //To avoid the lock
                    //Before delete all clones
                    LogEngine.ConsoleWriteLine("-SYNC EVENT-", ConsoleColor.Green);

                    var assembly = Assembly.LoadFile(assemblyFile);

                    var versionOnLocal   = assembly.GetName().Version;
                    var versionOnStorage = new Version(jitgAssemblyEvent.Version);

                    if (versionOnStorage.CompareTo(versionOnLocal) > 0)
                    {
                        LogEngine.ConsoleWriteLine(
                            string.Format("-SYNC EVENT TO DO- Local V.{0} Remote V. {1}", versionOnLocal,
                                          versionOnStorage), ConsoleColor.Green);
                        var assemblyUpdate = Path.ChangeExtension(assemblyFile, Configuration.General_UpdateFile);
                        File.WriteAllBytes(assemblyUpdate, jitgAssemblyEvent.AssemblyContent);
                        LogEngine.ConsoleWriteLine("-SYNC EVENT DONE-", ConsoleColor.Green);
                    }
                    assembly = null;
                }
            }
            catch (IOException ioException)
            {
                LogEngine.ConsoleWriteLine("-SYNC EVENT -", ConsoleColor.Red);
            }
            catch (UnauthorizedAccessException unauthorizedAccessException)
            {
                LogEngine.ConsoleWriteLine("-SYNC EVENT -", ConsoleColor.Red);
            }

            catch (Exception ex)
            {
                LogEngine.WriteLog(Configuration.General_Source,
                                   string.Format("Error in {0}", MethodBase.GetCurrentMethod().Name),
                                   Constant.Error_EventID_High_Critical_,
                                   Constant.TaskCategories_,
                                   ex,
                                   EventLogEntryType.Error);
            }
        }
コード例 #4
0
ファイル: Program.cs プロジェクト: debiaggi/GrabCaster
        } // Main

        private static string AskInputLine(string message)
        {
            var ret = string.Empty;
            while (ret == string.Empty)
            {
                LogEngine.ConsoleWriteLine(message, ConsoleColor.Green);
                ret = Console.ReadLine();
            }
            return ret;
        }
コード例 #5
0
        /// <summary>
        /// Persist the message in local file system
        /// </summary>
        /// <param name="bubblingEvent">
        /// </param>
        /// <param name="communicationDiretion">
        /// The communication Diretion.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        public static bool PersistMessage(BubblingEvent bubblingEvent, CommunicationDiretion communicationDiretion)
        {
            try
            {
                if (!Configuration.EnablePersistingMessaging())
                {
                    return(true);
                }

                var serializedMessage = JsonConvert.SerializeObject(bubblingEvent);
                var directoryDate     = string.Concat(
                    DateTime.Now.Year,
                    "\\",
                    DateTime.Now.Month.ToString().PadLeft(2, '0'),
                    "\\",
                    DateTime.Now.Day.ToString().PadLeft(2, '0'),
                    "\\",
                    communicationDiretion.ToString());
                var datetimeFile = string.Concat(
                    DateTime.Now.Year,
                    DateTime.Now.Month.ToString().PadLeft(2, '0'),
                    DateTime.Now.Day.ToString().PadLeft(2, '0'),
                    "-",
                    DateTime.Now.Hour.ToString().PadLeft(2, '0'),
                    "-",
                    DateTime.Now.Minute.ToString().PadLeft(2, '0'),
                    "-",
                    DateTime.Now.Second.ToString().PadLeft(2, '0'));

                var persistingForlder = Path.Combine(Configuration.LocalStorageConnectionString(), directoryDate);
                Directory.CreateDirectory(persistingForlder);
                var filePersisted = Path.Combine(
                    persistingForlder,
                    string.Concat(datetimeFile, "-", bubblingEvent.MessageId, Configuration.MessageFileStorageExtension));

                File.WriteAllText(filePersisted, serializedMessage);
                LogEngine.ConsoleWriteLine(
                    "Event persisted -  Consistency Transaction Point created.",
                    ConsoleColor.DarkGreen);
                return(true);
            }
            catch (Exception ex)
            {
                LogEngine.WriteLog(
                    Configuration.EngineName,
                    $"Error in {MethodBase.GetCurrentMethod().Name}",
                    Constant.DefconOne,
                    Constant.TaskCategoriesError,
                    ex,
                    EventLogEntryType.Error);
                return(false);
            }
        }
コード例 #6
0
        public byte[] PersistEventFromStorage(string messageId)
        {
            try
            {
                var storageAccountName = Configuration.GroupEventHubsStorageAccountName();
                var storageAccountKey  = Configuration.GroupEventHubsStorageAccountKey();
                var connectionString   =
                    $"DefaultEndpointsProtocol=https;AccountName={storageAccountName};AccountKey={storageAccountKey}";
                var storageAccount = CloudStorageAccount.Parse(connectionString);
                var blobClient     = storageAccount.CreateCloudBlobClient();

                // Retrieve a reference to a container.
                var container = blobClient.GetContainerReference(Configuration.GroupEventHubsName());

                // Create the container if it doesn't already exist.
                container.CreateIfNotExists();
                container.SetPermissions(
                    new BlobContainerPermissions {
                    PublicAccess = BlobContainerPublicAccessType.Blob
                });

                // Create the messageid reference
                var blockBlob = container.GetBlockBlobReference(messageId);

                blockBlob.FetchAttributes();
                var msgByteLength = blockBlob.Properties.Length;
                var msgContent    = new byte[msgByteLength];
                for (var i = 0; i < msgByteLength; i++)
                {
                    msgContent[i] = 0x20;
                }

                blockBlob.DownloadToByteArray(msgContent, 0);

                LogEngine.ConsoleWriteLine(
                    "Event persisted recovered -  Consistency Transaction Point restored.",
                    ConsoleColor.DarkGreen);

                return(msgContent);
            }
            catch (Exception ex)
            {
                LogEngine.WriteLog(
                    Configuration.EngineName,
                    $"Error in {MethodBase.GetCurrentMethod().Name}",
                    Constant.DefconOne,
                    Constant.TaskCategoriesError,
                    ex,
                    EventLogEntryType.Error);
                return(null);
            }
        }
コード例 #7
0
        public void PersistEventToStorage(byte[] messageBody, string messageId)
        {
            try
            {
                if (Configuration.RunLocalOnly())
                {
                    LogEngine.WriteLog(Configuration.EngineName,
                                       $"Impossible to use a remote storage provider, this GrabCaster point is configured for local only execution.",
                                       Constant.DefconOne,
                                       Constant.TaskCategoriesError,
                                       null,
                                       EventLogEntryType.Warning);
                    return;
                }

                var storageAccountName = Configuration.GroupEventHubsStorageAccountName();
                var storageAccountKey  = Configuration.GroupEventHubsStorageAccountKey();
                var connectionString   =
                    $"DefaultEndpointsProtocol=https;AccountName={storageAccountName};AccountKey={storageAccountKey}";
                var storageAccount = CloudStorageAccount.Parse(connectionString);
                var blobClient     = storageAccount.CreateCloudBlobClient();

                // Retrieve a reference to a container.
                var container = blobClient.GetContainerReference(Configuration.GroupEventHubsName());

                // Create the container if it doesn't already exist.
                container.CreateIfNotExists();
                container.SetPermissions(
                    new BlobContainerPermissions {
                    PublicAccess = BlobContainerPublicAccessType.Blob
                });

                // Create the messageid reference
                var blockBlob = container.GetBlockBlobReference(messageId);
                blockBlob.UploadFromByteArray(messageBody, 0, messageBody.Length);
                LogEngine.ConsoleWriteLine(
                    "Event persisted -  Consistency Transaction Point created.",
                    ConsoleColor.DarkGreen);
            }
            catch (Exception ex)
            {
                LogEngine.WriteLog(
                    Configuration.EngineName,
                    $"Error in {MethodBase.GetCurrentMethod().Name}",
                    Constant.DefconOne,
                    Constant.TaskCategoriesError,
                    ex,
                    EventLogEntryType.Error);
            }
        }
コード例 #8
0
 //Send all the configuration bubbling event and triggers
 public static void SyncSendConfigurationFileList(string DestinationPartner)
 {
     try
     {
         LogEngine.ConsoleWriteLine(
             string.Format("SENT BUBBLING EVT/TRG CONF. - to {0}", DestinationPartner), ConsoleColor.Yellow);
         OffRampEngineSending.SendMessageOnRamp(EventsEngine.SyncConfigurationFileList,
                                                Configuration.MessageDataProperty.SyncConfigurationFileListToDo, DestinationPartner, null);
     }
     catch (Exception ex)
     {
         LogEngine.WriteLog(Configuration.General_Source,
                            string.Format("Error in {0}", MethodBase.GetCurrentMethod().Name),
                            Constant.Error_EventID_High_Critical_,
                            Constant.TaskCategories_,
                            ex,
                            EventLogEntryType.Error);
     }
 }
コード例 #9
0
 //Sync all the configuration  event and triggers files
 public static void SyncLocalConfigurationFileList(List <SyncConfigurationFile> SyncConfigurationFileList)
 {
     try
     {
         LogEngine.ConsoleWriteLine("-SYNC LOCAL EVT/TRG CONF.-", ConsoleColor.Green);
         foreach (var jitgSyncConfigurationFile in SyncConfigurationFileList)
         {
             SyncLocalConfigurationFile(jitgSyncConfigurationFile);
         }
     }
     catch (Exception ex)
     {
         LogEngine.WriteLog(Configuration.General_Source,
                            string.Format("Error in {0}", MethodBase.GetCurrentMethod().Name),
                            Constant.Error_EventID_High_Critical_,
                            Constant.TaskCategories_,
                            ex,
                            EventLogEntryType.Error);
     }
 }
コード例 #10
0
 /// <summary>
 ///     Send local shared dll for the sync to the partner request
 /// </summary>
 /// <param name="Partner">Partner request to send</param>
 public static void SyncSendLocalDLL(AssemblyEvent jitgAssemblyEvent, string DestinationPartner)
 {
     try
     {
         EventsEngine.UpdateAssemblyEventListShared();
         LogEngine.ConsoleWriteLine(
             string.Format("SENT EVENT - {0} to {1}", jitgAssemblyEvent.FileName, DestinationPartner),
             ConsoleColor.Green);
         OffRampEngineSending.SendMessageOnRamp(jitgAssemblyEvent, Configuration.MessageDataProperty.SyncSendLocalDLL,
                                                DestinationPartner, null);
     }
     catch (Exception ex)
     {
         LogEngine.WriteLog(Configuration.General_Source,
                            string.Format("Error in {0}", MethodBase.GetCurrentMethod().Name),
                            Constant.Error_EventID_High_Critical_,
                            Constant.TaskCategories_,
                            ex,
                            EventLogEntryType.Error);
     }
 }
コード例 #11
0
        public void PersistSingleDataToStorage(byte[] messageBody, string blockId)
        {
            try
            {
                var storageAccountName = Configuration.GroupEventHubsStorageAccountName();
                var storageAccountKey  = Configuration.GroupEventHubsStorageAccountKey();
                var connectionString   =
                    $"DefaultEndpointsProtocol=https;AccountName={storageAccountName};AccountKey={storageAccountKey}";
                var storageAccount = CloudStorageAccount.Parse(connectionString);
                var blobClient     = storageAccount.CreateCloudBlobClient();

                // Retrieve a reference to a container.
                var container = blobClient.GetContainerReference(Configuration.GroupEventHubsName());

                // Create the container if it doesn't already exist.
                container.CreateIfNotExists();
                container.SetPermissions(
                    new BlobContainerPermissions {
                    PublicAccess = BlobContainerPublicAccessType.Blob
                });

                // Create the messageid reference
                var blockBlob = container.GetBlockBlobReference(blockId);
                blockBlob.UploadFromByteArray(messageBody, 0, messageBody.Length);
                LogEngine.ConsoleWriteLine(
                    "Event persisted -  Consistency Transaction Point created.",
                    ConsoleColor.DarkGreen);
            }
            catch (Exception ex)
            {
                LogEngine.WriteLog(
                    Configuration.EngineName,
                    $"Error in {MethodBase.GetCurrentMethod().Name}",
                    Constant.ErrorEventIdHighCritical,
                    Constant.TaskCategoriesError,
                    ex,
                    EventLogEntryType.Error);
            }
        }
コード例 #12
0
 /// <summary>
 ///     If restart required it perform the operations
 /// </summary>
 public static void CheckServiceStates()
 {
     while (true)
     {
         Thread.Sleep(10000);
         if (ServiceStates.RestartNeeded)
         {
             LogEngine.ConsoleWriteLine(
                 "--------------------------------------------------------",
                 ConsoleColor.DarkYellow);
             LogEngine.ConsoleWriteLine(
                 "Service needs restarting.",
                 ConsoleColor.Red);
             LogEngine.ConsoleWriteLine(
                 "--------------------------------------------------------",
                 ConsoleColor.DarkYellow);
             ServiceStates.RestartNeeded = false;
             //Thread.Sleep(Configuration.WaitTimeBeforeRestarting());
         }
     }
     // ReSharper disable once FunctionNeverReturns
 }
コード例 #13
0
 /// <summary>
 /// Starts the core Engine.
 /// </summary>
 public static void StartEngine()
 {
     try
     {
         // Start NT service
         Debug.WriteLine("LogEventUpStream - Initialization--Start Engine.");
         LogEngine.ConsoleWriteLine("Initialization--Start Engine.", ConsoleColor.Green);
         LogEngine.Init();
         Debug.WriteLine("LogEventUpStream - StartEventEngine.");
         CoreEngine.StartEventEngine(null);
     }
     catch (Exception ex)
     {
         LogEngine.WriteLog(
             Configuration.EngineName, 
             $"Error in {MethodBase.GetCurrentMethod().Name}", 
             Constant.DefconOne, 
             Constant.TaskCategoriesError, 
             ex, 
             EventLogEntryType.Error);
         Thread.Sleep(Configuration.WaitTimeBeforeRestarting());
         Environment.Exit(0);
     }
 }
コード例 #14
0
ファイル: OffRampEngine.cs プロジェクト: debiaggi/GrabCaster
        /// <summary>
        /// TODO The send message on ramp.
        /// </summary>
        /// <param name="bubblingTriggerConfiguration">
        /// TODO The bubbling trigger configuration.
        /// </param>
        /// <param name="ehMessageType">
        /// TODO The eh message type.
        /// </param>
        /// <param name="channelId">
        /// TODO The channel id.
        /// </param>
        /// <param name="pointId">
        /// TODO The point id.
        /// </param>
        /// <param name="properties">
        /// TODO The properties.
        /// </param>
        public static void SendMessageOnRamp(
            object bubblingTriggerConfiguration,
            Configuration.MessageDataProperty ehMessageType,
            string channelId,
            string pointId,
            Dictionary <string, object> properties,
            string pointIdOverrided)
        {
            try
            {
                if (Configuration.RunLocalOnly())
                {
                    LogEngine.WriteLog(Configuration.EngineName,
                                       $"Impossible to send the message using a remote message storage provider, this GrabCaster point is configured for local only execution.",
                                       Constant.DefconOne,
                                       Constant.TaskCategoriesError,
                                       null,
                                       EventLogEntryType.Warning);
                    return;
                }

                // Meter and measuring purpose
                var stopWatch = new Stopwatch();
                stopWatch.Start();
                byte[] serializedMessage = null;
                // Create EH data message
                if (ehMessageType != Configuration.MessageDataProperty.ByteArray)
                {
                    serializedMessage = SerializationEngine.ObjectToByteArray(bubblingTriggerConfiguration);
                }
                else
                {
                    serializedMessage = (byte[])bubblingTriggerConfiguration;
                }

                var             messageId = Guid.NewGuid().ToString();
                SkeletonMessage data      = new SkeletonMessage(null);

                // IF > 256kb then persist
                if (serializedMessage.Length > secondaryPersistProviderByteSize && !secondaryPersistProviderEnabled)
                {
                    LogEngine.WriteLog(Configuration.EngineName,
                                       $"Error in {MethodBase.GetCurrentMethod().Name} - Impossible to send the message, the message body size if bigger than the secondaryPersistProviderByteSize paramenter but the secondaryPersistProviderEnabled is false.\rConsider to enable the secondaryPersistProviderEnabled paramanter in the config file and configure the storage component.",
                                       Constant.DefconOne,
                                       Constant.TaskCategoriesError,
                                       null,
                                       EventLogEntryType.Error);

                    return;
                }

                if (serializedMessage.Length > secondaryPersistProviderByteSize && secondaryPersistProviderEnabled)
                {
                    data.Body = Encoding.UTF8.GetBytes(messageId);
                    ParametersCreateEventUpStream[0] = serializedMessage;
                    ParametersCreateEventUpStream[1] = messageId;
                    methodPersistEventToBlob.Invoke(classInstanceDpp, ParametersCreateEventUpStream);
                    data.Properties.Add(Configuration.MessageDataProperty.Persisting.ToString(), true);
                }
                else
                {
                    data.Body = serializedMessage;
                    data.Properties.Add(Configuration.MessageDataProperty.Persisting.ToString(), false);
                }
                // Load custome Properties
                if (properties != null)
                {
                    foreach (var prop in properties)
                    {
                        data.Properties.Add(prop.Key, prop.Value);
                    }
                }

                data.Properties.Add(Configuration.MessageDataProperty.MessageId.ToString(), messageId);

                // Set main security subscription
                data.Properties.Add(Configuration.GrabCasterMessageTypeName, Configuration.GrabCasterMessageTypeValue);

                // Message context
                data.Properties.Add(
                    Configuration.MessageDataProperty.Message.ToString(),
                    Configuration.MessageDataProperty.Message.ToString());
                data.Properties.Add(Configuration.MessageDataProperty.MessageType.ToString(), ehMessageType.ToString());

                string senderid = pointIdOverrided != null? pointIdOverrided : Configuration.PointId();
                data.Properties.Add(Configuration.MessageDataProperty.SenderId.ToString(), senderid);

                data.Properties.Add(Configuration.MessageDataProperty.SenderName.ToString(), Configuration.PointName());
                data.Properties.Add(
                    Configuration.MessageDataProperty.SenderDescriprion.ToString(),
                    Configuration.PointDescription());
                data.Properties.Add(Configuration.MessageDataProperty.ChannelId.ToString(), Configuration.ChannelId());
                data.Properties.Add(
                    Configuration.MessageDataProperty.ChannelName.ToString(),
                    Configuration.ChannelName());
                data.Properties.Add(
                    Configuration.MessageDataProperty.ChannelDescription.ToString(),
                    Configuration.ChannelDescription());

                data.Properties.Add(Configuration.MessageDataProperty.ReceiverChannelId.ToString(), channelId);
                data.Properties.Add(Configuration.MessageDataProperty.ReceiverPointId.ToString(), pointId);

                stopWatch.Stop();
                var ts = stopWatch.Elapsed;
                data.Properties.Add(Configuration.MessageDataProperty.OperationTime.ToString(), ts.Milliseconds);

                lock (offRampEngine)
                {
                    if (ehMessageType == Configuration.MessageDataProperty.Event ||
                        ehMessageType == Configuration.MessageDataProperty.Trigger)
                    {
                        var bubblingEvent = (BubblingEvent)bubblingTriggerConfiguration;
                        if (Configuration.LoggingVerbose())
                        {
                            var serializedEvents = JsonConvert.SerializeObject(
                                bubblingEvent.Events,
                                Formatting.Indented,
                                new JsonSerializerSettings {
                                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                            });
                            LogEngine.ConsoleWriteLine(
                                $"Sent Message Type {ehMessageType}sent - Endpoints: {serializedEvents}",
                                ConsoleColor.Green);
                        }
                        else
                        {
                            LogEngine.ConsoleWriteLine($"Sent Message Type {ehMessageType}", ConsoleColor.Green);
                        }
                    }
                    else
                    {
                        LogEngine.ConsoleWriteLine($"Sent Message Type {ehMessageType}", ConsoleColor.Green);
                    }
                }
                offRampEngine.Enqueue(data);
            }
            catch (Exception ex)
            {
                LogEngine.WriteLog(
                    Configuration.EngineName,
                    $"Error in {MethodBase.GetCurrentMethod().Name}",
                    Constant.DefconOne,
                    Constant.TaskCategoriesEventHubs,
                    ex,
                    EventLogEntryType.Error);
            }
        }
コード例 #15
0
        public static void IngestMessagge(object message)
        {
            string senderId;
            string senderDescription;

            byte[] eventDataByte   = null;
            var    skeletonMessage = (ISkeletonMessage)message;

            // ****************************IF MESSAGE TYPE = GRABCASTER*************************
            try
            {
                // Check message subscription, it must come from engine
                if (skeletonMessage.Properties[Configuration.GrabCasterMessageTypeName].ToString()
                    != Configuration.GrabCasterMessageTypeValue)
                {
                    LogEngine.ConsoleWriteLine(
                        "Not GrabCaster message type received -DISCARED-",
                        ConsoleColor.DarkYellow);
                    return;
                }
                else
                {
                    // Who sent the message
                    senderId          = skeletonMessage.Properties[Configuration.MessageDataProperty.SenderId.ToString()].ToString();
                    senderDescription =
                        skeletonMessage.Properties[Configuration.MessageDataProperty.SenderDescriprion.ToString()].ToString();

                    //If using Guid pattern as string some system put an escape character like \ before the end brachet }

                    // Who receive the message
                    LogEngine.ConsoleWriteLine(
                        $"Event received from Sender {senderId} Sender description {senderDescription}",
                        ConsoleColor.DarkCyan);

                    // ****************************IF SAME SENDER*************************
                    //TODO DELETE the  + "debug"
                    if (senderId == Configuration.PointId() + "debug")
                    {
                        LogEngine.ConsoleWriteLine("Same sender ID event discared.", ConsoleColor.Green);
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                // If error then not message typeof (no property present.)
                LogEngine.WriteLog(
                    Configuration.EngineName,
                    $"Error in {MethodBase.GetCurrentMethod().Name} - Not GrabCaster message type received (Missing GrabCaster_MessageType_Name properties.) -DISCARED-",
                    Constant.DefconOne,
                    Constant.TaskCategoriesError,
                    ex,
                    EventLogEntryType.Error);
                return;
            }

            try
            {
                // ****************************GET FROM STORAGE IF REQUIRED*************************
                if ((bool)skeletonMessage.Properties[Configuration.MessageDataProperty.Persisting.ToString()])
                {
                    ParametersPersistEventFromBlob[0] = skeletonMessage.Properties[Configuration.MessageDataProperty.MessageId.ToString()];
                    var ret = methodPersistEventFromBlob.Invoke(classInstanceDpp, ParametersPersistEventFromBlob);
                    eventDataByte = (byte[])ret;
                }
                else
                {
                    eventDataByte = skeletonMessage.Body;
                }

                //*******************************************************************
                //              3 IF TYPES EVENT - CONSOLE - REST
                // first area events, second console, third rest
                //*******************************************************************

                // ****************************IF EVENT TYPE*************************
                if (skeletonMessage.Properties[Configuration.MessageDataProperty.MessageType.ToString()].ToString()
                    == Configuration.MessageDataProperty.Event.ToString())
                {
                    // ****************************IF EMBEDED TYPE EXECUTE TRIGGER*************************
                    if (skeletonMessage.Properties[Configuration.MessageDataProperty.Embedded.ToString()].ToString()
                        == "true")
                    {
                        var recChannelId =
                            skeletonMessage.Properties[Configuration.MessageDataProperty.ReceiverChannelId.ToString()].ToString();
                        var recPointId =
                            skeletonMessage.Properties[Configuration.MessageDataProperty.ReceiverPointId.ToString()].ToString();

                        //If using Guid pattern as string some system put an escape character like \ before the end brachet }

                        var reqAvailable = (recChannelId.Contains(Configuration.ChannelId()) &&
                                            recPointId.Contains(Configuration.PointId())) ||
                                           (recChannelId.Contains(Configuration.ChannelAll) &&
                                            recPointId.Contains(Configuration.PointId())) ||
                                           (recChannelId.Contains(Configuration.ChannelId()) &&
                                            recPointId.Contains(Configuration.ChannelAll)) ||
                                           (recChannelId.Contains(Configuration.ChannelAll) &&
                                            recPointId.Contains(Configuration.ChannelAll));

                        if (!reqAvailable)
                        {
                            return;
                        }
                        string idConfiguration =
                            skeletonMessage.Properties[Configuration.MessageDataProperty.IdConfiguration.ToString()].ToString();
                        string idComponent =
                            skeletonMessage.Properties[Configuration.MessageDataProperty.IdComponent.ToString()].ToString();

                        try
                        {
                            var triggerSingleInstance =
                                (from trigger in EventsEngine.BubblingTriggerConfigurationsSingleInstance
                                 where trigger.IdComponent == idComponent && trigger.IdConfiguration == idConfiguration
                                 select trigger).First();
                            var bubblingTriggerConfiguration = triggerSingleInstance;
                            LogEngine.ConsoleWriteLine($"Execute trigger idConfiguration {idConfiguration} and idComponent {idComponent}", ConsoleColor.Green);
                            EventsEngine.ExecuteTriggerConfiguration(bubblingTriggerConfiguration, skeletonMessage.Body);
                        }
                        catch (Exception ex)
                        {
                            LogEngine.WriteLog(Configuration.EngineName,
                                               $"Error in {MethodBase.GetCurrentMethod().Name} - ExecuteTriggerConfiguration Error - Missing the idConfiguration {idConfiguration} and idComponent {idComponent}",
                                               Constant.DefconOne,
                                               Constant.TaskCategoriesError,
                                               ex,
                                               EventLogEntryType.Error);
                        }


                        // ****************************IF EMBEDED RETURN HERE*************************
                        return;
                    }

                    // ****************************CAST TO BUBBLING EVENT*************************
                    var eventBubbling = (BubblingEvent)SerializationEngine.ByteArrayToObject(eventDataByte);

                    // ****************************PERSIST MESSAGE IN FOLDER*************************
                    PersistentProvider.PersistMessage(eventBubbling, PersistentProvider.CommunicationDiretion.OffRamp);

                    if (Configuration.LoggingVerbose())
                    {
                        var serializedEvents = JsonConvert.SerializeObject(
                            eventBubbling.Events,
                            Formatting.Indented,
                            new JsonSerializerSettings {
                            ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                        });
                        LogEngine.ConsoleWriteLine(
                            $"Event received from point id: {skeletonMessage.Properties[Configuration.MessageDataProperty.SenderId.ToString()]} -point name : {skeletonMessage.Properties[Configuration.MessageDataProperty.SenderDescriprion.ToString()]} - {serializedEvents}",
                            ConsoleColor.Green);
                    }

                    // ****************************IF EXIST EVENT TO EXECUTE*************************
                    var eventsAvailable = from eventbubble in eventBubbling.Events
                                          from channel in eventbubble.Channels
                                          from point in channel.Points
                                          where
                                          (channel.ChannelId == Configuration.ChannelId() &&
                                           point.PointId == Configuration.PointId()) ||
                                          (channel.ChannelId == Configuration.ChannelAll &&
                                           point.PointId == Configuration.PointId()) ||
                                          (channel.ChannelId == Configuration.ChannelId() &&
                                           point.PointId == Configuration.PointAll) ||
                                          (channel.ChannelId == Configuration.ChannelAll &&
                                           point.PointId == Configuration.PointAll)
                                          select eventbubble;


                    if (!eventsAvailable.Any())
                    {
                        // ****************************NO EVENT RETURN*************************
                        return;
                    }

                    // ****************************EVENT EXIST EXECUTE*************************
                    EventsEngine.ExecuteBubblingActionEvent(
                        eventBubbling,
                        false,
                        skeletonMessage.Properties[Configuration.MessageDataProperty.SenderId.ToString()].ToString());
                    return;
                }



                var receiverChannelId =
                    skeletonMessage.Properties[Configuration.MessageDataProperty.ReceiverChannelId.ToString()].ToString();
                var receiverPointId =
                    skeletonMessage.Properties[Configuration.MessageDataProperty.ReceiverPointId.ToString()].ToString();

                var requestAvailable = (receiverChannelId == Configuration.ChannelId() &&
                                        receiverPointId == Configuration.PointId()) ||
                                       (receiverChannelId == Configuration.ChannelAll &&
                                        receiverPointId == Configuration.PointId()) ||
                                       (receiverChannelId == Configuration.ChannelId() &&
                                        receiverPointId == Configuration.PointAll) ||
                                       (receiverChannelId == Configuration.ChannelAll &&
                                        receiverPointId == Configuration.PointAll);

                if (!requestAvailable)
                {
                    // ****************************NOT FOR ME*************************
                    return;
                }


                // **************************** SYNC AREA *************************
                //Save in a string to simplify the reading and code
                string OperationTypRequested =
                    skeletonMessage.Properties[Configuration.MessageDataProperty.MessageType.ToString()].ToString();

                //******************* OPERATION CONF BAG- ALL THE CONF FILES AND DLLS ****************************************************************
                //Receive the request to send the bubbling
                if (OperationTypRequested == Configuration.MessageDataProperty.ConsoleRequestSendBubblingBag.ToString())
                {
                    if (!Configuration.DisableExternalEventsStreamEngine())
                    {
                        //If I am console do nothing
                        if (Configuration.IamConsole())
                        {
                            OffRampEngineSending.SendMessageOnRamp(
                                EventsEngine.bubblingBag,
                                Configuration.MessageDataProperty.ConsoleBubblingBagToSyncronize,
                                skeletonMessage.Properties[Configuration.MessageDataProperty.ChannelId.ToString()].ToString(),
                                skeletonMessage.Properties[Configuration.MessageDataProperty.SenderId.ToString()].ToString(),
                                null,
                                null);
                        }
                    }
                    else
                    {
                        LogEngine.WriteLog(
                            Configuration.EngineName,
                            "Warning the Device Provider Interface is disable, the GrabCaster point will be able to work in local mode only.",
                            Constant.DefconThree,
                            Constant.TaskCategoriesError,
                            null,
                            EventLogEntryType.Warning);
                    }
                }
                //Receive the request to send the bubbling
                if (OperationTypRequested == Configuration.MessageDataProperty.ConsoleBubblingBagToSyncronize.ToString())
                {
                    if (!Configuration.DisableExternalEventsStreamEngine())
                    {
                        //se non sono console
                        //metto
                        if (!Configuration.IamConsole())
                        {
                            byte[] bubblingContent   = SerializationEngine.ObjectToByteArray(skeletonMessage.Body);
                            string currentSyncFolder = Configuration.SyncDirectorySyncIn();
                            GrabCaster.Framework.CompressionLibrary.Helpers.CreateFromBytearray(skeletonMessage.Body, currentSyncFolder);
                        }
                        else
                        {
                            setConsoleActionEventEmbedded(skeletonMessage.Properties[Configuration.MessageDataProperty.SenderId.ToString()].ToString(),
                                                          skeletonMessage);
                        }
                    }
                    else
                    {
                        LogEngine.WriteLog(
                            Configuration.EngineName,
                            "Warning the Device Provider Interface is disable, the GrabCaster point will be able to work in local mode only.",
                            Constant.DefconThree,
                            Constant.TaskCategoriesError,
                            null,
                            EventLogEntryType.Warning);
                    }
                }
            }
            catch (Exception ex)
            {
                LogEngine.WriteLog(Configuration.EngineName,
                                   $"Error in {MethodBase.GetCurrentMethod().Name}",
                                   Constant.DefconOne,
                                   Constant.TaskCategoriesError,
                                   ex,
                                   EventLogEntryType.Error);
            }
        }
コード例 #16
0
        } // CurrentDomain_ProcessExit

        public static void StartEngine()
        {
            try
            {
                Configuration.LoadConfiguration();
                LogEngine.Init();
                LogEngine.ConsoleWriteLine(
                    $"Version {Assembly.GetExecutingAssembly().GetName().Version}",
                    ConsoleColor.Green);

                if (Configuration.DisableExternalEventsStreamEngine())
                {
                    LogEngine.WriteLog(
                        Configuration.EngineName,
                        "Warning the Device Provider Interface is disable, the GrabCaster point will be able to work in local mode only.",
                        Constant.DefconOne,
                        Constant.TaskCategoriesError,
                        null,
                        EventLogEntryType.Warning);
                }
                // Could be useful?
                //if (!Environment.UserInteractive)
                //{
                //    Debug.WriteLine("GrabCaster-servicesToRun procedure initialization.");
                //    // ServiceBase[] servicesToRun = { new NTWindowsService() };
                //    Debug.WriteLine("GrabCaster-servicesToRun procedure starting.");
                //    // ServiceBase.Run(servicesToRun);
                //}

                LogEngine.ConsoleWriteLine("--GrabCaster Sevice Initialization--Start Engine.", ConsoleColor.Green);
                delegateActionEvent = delegateActionEventEmbedded;
                CoreEngine.StartEventEngine(delegateActionEvent);
                engineLoaded = true;
                Thread.Sleep(Timeout.Infinite);
            }
            catch (NotImplementedException ex)
            {
                Methods.DirectEventViewerLog(ex);
                LogEngine.WriteLog(
                    Configuration.EngineName,
                    "Error in " + MethodBase.GetCurrentMethod().Name,
                    Constant.DefconOne,
                    Constant.TaskCategoriesError,
                    ex,
                    EventLogEntryType.Error);
            }
            catch (Exception ex)
            {
                Methods.DirectEventViewerLog(ex);
                Environment.Exit(0);
            } // try/catch
            finally
            {
                //Spool log queues
                if (LogEngine.QueueAbstractMessage != null)
                {
                    LogEngine.QueueAbstractMessageOnPublish(LogEngine.QueueAbstractMessage.ToArray().ToList());
                }
                if (LogEngine.QueueConsoleMessage != null)
                {
                    LogEngine.QueueConsoleMessageOnPublish(LogEngine.QueueConsoleMessage.ToArray().ToList());
                }
            }
        }
コード例 #17
0
        /// <summary>
        ///     Execute polling
        /// </summary>
        /// restart
        public static void StartEventEngine(SetEventActionEvent delegateActionEventEmbedded)
        {
            try
            {
                var current = AppDomain.CurrentDomain;
                current.AssemblyResolve += HandleAssemblyResolve;

                LogEngine.Enabled = Configuration.LoggingEngineEnabled();
                LogEngine.ConsoleWriteLine("Load Engine configuration.", ConsoleColor.White);

                //****************************Check for updates
                //Check if need to update files received from partners
                LogEngine.ConsoleWriteLine("Check Engine Syncronization.", ConsoleColor.White);
                EventsEngine.CheckForFileToUpdate();
                //****************************Check for updates

                //Set service states
                LogEngine.ConsoleWriteLine("Initialize Engine Service states.", ConsoleColor.White);
                ServiceStates.RunPolling    = true;
                ServiceStates.RestartNeeded = false;

                LogEngine.ConsoleWriteLine("Initialize Engine.", ConsoleColor.Cyan);
                EventsEngine.InitializeEventEngine(delegateActionEventEmbedded);

                //Init Message ingestor
                MessageIngestor.Init();

                //Create the two sends layers
                // in EventsEngine
                if (!Configuration.DisableExternalEventsStreamEngine())
                {
                    LogEngine.ConsoleWriteLine("Start Internal Event Engine Channel.", ConsoleColor.Yellow);
                    var canStart = EventsEngine.CreateEventUpStream();

                    if (!canStart)
                    {
                        LogEngine.WriteLog(
                            Configuration.EngineName,
                            $"Error during engine service starting. Name: {Configuration.EngineName} - ID: {Configuration.ChannelId()}",
                            Constant.DefconOne,
                            Constant.TaskCategoriesError,
                            null,
                            EventLogEntryType.Error);
                        Thread.Sleep(Configuration.WaitTimeBeforeRestarting());
                        Environment.Exit(0);
                    }

                    //in EventUpStream
                    LogEngine.ConsoleWriteLine("Start External Event Engine Channel.", ConsoleColor.Yellow);
                    //OnRamp start the OnRamp Engine
                    canStart = OffRampEngineSending.Init("MSP Device Component.dll (vNext)");

                    if (!canStart)
                    {
                        LogEngine.WriteLog(
                            Configuration.EngineName,
                            $"Error during engine service starting. Name: {Configuration.ChannelName()} - ID: {Configuration.ChannelId()}",
                            Constant.DefconOne,
                            Constant.TaskCategoriesError,
                            null,
                            EventLogEntryType.Error);
                        Thread.Sleep(Configuration.WaitTimeBeforeRestarting());
                        Environment.Exit(0);
                    }
                }

                //*****************Event object stream area*********************
                //Load the global event and triggers dlls
                var numOfTriggers = 0;
                var numOfEvents   = 0;

                var triggersAndEventsLoaded = EventsEngine.LoadBubblingEventList(ref numOfTriggers, ref numOfEvents);
                if (triggersAndEventsLoaded)
                {
                    LogEngine.ConsoleWriteLine(
                        $"Triggers loaded {numOfTriggers} - Events loaded {numOfEvents}",
                        ConsoleColor.DarkCyan);
                }

                EventsEngine.UpdateAssemblyEventListShared();
                //Load the Active triggers and the active events
                EventsEngine.RefreshBubblingSetting();
                //Start triggers single instances
                EventsEngine.ExecuteBubblingTriggerConfigurationsSingleInstance();
                //Start triggers polling instances
                if (Configuration.EnginePollingTime() > 0)
                {
                    var treadPollingRun = new Thread(StartTriggerPolling);
                    treadPollingRun.Start();
                }
                else
                {
                    LogEngine.WriteLog(Configuration.EngineName,
                                       $"Configuration.EnginePollingTime = {Configuration.EnginePollingTime()}, internal polling system disabled.",
                                       Constant.DefconOne,
                                       Constant.TaskCategoriesError,
                                       null,
                                       EventLogEntryType.Warning);
                }

                //Start Engine Service
                LogEngine.ConsoleWriteLine(
                    "Asyncronous Threading Service state active.",
                    ConsoleColor.DarkCyan);
                var treadEngineStates = new Thread(CheckServiceStates);
                treadEngineStates.Start();

                if (!Configuration.DisableExternalEventsStreamEngine())
                {
                    LogEngine.ConsoleWriteLine("Start On Ramp Engine.", ConsoleColor.Green);
                    var onRampEngineReceiving = new OnRampEngineReceiving();
                    onRampEngineReceiving.Init("component.dll name");
                }
                // Configuration files watcher
                EventsEngine.StartConfigurationSyncEngine();

                LogEngine.WriteLog(
                    Configuration.EngineName,
                    $"Engine service initialization procedure terminated. Name: {Configuration.ChannelName()} - ID: {Configuration.ChannelId()}",
                    Constant.DefconOne,
                    Constant.TaskCategoriesError,
                    null,
                    EventLogEntryType.Information);
            }
            catch (Exception ex)
            {
                LogEngine.WriteLog(
                    Configuration.EngineName,
                    $"Error in {MethodBase.GetCurrentMethod().Name}",
                    Constant.DefconOne,
                    Constant.TaskCategoriesError,
                    ex,
                    EventLogEntryType.Error);
            }
        }
コード例 #18
0
        /// <summary>
        ///     Execute polling
        /// </summary>
        private static void StartTriggerPolling()
        {
            //running thread polling
            var pollingTime = Configuration.EnginePollingTime();

            try
            {
                if (pollingTime == 0)
                {
                    LogEngine.WriteLog(
                        Configuration.EngineName,
                        $"EnginePollingTime = 0 - Internal logging system disabled.",
                        Constant.DefconOne,
                        Constant.TaskCategoriesError,
                        null,
                        EventLogEntryType.Warning);
                    return;
                }
                else
                {
                    LogEngine.ConsoleWriteLine("Start Trigger Polling Cycle", ConsoleColor.Blue);
                }


                while (ServiceStates.RunPolling)
                {
                    if (ServiceStates.RestartNeeded)
                    {
                        LogEngine.ConsoleWriteLine(
                            "--------------------------------------------------------",
                            ConsoleColor.DarkYellow);
                        LogEngine.ConsoleWriteLine("- UPDATE READY - SERVICE NEEDS RESTART -", ConsoleColor.Red);
                        LogEngine.ConsoleWriteLine(
                            "--------------------------------------------------------",
                            ConsoleColor.DarkYellow);
                        //ServiceStates.RunPolling = false;
                        return;
                    }
                    ++pollingStep;
                    if (pollingStep > 9)
                    {
                        LogEngine.ConsoleWriteLine(
                            $"Execute Trigger Polling {pollingStep} Cycle",
                            ConsoleColor.Blue);
                        pollingStep = 0;
                    }
                    Thread.Sleep(pollingTime);
                    var treadPollingRun = new Thread(EventsEngine.ExecuteBubblingTriggerConfigurationPolling);
                    lock (treadPollingRun)
                    {
                        treadPollingRun.Start();
                    }
                }
            }
            catch (Exception ex)
            {
                LogEngine.WriteLog(
                    Configuration.EngineName,
                    $"Error in {MethodBase.GetCurrentMethod().Name}",
                    Constant.DefconOne,
                    Constant.TaskCategoriesError,
                    ex,
                    EventLogEntryType.Error);
            }
        }
コード例 #19
0
ファイル: Program.cs プロジェクト: debiaggi/GrabCaster
        } // CurrentDomain_ProcessExit

        /// <summary>
        /// Mains the main entry to the program.
        /// </summary>
        /// <param name="args">The arguments to the program.</param>
        /// <exception cref="System.NotImplementedException">
        /// Exception thrown if incorrect parameters are passed to the command-line.
        /// </exception>
        public static void Main(string[] args)
        {
            try
            {

                LogEngine.Init();
                LogEngine.ConsoleWriteLine(
                    $"Version {Assembly.GetExecutingAssembly().GetName().Version}",
                    ConsoleColor.Green);

                if (Configuration.DisableExternalEventsStreamEngine())
                {
                    LogEngine.WriteLog(
                        Configuration.EngineName,
                        "Warning the Device Provider Interface is disable, the GrabCaster point will be able to work in local mode only.",
                        Constant.DefconThree,
                        Constant.TaskCategoriesError,
                        null,
                        EventLogEntryType.Warning);
                }

                if (!Environment.UserInteractive)
                {
                    Debug.WriteLine("GrabCaster-servicesToRun procedure initialization.");
                    ServiceBase[] servicesToRun = { new NTWindowsService() };
                    Debug.WriteLine("GrabCaster-servicesToRun procedure starting.");
                    ServiceBase.Run(servicesToRun);
                }
                else
                {

                    if (args.Length == 0)
                    {
                        // Set Console windows
                        Console.Title = Configuration.PointName();
                        Console.SetWindowPosition(0, 0);
                        Console.Clear();
                        Console.ForegroundColor = ConsoleColor.Green;
                        Console.WriteLine(@"[M] Run GrabCaster in MS-DOS Console mode.");
                        Console.WriteLine(@"[I] Install GrabCaster Windows NT Service.");
                        Console.WriteLine(@"[U] Uninstall GrabCaster Windows NT Service.");
                        Console.WriteLine(@"[C] Clone a new GrabCaster Point.");
                        Console.WriteLine(@"[Ctrl + C] Exit.");
                        Console.ForegroundColor = ConsoleColor.White;
                        var consoleKeyInfo = Console.ReadKey();

                        switch (consoleKeyInfo.Key)
                        {
                            case ConsoleKey.M:
                                AppDomain.CurrentDomain.ProcessExit += CurrentDomainProcessExit;
                                LogEngine.ConsoleWriteLine(
                                    "--GrabCaster Sevice Initialization--Start Engine.",
                                    ConsoleColor.Green);
                                CoreEngine.StartEventEngine(null);
                                Console.ReadLine();
                                break;
                            case ConsoleKey.I:
                                Console.ForegroundColor = ConsoleColor.White;
                                Console.Clear();
                                CoreNtService.ServiceName = AskInputLine("Specify the Windows NT Service Name:");
                                CoreNtService.InstallService();
                                break;
                            case ConsoleKey.U:
                                Console.ForegroundColor = ConsoleColor.White;
                                Console.Clear();
                                CoreNtService.ServiceName = AskInputLine("Specify the Windows NT Service Name:");
                                CoreNtService.StopService();
                                CoreNtService.UninstallService();
                                break;
                            case ConsoleKey.C:
                                //string CloneName = AskInputLine("Enter the Clone name.");
                                Process.Start(Path.Combine(Application.StartupPath, "Create new Clone.cmd"));
                                break;
                        }
                    } //if
                    else
                    {
                        //Run in batch and console mode
                        if (args.Length == 1 && args[0] == "-console".ToLower())
                        {
                            LogEngine.ConsoleWriteLine(
                                "--GrabCaster Sevice Initialization--Start Engine.",
                                ConsoleColor.Green);
                            CoreEngine.StartEventEngine(null);
                            Console.ReadLine();
                        }
                        else if (args.Length == 2 && args[0] == "-ntinstall".ToLower())
                        {
                            CoreNtService.ServiceName = string.Concat("GrabCaster", args[1]);
                            CoreNtService.InstallService();
                            Environment.Exit(0);
                        }
                        else if (args.Length == 2 && args[0] == "-ntuninstall".ToLower())
                        {
                            CoreNtService.ServiceName = string.Concat("GrabCaster", args[1]);
                            CoreNtService.StopService();
                            CoreNtService.UninstallService();
                            Environment.Exit(0);
                        }
                        else
                        {
                            Console.Clear();
                            LogEngine.ConsoleWriteLine(
                                @"GrabCaster [-console]  [-ntinstall servicename] [-ntuninstall servicename]",
                                ConsoleColor.Green);
                            LogEngine.ConsoleWriteLine("", ConsoleColor.DarkGreen);
                            LogEngine.ConsoleWriteLine(
                                @"[-console] Execute GrabCaster in MS Dos console mode.",
                                ConsoleColor.Green);
                            LogEngine.ConsoleWriteLine(
                                "[-ntinstall servicename] Install jiGate as Windows NT Service servicename.",
                                ConsoleColor.Green);
                            LogEngine.ConsoleWriteLine(
                                "[-ntuninstall servicename] Uninstall the GrabCaster Windows NT Service servicename.",
                                ConsoleColor.Green);

                            Console.ReadLine();
                            Environment.Exit(0);
                        }
                    }
                } // if
            }
            catch (NotImplementedException ex)
            {
                Methods.DirectEventViewerLog(ex);
                LogEngine.WriteLog(
                    Configuration.EngineName,
                    "Error in " + MethodBase.GetCurrentMethod().Name,
                    Constant.DefconOne,
                    Constant.TaskCategoriesError,
                    ex,
                    EventLogEntryType.Error);
            }
            catch (Exception ex)
            {
                Methods.DirectEventViewerLog(ex);
                Environment.Exit(0);
            } // try/catch
            finally
            {
                //Spool log queues
                if (LogEngine.QueueAbstractMessage != null)
                {
                    LogEngine.QueueAbstractMessageOnPublish(LogEngine.QueueAbstractMessage.ToArray().ToList());
                }
                if (LogEngine.QueueConsoleMessage != null)
                {
                    LogEngine.QueueConsoleMessageOnPublish(LogEngine.QueueConsoleMessage.ToArray().ToList());
                }
            }
        } // Main
コード例 #20
0
        public void Run(SetEventOnRampMessageReceived setEventOnRampMessageReceived)
        {
            try
            {
                // Assign the delegate
                SetEventOnRampMessageReceived = setEventOnRampMessageReceived;
                // Load vars
                var eventHubConnectionString = Configuration.AzureNameSpaceConnectionString();
                var eventHubName             = Configuration.GroupEventHubsName();

                LogEngine.WriteLog(
                    Configuration.EngineName,
                    $"Event Hubs transfort Type: {Configuration.ServiceBusConnectivityMode()}",
                    Constant.DefconOne,
                    Constant.TaskCategoriesError,
                    null,
                    EventLogEntryType.Information);

                var builder = new ServiceBusConnectionStringBuilder(eventHubConnectionString)
                {
                    TransportType =
                        TransportType.Amqp
                };

                //If not exit it create one, drop brachets because Azure rules
                var eventHubConsumerGroup =
                    string.Concat(Configuration.EngineName, "_", Configuration.ChannelId())
                    .Replace("{", "")
                    .Replace("}", "")
                    .Replace("-", "");
                var nsManager = NamespaceManager.CreateFromConnectionString(builder.ToString());
                LogEngine.ConsoleWriteLine(
                    $"Initializing Group Name {eventHubConsumerGroup}",
                    ConsoleColor.White);

                LogEngine.ConsoleWriteLine("Start DirectRegisterEventReceiving.", ConsoleColor.White);

                // Create Event Hubs
                var eventHubClient = EventHubClient.CreateFromConnectionString(builder.ToString(), eventHubName);
                // Create consumer
                nsManager.CreateConsumerGroupIfNotExists(eventHubName, eventHubConsumerGroup);

                var namespaceManager = NamespaceManager.CreateFromConnectionString(builder.ToString());
                var ehDescription    = namespaceManager.GetEventHub(eventHubName);
                // Use the default consumer group

                foreach (var partitionId in ehDescription.PartitionIds)
                {
                    var myNewThread =
                        new Thread(() => ReceiveDirectFromPartition(eventHubClient, partitionId, eventHubConsumerGroup));
                    myNewThread.Start();
                }

                LogEngine.ConsoleWriteLine(
                    "After DirectRegisterEventReceiving Downstream running.",
                    ConsoleColor.White);
            }
            catch (Exception ex)
            {
                LogEngine.WriteLog(
                    Configuration.EngineName,
                    $"Error in {MethodBase.GetCurrentMethod().Name} - Hint: Check if the firewall outbound port 5671 is opened.",
                    Constant.DefconOne,
                    Constant.TaskCategoriesEventHubs,
                    ex,
                    EventLogEntryType.Error);
            }
        }
コード例 #21
0
        public static void IngestMessagge(object message)
        {
            string senderId;
            string senderDescription;

            byte[] eventDataByte   = null;
            var    skeletonMessage = (ISkeletonMessage)message;

            // ****************************IF MESSAGE TYPE = GRABCASTER*************************
            try
            {
                // Check message subscription, it must come from engine
                if (skeletonMessage.Properties[Configuration.GrabCasterMessageTypeName].ToString()
                    != Configuration.GrabCasterMessageTypeValue)
                {
                    LogEngine.ConsoleWriteLine(
                        "Not GrabCaster message type received -DISCARED-",
                        ConsoleColor.DarkYellow);
                    return;
                }
                else
                {
                    // Who sent the message
                    senderId          = skeletonMessage.Properties[Configuration.MessageDataProperty.SenderId.ToString()].ToString();
                    senderDescription =
                        skeletonMessage.Properties[Configuration.MessageDataProperty.SenderDescriprion.ToString()].ToString();

                    //If using Guid pattern as string some system put an escape character like \ before the end brachet }

                    // Who receive the message
                    LogEngine.ConsoleWriteLine(
                        $"Event received from Sender {senderId} Sender description {senderDescription}",
                        ConsoleColor.DarkCyan);

                    // ****************************IF SAME SENDER*************************
                    if (senderId == Configuration.PointId())
                    {
                        LogEngine.ConsoleWriteLine("Same sender ID event discared.", ConsoleColor.Green);
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                // If error then not message typeof (no property present.)
                LogEngine.WriteLog(
                    Configuration.EngineName,
                    $"Error in {MethodBase.GetCurrentMethod().Name} - Not GrabCaster message type received (Missing GrabCaster_MessageType_Name properties.) -DISCARED-",
                    Constant.ErrorEventIdHighCritical,
                    Constant.TaskCategoriesError,
                    ex,
                    EventLogEntryType.Error);
                return;
            }

            try
            {
                // ****************************GET FROM STORAGE IF REQUIRED*************************
                if ((bool)skeletonMessage.Properties[Configuration.MessageDataProperty.Persisting.ToString()])
                {
                    ParametersPersistEventFromBlob[0] = skeletonMessage.Properties[Configuration.MessageDataProperty.MessageId.ToString()];
                    var ret = methodPersistEventFromBlob.Invoke(classInstanceDpp, ParametersPersistEventFromBlob);
                    eventDataByte = (byte[])ret;
                }
                else
                {
                    eventDataByte = skeletonMessage.Body;
                }

                //*******************************************************************
                //              3 IF TYPES EVENT - CONSOLE - REST
                // first area events, second console, third rest
                //*******************************************************************

                // ****************************IF EVENT TYPE*************************
                if (skeletonMessage.Properties[Configuration.MessageDataProperty.MessageType.ToString()].ToString()
                    == Configuration.MessageDataProperty.Event.ToString())
                {
                    // ****************************IF EMBEDED TYPE EXECUTE TRIGGER*************************
                    if (skeletonMessage.Properties[Configuration.MessageDataProperty.Embedded.ToString()].ToString()
                        == "true")
                    {
                        var recChannelId =
                            skeletonMessage.Properties[Configuration.MessageDataProperty.ReceiverChannelId.ToString()].ToString();
                        var recPointId =
                            skeletonMessage.Properties[Configuration.MessageDataProperty.ReceiverPointId.ToString()].ToString();

                        //If using Guid pattern as string some system put an escape character like \ before the end brachet }

                        var reqAvailable = (recChannelId.Contains(Configuration.ChannelId()) &&
                                            recPointId.Contains(Configuration.PointId())) ||
                                           (recChannelId.Contains(Configuration.ChannelAll) &&
                                            recPointId.Contains(Configuration.PointId())) ||
                                           (recChannelId.Contains(Configuration.ChannelId()) &&
                                            recPointId.Contains(Configuration.ChannelAll)) ||
                                           (recChannelId.Contains(Configuration.ChannelAll) &&
                                            recPointId.Contains(Configuration.ChannelAll));

                        if (!reqAvailable)
                        {
                            return;
                        }
                        string idConfiguration =
                            skeletonMessage.Properties[Configuration.MessageDataProperty.IdConfiguration.ToString()].ToString();
                        string idComponent =
                            skeletonMessage.Properties[Configuration.MessageDataProperty.IdComponent.ToString()].ToString();

                        try
                        {
                            var triggerSingleInstance =
                                (from trigger in EventsEngine.BubblingTriggerConfigurationsSingleInstance
                                 where trigger.IdComponent == idComponent && trigger.IdConfiguration == idConfiguration
                                 select trigger).First();
                            var bubblingTriggerConfiguration = triggerSingleInstance;
                            LogEngine.ConsoleWriteLine($"Execute trigger idConfiguration {idConfiguration} and idComponent {idComponent}", ConsoleColor.Green);
                            EventsEngine.ExecuteTriggerConfiguration(bubblingTriggerConfiguration, skeletonMessage.Body);
                        }
                        catch (Exception ex)
                        {
                            LogEngine.WriteLog(Configuration.EngineName,
                                               $"Error in {MethodBase.GetCurrentMethod().Name} - ExecuteTriggerConfiguration Error - Missing the idConfiguration {idConfiguration} and idComponent {idComponent}",
                                               Constant.ErrorEventIdHighCritical,
                                               Constant.TaskCategoriesError,
                                               ex,
                                               EventLogEntryType.Error);
                        }


                        // ****************************IF EMBEDED RETURN HERE*************************
                        return;
                    }

                    // ****************************CAST TO BUBBLING EVENT*************************
                    var eventBubbling = (BubblingEvent)SerializationEngine.ByteArrayToObject(eventDataByte);

                    // ****************************PERSIST MESSAGE IN FOLDER*************************
                    PersistentProvider.PersistMessage(eventBubbling, PersistentProvider.CommunicationDiretion.OffRamp);

                    if (Configuration.LoggingVerbose())
                    {
                        var serializedEvents = JsonConvert.SerializeObject(
                            eventBubbling.Events,
                            Formatting.Indented,
                            new JsonSerializerSettings {
                            ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                        });
                        LogEngine.ConsoleWriteLine(
                            $"Event received from point id: {skeletonMessage.Properties[Configuration.MessageDataProperty.SenderId.ToString()]} -point name : {skeletonMessage.Properties[Configuration.MessageDataProperty.SenderDescriprion.ToString()]} - {serializedEvents}",
                            ConsoleColor.Green);
                    }

                    // ****************************IF EXIST EVENT TO EXECUTE*************************
                    var eventsAvailable = from eventbubble in eventBubbling.Events
                                          from channel in eventbubble.Channels
                                          from point in channel.Points
                                          where
                                          (channel.ChannelId == Configuration.ChannelId() &&
                                           point.PointId == Configuration.PointId()) ||
                                          (channel.ChannelId == Configuration.ChannelAll &&
                                           point.PointId == Configuration.PointId()) ||
                                          (channel.ChannelId == Configuration.ChannelId() &&
                                           point.PointId == Configuration.PointAll) ||
                                          (channel.ChannelId == Configuration.ChannelAll &&
                                           point.PointId == Configuration.PointAll)
                                          select eventbubble;


                    if (!eventsAvailable.Any())
                    {
                        // ****************************NO EVENT RETURN*************************
                        return;
                    }

                    // ****************************EVENT EXIST EXECUTE*************************
                    EventsEngine.ExecuteBubblingActionEvent(
                        eventBubbling,
                        false,
                        skeletonMessage.Properties[Configuration.MessageDataProperty.SenderId.ToString()].ToString());
                    return;
                }



                var receiverChannelId =
                    skeletonMessage.Properties[Configuration.MessageDataProperty.ReceiverChannelId.ToString()].ToString();
                var receiverPointId =
                    skeletonMessage.Properties[Configuration.MessageDataProperty.ReceiverPointId.ToString()].ToString();

                var requestAvailable = (receiverChannelId == Configuration.ChannelId() &&
                                        receiverPointId == Configuration.PointId()) ||
                                       (receiverChannelId == Configuration.ChannelAll &&
                                        receiverPointId == Configuration.PointId()) ||
                                       (receiverChannelId == Configuration.ChannelId() &&
                                        receiverPointId == Configuration.PointAll) ||
                                       (receiverChannelId == Configuration.ChannelAll &&
                                        receiverPointId == Configuration.PointAll);

                if (!requestAvailable)
                {
                    // ****************************NOT FOR ME*************************
                    return;
                }


                // **************************** IF CONSOLE TYPE *************************
                //Save in a string to simplify the reading and code
                string OperationTypRequested =
                    skeletonMessage.Properties[Configuration.MessageDataProperty.MessageType.ToString()].ToString();

                //******************* OPERATION CONF BAG- ALL THE CONF FILES AND DLLS ****************************************************************
                if (OperationTypRequested
                    == Configuration.MessageDataProperty.ConsoleSendBubblingBag.ToString() ||
                    OperationTypRequested
                    == Configuration.MessageDataProperty.ConsoleSendBubblingBagFromPoint.ToString())
                {
                    //If send or received operaion
                    bool sendOperation = true && OperationTypRequested == Configuration.MessageDataProperty.ConsoleSendBubblingBag.ToString();
                    if (!Configuration.DisableDeviceProviderInterface())
                    {
                        if (sendOperation)
                        {
                            OffRampEngineSending.SendMessageOnRamp(
                                EventsEngine.bubblingBag,
                                Configuration.MessageDataProperty.ConsoleSendBubblingBagFromPoint,
                                skeletonMessage.Properties[Configuration.MessageDataProperty.ChannelId.ToString()].ToString(),
                                skeletonMessage.Properties[Configuration.MessageDataProperty.SenderId.ToString()].ToString(),
                                null,
                                null);
                        }
                        else
                        {
                            setConsoleActionEventEmbedded(
                                Configuration.MessageDataProperty.ReceiverPointId.ToString(),
                                skeletonMessage);
                        }
                    }
                    else
                    {
                        LogEngine.WriteLog(
                            Configuration.EngineName,
                            "Warning the Device Provider Interface is disable, the GrabCaster point will be able to work in local mode only.",
                            Constant.ErrorEventIdHighCritical,
                            Constant.TaskCategoriesError,
                            null,
                            EventLogEntryType.Warning);
                    }
                }
                //******************* OPERATION CONF BAG- ALL THE CONF FILES AND DLLS ****************************************************************



                // **************************** REST SERVICE CALLS AREA *************************

                //RICEVE I BUBBLINGS
                // ****************************WRITE THE TRIGGERS AND EVENTS CONFIGURATION FILES IN FOLDERS*************************
                if (skeletonMessage.Properties[Configuration.MessageDataProperty.MessageType.ToString()].ToString()
                    == Configuration.MessageDataProperty.SyncSendBubblingConfiguration.ToString())
                {
                    // eventDataByte = NULL
                    LogEngine.ConsoleWriteLine(
                        $"SyncSendBubblingConfiguration from - {senderId} - {senderDescription}",
                        ConsoleColor.Cyan);
                    var syncConfigurationFilelIst =
                        (List <SyncConfigurationFile>)SerializationEngine.ByteArrayToObject(eventDataByte);
                    SyncProvider.SyncBubblingConfigurationFileList(
                        syncConfigurationFilelIst,
                        skeletonMessage.Properties[Configuration.MessageDataProperty.MessageType.ToString()].ToString(),
                        skeletonMessage.Properties[Configuration.MessageDataProperty.SenderId.ToString()].ToString(),
                        skeletonMessage.Properties[Configuration.MessageDataProperty.SenderName.ToString()].ToString(),
                        skeletonMessage.Properties[Configuration.MessageDataProperty.SenderDescriprion.ToString()].ToString(),
                        skeletonMessage.Properties[Configuration.MessageDataProperty.ChannelId.ToString()].ToString(),
                        skeletonMessage.Properties[Configuration.MessageDataProperty.ChannelName.ToString()].ToString(),
                        skeletonMessage.Properties[Configuration.MessageDataProperty.ChannelDescription.ToString()].ToString());
                    return;
                }

                //RICEVE LA CONF DAL PUNTO
                // ****************************WRITE THE POINT CONFIGURATION FILE IN FOLDERs*************************
                if (skeletonMessage.Properties[Configuration.MessageDataProperty.MessageType.ToString()].ToString()
                    == Configuration.MessageDataProperty.SyncSendConfiguration.ToString())
                {
                    // EventDataByte = NULL
                    LogEngine.ConsoleWriteLine(
                        $"SyncSendConfiguration from - {senderId} - {senderDescription}",
                        ConsoleColor.Cyan);
                    SyncProvider.SyncWriteConfiguration(
                        skeletonMessage.Properties[Configuration.MessageDataProperty.ChannelId.ToString()].ToString(),
                        skeletonMessage.Properties[Configuration.MessageDataProperty.SenderId.ToString()].ToString(),
                        eventDataByte);
                    return;
                }

                //RICEVE E SCRIVE UN FILE DI CONFIGURAZIONE TRIGGER O EVENT NELLA BUBBLIG
                // ****************************WRITE THE SPECIFIC BUBBLING FILE IN FOLDERS*************************
                if (skeletonMessage.Properties[Configuration.MessageDataProperty.MessageType.ToString()].ToString()
                    == Configuration.MessageDataProperty.SyncSendFileBubblingConfiguration.ToString())
                {
                    // EventDataByte = NULL
                    LogEngine.ConsoleWriteLine(
                        $"SyncSendFileBubblingConfiguration from - {senderId} - {senderDescription}",
                        ConsoleColor.Cyan);
                    var syncConfigurationFilelIst =
                        (List <SyncConfigurationFile>)SerializationEngine.ByteArrayToObject(eventDataByte);
                    SyncProvider.SyncLocalBubblingConfigurationFile(syncConfigurationFilelIst);
                    return;
                }


                //SCRIVE UN COMP DLL IN EVENTO O TRIGGER FOLDER
                // ****************************UPDATE A DLL COMPONENT IN FILE IN FOLDERS*************************
                if (skeletonMessage.Properties[Configuration.MessageDataProperty.MessageType.ToString()].ToString()
                    == Configuration.MessageDataProperty.SyncSendComponent.ToString())
                {
                    // EventDataByte = NULL
                    LogEngine.ConsoleWriteLine(
                        $"SyncSendComponent from - {senderId} - {senderDescription}",
                        ConsoleColor.Cyan);
                    var eventBubbling = (BubblingEvent)SerializationEngine.ByteArrayToObject(eventDataByte);
                    SyncProvider.SyncUpdateComponent(
                        skeletonMessage.Properties[Configuration.MessageDataProperty.ChannelId.ToString()].ToString(),
                        skeletonMessage.Properties[Configuration.MessageDataProperty.SenderId.ToString()].ToString(),
                        eventBubbling);
                    return;
                }

                // Request to send the local configuration
                // Send the configuration
                if (skeletonMessage.Properties[Configuration.MessageDataProperty.MessageType.ToString()].ToString()
                    == Configuration.MessageDataProperty.SyncSendRequestBubblingConfiguration.ToString())
                {
                    // EventDataByte = NULL
                    LogEngine.ConsoleWriteLine(
                        $"SyncSendBubblingConfiguration from - {senderId} - {senderDescription}",
                        ConsoleColor.Cyan);
                    SyncProvider.SyncSendBubblingConfiguration(
                        skeletonMessage.Properties[Configuration.MessageDataProperty.ChannelId.ToString()].ToString(),
                        skeletonMessage.Properties[Configuration.MessageDataProperty.SenderId.ToString()].ToString());
                    return;
                }

                // Request to send the  configuration
                // Send the configuration
                if (skeletonMessage.Properties[Configuration.MessageDataProperty.MessageType.ToString()].ToString()
                    == Configuration.MessageDataProperty.SyncSendRequestConfiguration.ToString())
                {
                    // EventDataByte = NULL
                    LogEngine.ConsoleWriteLine(
                        $"SyncSendRequestConfiguration from - {senderId} - {senderDescription}",
                        ConsoleColor.Cyan);

                    SyncProvider.SyncSendConfiguration(skeletonMessage.Properties[Configuration.MessageDataProperty.ChannelId.ToString()].ToString(),
                                                       skeletonMessage.Properties[Configuration.MessageDataProperty.SenderId.ToString()].ToString());


                    return;
                }


                // Request to send back a component
                if (skeletonMessage.Properties[Configuration.MessageDataProperty.MessageType.ToString()].ToString()
                    == Configuration.MessageDataProperty.SyncSendRequestComponent.ToString())
                {
                    // EventDataByte = NULL
                    LogEngine.ConsoleWriteLine(
                        $"SyncSendRequestComponent from - {senderId} - {senderDescription}",
                        ConsoleColor.Cyan);
                    SyncProvider.SyncSendComponent(
                        skeletonMessage.Properties[Configuration.MessageDataProperty.ChannelId.ToString()].ToString(),
                        skeletonMessage.Properties[Configuration.MessageDataProperty.SenderId.ToString()].ToString(),
                        skeletonMessage.Properties[Configuration.MessageDataProperty.IdComponent.ToString()].ToString());
                    return;
                }
            }
            catch (Exception ex)
            {
                LogEngine.WriteLog(Configuration.EngineName,
                                   $"Error in {MethodBase.GetCurrentMethod().Name}",
                                   Constant.ErrorEventIdHighCritical,
                                   Constant.TaskCategoriesError,
                                   ex,
                                   EventLogEntryType.Error);
            }
        }
コード例 #22
0
ファイル: OffRampEngine.cs プロジェクト: debiaggi/GrabCaster
        /// <summary>
        /// Initialize the onramp engine the OffRampPatternComponent variable is for the next version
        /// </summary>
        /// <param name="offRampPatternComponent">
        /// The Off Ramp Pattern Component.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        public static bool Init(string offRampPatternComponent)
        {
            try
            {
                if (Configuration.RunLocalOnly())
                {
                    LogEngine.WriteLog(Configuration.EngineName,
                                       $"This GrabCaster point is configured for local only execution.",
                                       Constant.DefconOne,
                                       Constant.TaskCategoriesError,
                                       null,
                                       EventLogEntryType.Warning);
                    return(true);
                }
                LogEngine.ConsoleWriteLine("Initialize Abstract Event Up Stream Engine.", ConsoleColor.Yellow);

                // Load event up stream external component
                var eventsUpStreamComponent = Path.Combine(
                    Configuration.DirectoryOperativeRootExeName(),
                    Configuration.EventsStreamComponent());

                // Create the reflection method cached
                var assembly = Assembly.LoadFrom(eventsUpStreamComponent);

                // Main class logging
                var assemblyClass = (from t in assembly.GetTypes()
                                     let attributes = t.GetCustomAttributes(typeof(EventsUpStreamContract), true)
                                                      where t.IsClass && attributes != null && attributes.Length > 0
                                                      select t).First();

                var classAttributes = assemblyClass.GetCustomAttributes(typeof(EventsUpStreamContract), true);

                if (classAttributes.Length > 0)
                {
                    Debug.WriteLine("EventsUpStreamContract - methodCreateEventUpStream caller");
                    methodCreateEventUpStream = assemblyClass.GetMethod("CreateEventUpStream");
                    Debug.WriteLine("EventsUpStreamContract - methodSendMessage caller");
                    methodSendMessage = assemblyClass.GetMethod("SendMessage");
                }

                classInstance = Activator.CreateInstance(assemblyClass, null);

                offRampEngine = new OffRampEngine(
                    Configuration.ThrottlingOffRampIncomingRateNumber(),
                    Configuration.ThrottlingOffRampIncomingRateSeconds());
                offRampEngine.OnPublish += OffRampEngineOnPublish;

                LogEngine.WriteLog(
                    Configuration.EngineName,
                    "Start Off Ramp Engine.",
                    Constant.DefconOne,
                    Constant.TaskCategoriesError,
                    null,
                    EventLogEntryType.Information);

                // Inizialize the Dpp
                LogEngine.ConsoleWriteLine("Initialize Abstract Storage Provider Engine.", ConsoleColor.Yellow);
                methodCreateEventUpStream.Invoke(classInstance, null);

                secondaryPersistProviderEnabled  = Configuration.SecondaryPersistProviderEnabled();
                secondaryPersistProviderByteSize = Configuration.SecondaryPersistProviderByteSize();

                // Load the abrstracte persistent provider
                var devicePersistentProviderComponent = Path.Combine(
                    Configuration.DirectoryOperativeRootExeName(),
                    Configuration.PersistentProviderComponent());

                // Create the reflection method cached
                var assemblyPersist = Assembly.LoadFrom(devicePersistentProviderComponent);

                // Main class logging
                var assemblyClassDpp = (from t in assemblyPersist.GetTypes()
                                        let attributes = t.GetCustomAttributes(typeof(DevicePersistentProviderContract), true)
                                                         where t.IsClass && attributes != null && attributes.Length > 0
                                                         select t).First();

                var classAttributeDpp = assemblyClassDpp.GetCustomAttributes(typeof(DevicePersistentProviderContract), true);

                if (classAttributeDpp.Length > 0)
                {
                    Debug.WriteLine("DevicePersistentProviderContract - methodPersistEvent caller");
                    methodPersistEventToBlob = assemblyClassDpp.GetMethod("PersistEventToStorage");
                }

                classInstanceDpp = Activator.CreateInstance(assemblyClassDpp, null);

                return(true);
            }
            catch (Exception ex)
            {
                LogEngine.WriteLog(
                    Configuration.EngineName,
                    $"Error in {MethodBase.GetCurrentMethod().Name}",
                    Constant.DefconOne,
                    Constant.TaskCategoriesError,
                    ex,
                    EventLogEntryType.Error);
                return(false);
            }
        }
コード例 #23
0
ファイル: OffRampEngine.cs プロジェクト: debiaggi/GrabCaster
        /// <summary>
        /// Send a message service as Sync received or sync available in json format
        ///     e un messaggio di servizio, tipo, sync disponibile eccetera, non e importantissimo
        /// </summary>
        /// <param name="ehMessageType">
        /// The EH Message Type.
        /// </param>
        /// <param name="channelId">
        /// The Channel ID.
        /// </param>
        /// <param name="pointId">
        /// The Point ID.
        /// </param>
        /// <param name="idComponent">
        /// The ID Component.
        /// </param>
        /// <param name="subscriberId">
        /// The subscriber ID.
        /// </param>
        public static void SendNullMessageOnRamp(
            Configuration.MessageDataProperty ehMessageType,
            string channelId,
            string pointId,
            string idComponent,
            string subscriberId,
            string pointIdOverrided)
        {
            try
            {
                if (Configuration.RunLocalOnly())
                {
                    LogEngine.WriteLog(Configuration.EngineName,
                                       $"Impossible to send the message using a remote message storage provider, this GrabCaster point is configured for local only execution.",
                                       Constant.DefconOne,
                                       Constant.TaskCategoriesError,
                                       null,
                                       EventLogEntryType.Warning);
                    return;
                }

                // Meter and measuring purpose
                var stopWatch = new Stopwatch();
                stopWatch.Start();
                var data = new SkeletonMessage(Encoding.UTF8.GetBytes(string.Empty));
                data.Properties.Add(Configuration.MessageDataProperty.Persisting.ToString(), false);

                // Set main security subscription
                data.Properties.Add(Configuration.GrabCasterMessageTypeName, Configuration.GrabCasterMessageTypeValue);

                data.Properties.Add(Configuration.MessageDataProperty.MessageId.ToString(), Guid.NewGuid().ToString());
                data.Properties.Add(
                    Configuration.MessageDataProperty.Message.ToString(),
                    Configuration.MessageDataProperty.Message.ToString());
                data.Properties.Add(Configuration.MessageDataProperty.SubscriberId.ToString(), subscriberId);
                data.Properties.Add(Configuration.MessageDataProperty.MessageType.ToString(), ehMessageType.ToString());

                string senderid = pointIdOverrided != null ? pointIdOverrided : Configuration.PointId();
                data.Properties.Add(Configuration.MessageDataProperty.SenderId.ToString(), senderid);
                data.Properties.Add(Configuration.MessageDataProperty.SenderName.ToString(), Configuration.PointName());
                data.Properties.Add(
                    Configuration.MessageDataProperty.SenderDescriprion.ToString(),
                    Configuration.PointDescription());
                data.Properties.Add(Configuration.MessageDataProperty.ChannelId.ToString(), Configuration.ChannelId());
                data.Properties.Add(
                    Configuration.MessageDataProperty.ChannelName.ToString(),
                    Configuration.ChannelName());
                data.Properties.Add(
                    Configuration.MessageDataProperty.ChannelDescription.ToString(),
                    Configuration.ChannelDescription());
                data.Properties.Add(Configuration.MessageDataProperty.ReceiverChannelId.ToString(), channelId);
                data.Properties.Add(Configuration.MessageDataProperty.ReceiverPointId.ToString(), pointId);
                data.Properties.Add(Configuration.MessageDataProperty.IdComponent.ToString(), idComponent);

                stopWatch.Stop();
                var ts = stopWatch.Elapsed;
                data.Properties.Add(Configuration.MessageDataProperty.OperationTime.ToString(), ts.Milliseconds);

                // Queue the data
                lock (offRampEngine)
                {
                    offRampEngine.Enqueue(data);
                }

                LogEngine.ConsoleWriteLine(
                    $"Sent Message Type: {ehMessageType} - To ChannelID: {channelId} PointID: {pointId}",
                    ConsoleColor.DarkMagenta);
            }
            catch (Exception ex)
            {
                LogEngine.WriteLog(
                    Configuration.EngineName,
                    $"Error in {MethodBase.GetCurrentMethod().Name}",
                    Constant.DefconOne,
                    Constant.TaskCategoriesEventHubs,
                    ex,
                    EventLogEntryType.Error);
            }
        }
コード例 #24
0
        private static void ReceiveDirectFromPartition(
            EventHubClient eventHubClient,
            string partitionId,
            string consumerGroup)
        {
            try
            {
                var group = eventHubClient.GetConsumerGroup(consumerGroup);

                var eventHubsStartingDateTimeReceiving =
                    DateTime.Parse(
                        Configuration.EventHubsStartingDateTimeReceiving() == "0"
                        // ReSharper disable once SpecifyACultureInStringConversionExplicitly
                            ? DateTime.UtcNow.ToString()
                            : Configuration.EventHubsStartingDateTimeReceiving());
                var eventHubsEpoch = Configuration.EventHubsEpoch();

                EventHubReceiver receiver = null;

                switch (Configuration.EventHubsCheckPointPattern())
                {
                case EventHubsCheckPointPattern.CheckPoint:
                    //Receiving from the last valid receiving point
                    receiver = group.CreateReceiver(partitionId, DateTime.UtcNow);
                    break;

                case EventHubsCheckPointPattern.Dt:

                    receiver = group.CreateReceiver(partitionId, eventHubsStartingDateTimeReceiving);
                    break;

                case EventHubsCheckPointPattern.Dtepoch:
                    receiver = group.CreateReceiver(partitionId, eventHubsStartingDateTimeReceiving, eventHubsEpoch);
                    break;

                case EventHubsCheckPointPattern.Dtutcnow:
                    receiver = group.CreateReceiver(partitionId, DateTime.UtcNow);
                    break;

                case EventHubsCheckPointPattern.Dtnow:
                    receiver = group.CreateReceiver(partitionId, DateTime.Now);
                    break;

                case EventHubsCheckPointPattern.Dtutcnowepoch:
                    receiver = group.CreateReceiver(partitionId, DateTime.UtcNow, eventHubsEpoch);
                    break;

                case EventHubsCheckPointPattern.Dtnowepoch:
                    receiver = group.CreateReceiver(partitionId, DateTime.Now, eventHubsEpoch);
                    break;
                }
                LogEngine.ConsoleWriteLine(
                    $"Direct Receiver created. Partition {partitionId}",
                    ConsoleColor.Yellow);
                while (true)
                {
                    var message = receiver?.Receive();
                    if (message != null)
                    {
                        SkeletonMessage skeletonMessage = SkeletonMessage.DeserializeMessage(message.GetBytes());
                        SetEventOnRampMessageReceived(skeletonMessage);
                    }
                }
            }
            catch (Exception ex)
            {
                LogEngine.WriteLog(
                    Configuration.EngineName,
                    $"Error in {MethodBase.GetCurrentMethod().Name}",
                    Constant.DefconOne,
                    Constant.TaskCategoriesError,
                    ex,
                    EventLogEntryType.Error);
            }
        }