/// <summary> /// Load the bubbling settings /// </summary> public static void InitializeOffRampEmbedded(ActionEvent delegateEmbedded) { //Load Configuration ConfigurationBag.LoadConfiguration(); LogEngine.WriteLog(ConfigurationBag.EngineName, "Inizialize Off Ramp embedded messaging.", Constant.LogLevelError, Constant.TaskCategoriesError, null, Constant.LogLevelInformation); //Solve App domain environment var current = AppDomain.CurrentDomain; current.AssemblyResolve += HandleAssemblyResolve; int triggers = 0; int events = 0; int components = 0; EventsEngine.InitializeTriggerEngine(); EventsEngine.InitializeEmbeddedEvent(delegateEmbedded); //Load component list configuration EventsEngine.LoadAssemblyComponents(ref triggers, ref events, ref components); //Load event list configuration EventsEngine.RefreshBubblingSetting(false); }
/// <summary> /// Initialize log. /// </summary> /// <returns> /// The <see cref="bool" />. /// </returns> public bool InitLog() { Directory.CreateDirectory(ConfigurationBag.DirectoryLog()); PathFile = Path.Combine(ConfigurationBag.DirectoryLog(), $"{DateTime.Now.Month}{DateTime.Now.Day}{DateTime.Now.Year}-{Guid.NewGuid()}.txt"); logFile = System.IO.File.AppendText(PathFile); return(true); }
public static void StartEngine() { try { ConfigurationBag.LoadConfiguration(); LogEngine.Init(); Debug.WriteLine( $"Version {Assembly.GetExecutingAssembly().GetName().Version}", ConsoleColor.Green); Debug.WriteLine("--GrabCaster Sevice Initialization--Start Engine.", ConsoleColor.Green); _delegate = delegateActionEventEmbedded; CoreEngine.StartEventEngine(_delegate); engineLoaded = true; Thread.Sleep(Timeout.Infinite); } catch (NotImplementedException ex) { LogEngine.WriteLog( ConfigurationBag.EngineName, "Error in " + MethodBase.GetCurrentMethod().Name, Constant.LogLevelError, Constant.TaskCategoriesError, ex, Constant.LogLevelError); } catch (Exception ex) { LogEngine.WriteLog( ConfigurationBag.EngineName, "Error in " + MethodBase.GetCurrentMethod().Name, Constant.LogLevelError, Constant.TaskCategoriesError, ex, Constant.LogLevelError); 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()); } } }
//http://localhost:8000/GrabCaster/Deploy?Configuration=Release&Platform=AnyCpu public string Deploy(string configuration, string platform) { try { string publishingFolder = Path.Combine(ConfigurationBag.DirectoryDeployment(), ConfigurationBag.DirectoryNamePublishing); var regTriggers = new Regex(ConfigurationBag.DeployExtensionLookFor); var deployFiles = Directory.GetFiles(publishingFolder, "*.*", SearchOption.AllDirectories) .Where( path => Path.GetExtension(path) == ".trigger" || Path.GetExtension(path) == ".event" || Path.GetExtension(path) == ".component"); StringBuilder results = new StringBuilder(); foreach (var file in deployFiles) { string projectName = Path.GetFileNameWithoutExtension(publishingFolder + file); string projectType = Path.GetExtension(publishingFolder + file).Replace(".", ""); bool resultOk = Jit.CompilePublishing(projectType, projectName, configuration, platform); if (resultOk) { string message = resultOk ? "without errors" : "with errors"; results.AppendLine( $"{projectName}.{projectType} builded {message} check the {projectName}Build.Log file for more information"); } } return(results.ToString()); } catch (Exception ex) { LogEngine.WriteLog( ConfigurationBag.EngineName, $"Error in {MethodBase.GetCurrentMethod().Name}", Constant.LogLevelError, Constant.TaskCategoriesError, ex, Constant.LogLevelError); return(ex.Message); } }
static void Main(string[] args) { string publishingFolder = Path.Combine(ConfigurationBag.DirectoryDeployment(), ConfigurationBag.DirectoryNamePublishing); var regTriggers = new Regex(ConfigurationBag.DeployExtensionLookFor); var deployFiles = Directory.GetFiles(publishingFolder, "*.*", SearchOption.AllDirectories) .Where( path => Path.GetExtension(path) == ".trigger" || Path.GetExtension(path) == ".event" || Path.GetExtension(path) == ".component"); foreach (var file in deployFiles) { string projectName = Path.GetFileNameWithoutExtension(publishingFolder + file); string projectType = Path.GetExtension(publishingFolder + file).Replace(".", ""); Jit.CompilePublishing(projectType, projectName, "Release", "AnyCpu"); } }
public static void Init() { try { ConfigurationBag.LoadConfiguration(); Enabled = ConfigurationBag.Configuration.LoggingEngineEnabled; //Load logging external component var loggingComponent = Path.Combine( ConfigurationBag.Configuration.DirectoryOperativeRootExeName, ConfigurationBag.Configuration.LoggingComponent); Debug.WriteLine("Check Abstract Logging Engine."); //Create the reflection method cached var assembly = Assembly.LoadFrom(loggingComponent); //Main class logging var assemblyClass = (from t in assembly.GetTypes() let attributes = t.GetCustomAttributes(typeof(LogContract), true) where t.IsClass && attributes != null && attributes.Length > 0 select t).First(); LogEngineComponent = Activator.CreateInstance(assemblyClass) as ILogEngine; Debug.WriteLine("LogEventUpStream - Inizialize the external log"); LogEngineComponent.InitLog(); Debug.WriteLine("Initialize Abstract Logging Engine."); Debug.WriteLine("LogEventUpStream - CreateEventSource if not exist"); if (!EventLog.SourceExists(EventViewerSource)) { EventLog.CreateEventSource(EventViewerSource, EventViewerLog); } //Create the QueueConsoleMessage internal queue Debug.WriteLine( "LogEventUpStream - logQueueConsoleMessage.OnPublish += LogQueueConsoleMessageOnPublish"); QueueConsoleMessage = new LogQueueConsoleMessage( ConfigurationBag.Configuration.ThrottlingConsoleLogIncomingRateNumber, ConfigurationBag.Configuration.ThrottlingConsoleLogIncomingRateSeconds); QueueConsoleMessage.OnPublish += QueueConsoleMessageOnPublish; //Create the QueueAbstractMessage internal queue Debug.WriteLine( "LogEventUpStream - logQueueAbstractMessage.OnPublish += LogQueueAbstractMessageOnPublish"); QueueAbstractMessage = new LogQueueAbstractMessage( ConfigurationBag.Configuration.ThrottlingLsiLogIncomingRateNumber, ConfigurationBag.Configuration.ThrottlingLsiLogIncomingRateSeconds); QueueAbstractMessage.OnPublish += QueueAbstractMessageOnPublish; Debug.WriteLine("LogEventUpStream - Log Queues initialized."); } catch (Exception ex) { DirectEventViewerLog($"Error in {MethodBase.GetCurrentMethod().Name} - {ex.Message}", 1); WriteLog( ConfigurationBag.EngineName, $"Error in {MethodBase.GetCurrentMethod().Name}", Constant.LogLevelError, Constant.TaskCategoriesError, ex, Constant.LogLevelError); Environment.Exit(0); } }
public static bool CompilePublishing(string projectExtension, string projectName, string configurationBuild, string platform) { try { string projectType = ""; switch (projectExtension.ToLower()) { case "trigger": projectType = "Trigger"; break; case "event": projectType = "Event"; break; case "component": projectType = "Component"; break; } string projectTtypeName = $"GrabCaster{projectType}"; string sourcePublishing = Path.Combine(ConfigurationBag.DirectoryDeployment(), "Publishing"); string sourceTemplate = Path.Combine(ConfigurationBag.DirectoryDeployment(), projectTtypeName); string destinationPath = Path.Combine(ConfigurationBag.DirectoryDeployment(), $"Temp\\{Guid.NewGuid()}"); //Create the new project //Create all of the directories foreach (string dirPath in Directory.GetDirectories(sourceTemplate, "*", SearchOption.AllDirectories)) { Directory.CreateDirectory(dirPath.Replace(sourceTemplate, destinationPath)); } //Copy all the files & Replaces any files with the same name foreach (string newPath in Directory.GetFiles(sourceTemplate, "*.*", SearchOption.AllDirectories)) { File.Copy(newPath, newPath.Replace(sourceTemplate, destinationPath), true); } //Copy all the files required from Publishing to the new project Configuration folder //Create all of the directories foreach (string dirPath in Directory.GetDirectories(sourcePublishing, "*", SearchOption.AllDirectories)) { Directory.CreateDirectory(dirPath.Replace(sourcePublishing, destinationPath + $"\\bin\\{configurationBuild}")); } //Copy all the files & Replaces any files with the same name foreach (string newPath in Directory.GetFiles(sourcePublishing, "*.*", SearchOption.AllDirectories)) { File.Copy(newPath, newPath.Replace(sourcePublishing, destinationPath + $"\\bin\\{configurationBuild}"), true); } string solutionFile = Path.Combine(destinationPath, projectName + ".sln"); string projectFile = Path.Combine(destinationPath, projectName + ".csproj"); string classFile = Path.Combine(destinationPath, projectName + ".cs"); string assemblyInfoFile = Path.Combine(destinationPath, "Properties\\AssemblyInfo.cs"); //Rename the solution file File.Move(Path.Combine(destinationPath, projectTtypeName + ".sln"), solutionFile); //Rename the project file File.Move(Path.Combine(destinationPath, projectTtypeName + ".csproj"), projectFile); //Rename the class file File.Move(Path.Combine(destinationPath, projectTtypeName + ".cs"), classFile); //Get using, code and dll string textBag = File.ReadAllText(Path.Combine(sourcePublishing, projectName + $".{projectExtension}")); //Get Dll to add as reference var dllsReference = Directory.GetFiles(destinationPath + $"\\bin\\{configurationBuild}", "*.*", SearchOption.AllDirectories) .Where( path => Path.GetExtension(path) == ".dll" && !Path.GetFileName(path).Contains("GrabCaster.Framework")); string dllTextReference = "<Reference Include=\"FULLNAME, processorArchitecture=MSIL\">\r" + "<SpecificVersion>False</SpecificVersion>\r" + $"<HintPath>bin\\{configurationBuild}\\DLLNAME </HintPath>\r" + "</Reference>\r"; StringBuilder sbDlls = new StringBuilder(); foreach (var dllReference in dllsReference) { Assembly assembly = Assembly.LoadFrom(dllReference); sbDlls.AppendLine(dllTextReference.Replace("FULLNAME", assembly.FullName) .Replace("DLLNAME", Path.GetFileName(assembly.Location))); } //Rename markup in solution file string textSln = File.ReadAllText(solutionFile); textSln = textSln.Replace(projectTtypeName, projectName); File.WriteAllText(solutionFile, textSln); //Rename markup in project file string textProj = File.ReadAllText(projectFile); textProj = textProj.Replace(projectTtypeName, projectName); textProj = textProj.Replace("<!--DLL-->", sbDlls.ToString()); textProj = textProj.Replace("*CONFIGURATION*", configurationBuild); textProj = textProj.Replace("*PLATFORM*", platform); File.WriteAllText(projectFile, textProj); //Rename markup in class file string textCs = File.ReadAllText(classFile); textCs = textCs.Replace(projectTtypeName, projectName); string componentId = Guid.NewGuid().ToString(); //TriggerID textCs = textCs.Replace("*ID*", componentId); //ContractID textCs = textCs.Replace("*CONTRACTID*", Guid.NewGuid().ToString()); //Name textCs = textCs.Replace("*NAME*", projectName); //Description textCs = textCs.Replace("*DESCRIPTION*", $"{projectName} {projectType} component"); //using var textUsing = Regex.Matches(textBag, "<USING>(.*?)</USING>", RegexOptions.Multiline | RegexOptions.Singleline)[0] .Value.Replace("<USING>", "").Replace("</USING>", ""); textCs = textCs.Replace("//<USING>", textUsing); //Code var textCode = Regex.Matches(textBag, "<MAINCODE>(.*?)</MAINCODE>", RegexOptions.Multiline | RegexOptions.Singleline)[0].Value.Replace("<MAINCODE>", "") .Replace("</MAINCODE>", ""); //Properties var textCodeLines = Regex.Matches(textBag, "<MAINCODE>(.*?)</MAINCODE>", RegexOptions.Multiline | RegexOptions.Singleline)[0].Value.Replace("<MAINCODE>", "") .Replace("</MAINCODE>", "") .Split('\r'); string functionName = ""; string innerArgs = ""; //look the function name foreach (var textCodeLine in textCodeLines) { var func = Regex.Match(textCodeLine, @"\b[^()]+\((.*)\)$"); if (func.Success) { functionName = func.Value; innerArgs = func.Groups[1].Value; break; } } //remove the func name from the code textCode = textCode.Replace(functionName, ""); //Remove the first and last brachet int brachet = textCode.IndexOf("{") + 1; textCode = textCode.Substring(brachet, textCode.Length - brachet); textCode = textCode.Substring(0, textCode.LastIndexOf("}") - 1); textCs = textCs.Replace("//<MAINCODE>", textCode); // Get parameters var paramTags = Regex.Matches(innerArgs, @"([^,]+\(.+?\))|([^,]+)"); StringBuilder sbParamsComponent = new StringBuilder(); StringBuilder sbParamsConfiguration = new StringBuilder(); sbParamsComponent.AppendLine(""); foreach (var item in paramTags) { string[] param = item.ToString().Split(' '); sbParamsComponent.AppendLine( $"\t\t[{projectType}PropertyContract(\"{param[1]}\", \"{param[1]} property\")]"); sbParamsComponent.AppendLine("\t\tpublic " + item + " { get; set; }"); sbParamsConfiguration.AppendLine("\t\t{"); sbParamsConfiguration.AppendLine($"\t\t\"Name\": \"{param[1]}\","); sbParamsConfiguration.AppendLine("\t\t\"Value\": \"\""); sbParamsConfiguration.AppendLine("\t\t},"); } textCs = textCs.Replace("//<PROPERTIES>", sbParamsComponent.ToString()); //functions string textFunctions = Regex.Matches(textBag, "<FUNCTIONS>(.*?)</FUNCTIONS>", RegexOptions.Multiline | RegexOptions.Singleline)[0].Value.Replace("<FUNCTIONS>", "") .Replace("</FUNCTIONS>", ""); textCs = textCs.Replace("//<FUNCTIONS>", textFunctions); File.WriteAllText(classFile, textCs); //Rename markup in project file string textInfo = File.ReadAllText(assemblyInfoFile); textInfo = textInfo.Replace(projectTtypeName, projectName); File.WriteAllText(assemblyInfoFile, textInfo); //Create the Configuration file var configurationFiles = Directory.GetFiles(destinationPath, "*.*", SearchOption.AllDirectories) .Where( path => Path.GetExtension(path) == ".off" || Path.GetExtension(path) == ".cmp" || Path.GetExtension(path) == ".evn"); foreach (var file in configurationFiles) { string configurationFile = file.Replace(projectTtypeName, projectName); File.Move(file, configurationFile.Replace(projectTtypeName, projectName)); string textJson = File.ReadAllText(configurationFile); string configurationProperties = sbParamsConfiguration.ToString(); configurationProperties = configurationProperties.Substring(0, configurationProperties.LastIndexOf(",")); textJson = textJson.Replace("//<PROPERTIES>", configurationProperties); textJson = textJson.Replace("*ID*", componentId); textJson = textJson.Replace("*IDCONFIGURATION*", Guid.NewGuid().ToString()); //Name textJson = textJson.Replace("*NAME*", $"{projectName} {projectType} configuration"); //Description textJson = textJson.Replace("*DESCRIPTION*", $"{projectName} {projectType} configuration"); File.WriteAllText(configurationFile, textJson); } //Build the project bool resultOk = Build(projectFile, sourcePublishing, projectName, configurationBuild, platform); //Copy the {Configuration} into the component if (resultOk) { string folderConfigurationFile = ""; string folderdllFile = ""; switch (projectExtension.ToLower()) { case "trigger": folderdllFile = ConfigurationBag.DirectoryTriggers(); folderConfigurationFile = ConfigurationBag.DirectoryBubblingTriggers(); break; case "event": folderdllFile = ConfigurationBag.DirectoryEvents(); folderConfigurationFile = ConfigurationBag.DirectoryBubblingEvents(); break; case "component": folderdllFile = ConfigurationBag.DirectoryComponents(); folderConfigurationFile = ConfigurationBag.DirectoryBubblingComponents(); break; default: break; } //Copy the dll string source = Path.Combine(destinationPath, $"bin\\{configurationBuild}\\{projectName}.{projectType}.dll"); string destinationDll = Path.Combine(folderdllFile, $"{projectName}.{projectType}.dll"); File.Copy(source, destinationDll, true); var configurationFilesNew = Directory.GetFiles(destinationPath, "*.*", SearchOption.AllDirectories) .Where( path => Path.GetExtension(path) == ".off" || Path.GetExtension(path) == ".cmp" || Path.GetExtension(path) == ".evn"); //Copy the configuration files foreach (var configurationFile in configurationFilesNew) { File.Copy(configurationFile, Path.Combine(folderConfigurationFile, Path.GetFileName(configurationFile)), true); } } return(resultOk); } catch (Exception ex) { LogEngine.WriteLog(ConfigurationBag.EngineName, "Configuration.WebApiEndPoint key empty, internal Web Api interface disable", Constant.LogLevelError, Constant.TaskCategoriesError, ex, Constant.LogLevelWarning); return(false); } }
public static void IngestMessagge(BubblingObject bubblingObject) { try { LogEngine.WriteLog(ConfigurationBag.EngineName, $"IngestMessagge bubblingObject.SenderChannelId {bubblingObject.SenderChannelId} " + $"bubblingObject.SenderPointId {bubblingObject.SenderPointId} " + $"bubblingObject.DestinationChannelId {bubblingObject.DestinationChannelId} " + $" bubblingObject.DestinationPointId {bubblingObject.DestinationPointId} " + $"bubblingObject.MessageType {bubblingObject.MessageType}" + $"bubblingObject.Persisting {bubblingObject.Persisting} " + $"bubblingObject.MessageId {bubblingObject.MessageId} " + $"bubblingObject.Name {bubblingObject.Name}", Constant.LogLevelError, Constant.TaskCategoriesConsole, null, Constant.LogLevelVerbose); //If local event then execute if (bubblingObject.LocalEvent) { //new Task(() => //{ // EventsEngine.ExecuteEventsInTrigger( // bubblingObject, // bubblingObject.Events[0], // false, // bubblingObject.SenderPointId); //}).Start(); EventsEngine.ExecuteEventsInTrigger( bubblingObject, bubblingObject.Events[0], false, bubblingObject.SenderPointId); return; } //Check if message is for this point var receiverChannelId = bubblingObject.DestinationChannelId; var receiverPointId = bubblingObject.DestinationPointId; var requestAvailable = (receiverChannelId == ConfigurationBag.Configuration.ChannelId && receiverPointId == ConfigurationBag.Configuration.PointId) || (receiverChannelId == ConfigurationBag.ChannelAll && receiverPointId == ConfigurationBag.Configuration.PointId) || (receiverChannelId == ConfigurationBag.Configuration.ChannelId && receiverPointId == ConfigurationBag.PointAll) || (receiverChannelId == ConfigurationBag.ChannelAll && receiverPointId == ConfigurationBag.PointAll); if (!requestAvailable) { // ****************************NOT FOR ME************************* return; } if (bubblingObject.SenderPointId == ConfigurationBag.Configuration.PointId) { // **************************** HA AREA ************************* if (bubblingObject.MessageType == "HA" && bubblingObject.HAGroup == ConfigurationBag.Configuration.HAGroup && EventsEngine.HAEnabled) { //If HA group member and HA EventsEngine.HAPoints[EventsEngine.HAPointTickId] = DateTime.Now; long haTickFrom = long.Parse(UTF8Encoding.UTF8.GetString(bubblingObject.Data)); //if same tick then return because same point if (haTickFrom == EventsEngine.HAPointTickId) { return; } DateTime dt; lock (EventsEngine.HAPoints) { //If not exist then add if (!EventsEngine.HAPoints.TryGetValue(haTickFrom, out dt)) { EventsEngine.HAPoints.Add(haTickFrom, DateTime.Now); } else { EventsEngine.HAPoints[haTickFrom] = DateTime.Now; } } byte[] content = UTF8Encoding.UTF8.GetBytes(EventsEngine.HAPointTickId.ToString()); BubblingObject bubblingObjectToSync = new BubblingObject(content); bubblingObject.MessageType = "HA"; OffRampEngineSending.SendMessageOffRamp(bubblingObjectToSync, "HA", bubblingObject.SenderChannelId, bubblingObject.SenderPointId, string.Empty); } else { return; } } // ****************************GET FROM STORAGE IF REQUIRED************************* if (bubblingObject.Persisting) { bubblingObject = (BubblingObject) SerializationEngine.ByteArrayToObject( DevicePersistentProvider.PersistEventFromStorage(bubblingObject.MessageId)); } #region EVENT // ****************************IF EVENT TYPE************************* if (bubblingObject.MessageType == "Event") { //If HA group member and HA if (EventsEngine.HAEnabled) { //Check if is the first in list, if not then discard EventsEngine.HAPoints.OrderBy(key => key.Key); if (EventsEngine.HAPoints.Count > 1 && EventsEngine.HAPoints.First().Key != EventsEngine.HAPointTickId) { return; } } //Check if is Syncronouse response if (bubblingObject.SyncronousFromEvent && bubblingObject.SenderPointId == ConfigurationBag.Configuration.PointId) { //Yes it's a syncronous response from my request from this pointid //Execute the delegate and exit var propDataContext = bubblingObject.DataContext; bubblingObject.SyncronousFromEvent = false; EventsEngine.SyncAsyncEventsExecuteDelegate(bubblingObject.SyncronousToken, propDataContext); bubblingObject.SenderPointId = ""; bubblingObject.SyncronousToken = ""; return; } // ****************************EVENT EXIST EXECUTE************************* EventsEngine.ExecuteEventsInTrigger( bubblingObject, bubblingObject.Events[0], false, bubblingObject.SenderPointId); return; } #endregion #region CONSOLE // **************************** SYNC AREA ************************* //******************* OPERATION CONF BAG- ALL THE CONF FILES AND DLLS **************************************************************** //Receive a package folder to syncronize him self if (bubblingObject.MessageType == "SyncPull") { byte[] content = Helpers.CreateFromDirectory( ConfigurationBag.Configuration.DirectoryOperativeRootExeName); BubblingObject bubblingObjectToSync = new BubblingObject(content); bubblingObject.MessageType = "SyncPush"; OffRampEngineSending.SendMessageOffRamp(bubblingObjectToSync, "SyncPush", bubblingObject.SenderChannelId, bubblingObject.SenderPointId, string.Empty); } //Receive the request to send the bubbling if (bubblingObject.MessageType == "SyncPush") { LogEngine.DirectEventViewerLog( $"Received a syncronization package from channel ID {bubblingObject.SenderChannelId} and point ID {bubblingObject.SenderChannelId}\rAutoSyncronizationEnabled parameter = {ConfigurationBag.Configuration.AutoSyncronizationEnabled}", 2); if (ConfigurationBag.Configuration.AutoSyncronizationEnabled) { byte[] bubblingContent = SerializationEngine.ObjectToByteArray(bubblingObject.Data); string currentSyncFolder = ConfigurationBag.SyncDirectorySyncIn(); Helpers.CreateFromBytearray(bubblingObject.Data, currentSyncFolder); } } #endregion } catch (Exception ex) { LogEngine.WriteLog(ConfigurationBag.EngineName, $"Error in {MethodBase.GetCurrentMethod().Name}", Constant.LogLevelError, Constant.TaskCategoriesError, ex, Constant.LogLevelError); } }