Exemplo n.º 1
0
        /// <summary>
        /// Make a deep clone of the Message
        /// </summary>
        /// <param name="tMsg">Mesage to be cloned</param>
        /// <param name="DoClonePLB">If set to True, the PLB parameter will be block-copied, too</param>
        /// <returns></returns>
        public static TSM Clone(TSM tMsg, bool DoClonePLB)
        {
            TSM tRes = new TSM(tMsg.SID)    //Save not to set ORG or SID for fast cloning
            {
                TXT  = tMsg.TXT,
                TIM  = tMsg.TIM,
                FLG  = tMsg.FLG,
                ORG  = tMsg.ORG,//ORG-OK
                QDX  = tMsg.QDX,
                LVL  = tMsg.LVL,
                ENG  = tMsg.ENG,
                FID  = tMsg.FID,
                SEID = tMsg.SEID,
                CST  = tMsg.CST,
                UID  = tMsg.UID,
                PLS  = tMsg.PLS,
                OWN  = tMsg.OWN
            };

            if (DoClonePLB && tMsg.PLB != null && tMsg.PLB.Length > 0)
            {
                tRes.PLB = new byte[tMsg.PLB.Length];
                TheCommonUtils.cdeBlockCopy(tMsg.PLB, 0, tRes.PLB, 0, tMsg.PLB.Length);
            }
            return(tRes);
        }
Exemplo n.º 2
0
 /// <summary>
 /// Used to show an Alert. Override to plugin your own custom alert handler
 /// </summary>
 /// <param name="pMsg">Message with the Alert</param>
 /// <param name="pTargetScreen">A TheBaseAssets.MyDashboards ScreenName to jump to</param>
 public virtual void ShowMessageToast(TSM pMsg, string pTargetScreen)
 {
     if (MyMainPage != null)
     {
         MyMainPage.ShowMessageToast(pMsg, pTargetScreen);
     }
 }
Exemplo n.º 3
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="engine"></param>
        /// <returns></returns>
        private static ResourceManager GetStringResourceManager(string engine)
        {
            ResourceManager rm = null;

            if (!string.IsNullOrEmpty(engine) && ResourceManagersPerEngine.TryGetValue(engine, out rm))
            {
                return(rm);
            }
            if (string.IsNullOrEmpty(engine) || !TheBaseAssets.MyCDEPluginTypes.TryGetValue(engine, out Type plugInType))
            {
                engine = "cdeEngine";
                if (ResourceManagersPerEngine.TryGetValue(engine, out rm))
                {
                    return(rm);
                }
                plugInType = typeof(TheCommonUtils);
            }
            try
            {
                rm = new ResourceManager("cdeStrings", plugInType.Assembly);
            }
            catch (Exception ex)
            {
                TheBaseAssets.MySYSLOG.WriteToLog(1, TSM.L(eDEBUG_LEVELS.OFF)
                    ? null
                    : new TSM(eEngineName.NMIService, "Error creating resource manager", eMsgLevel.l2_Warning, $"cdeStrings, {plugInType.Name}: {ex}"));
            }
            if (rm != null)
            {
                ResourceManagersPerEngine.TryAdd(engine, rm);
            }
            return(rm);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Deserializes a JSON string to a TSM
        /// PLB will be ignored
        /// WARNING: this is not used in the C-DEngine and migh
        /// </summary>
        /// <param name="pPayload"></param>
        /// <returns></returns>
        internal static TSM DeserializeJStringToObjectTSM(object pPayload)
        {
            if (pPayload == null)
            {
                return(null);
            }

            TSM tTSM = new TSM();   //Save not to set ORG or SID

            tTSM.SID = "";

            Dictionary <string, object> tdic = pPayload as Dictionary <string, object>;

            if (tdic == null)
            {
                fastJSON.JsonParser tParser = new fastJSON.JsonParser(pPayload.ToString(), false);
                tdic = tParser.Decode() as Dictionary <string, object>;
            }
            if (tdic != null)
            {
                foreach (string key in tdic.Keys)
                {
                    if (tdic[key] != null)
                    {
                        ValSetter2(ref tTSM, key, tdic[key], true);
                    }
                }
            }
            return(tTSM);
        }
Exemplo n.º 5
0
 /// <summary>
 /// Writes to the SystemLog
 /// </summary>
 /// <param name="LogID"></param>
 /// <param name="LogLevel"></param>
 /// <param name="pTopic"></param>
 /// <param name="pSeverity"></param>
 /// <param name="pLogText"></param>
 /// <param name="NoLog"></param>
 public void WriteToLog(eDEBUG_LEVELS LogLevel, int LogID, string pTopic, string pLogText, eMsgLevel pSeverity = eMsgLevel.l4_Message, bool NoLog = false)
 {
     if (TSM.L(LogLevel))
     {
         return;
     }
     WriteToLog(LogID, new TSM(pTopic, pLogText, pSeverity), NoLog);
 }
Exemplo n.º 6
0
 /// <summary>
 /// Writes a TSM to The SystemLog
 /// </summary>
 /// <param name="MyText"></param>
 /// <param name="LogID"></param>
 /// <param name="NoLog"></param>
 public void WriteToLog(TSM MyText, int LogID = 0, bool NoLog = false)
 {
     if (MyText == null)
     {
         return;
     }
     WriteToLog(LogID, MyText, NoLog);
 }
Exemplo n.º 7
0
 public void WriteToLog(int LogID, TSM MyText)
 {
     if (MyText == null)
     {
         return;
     }
     WriteToLog(LogID, MyText, false);
 }
Exemplo n.º 8
0
 public static void WriteLog(int tLogID, TSM MyText, bool NoLog)
 {
     if (TheBaseAssets.MySYSLOG == null)
     {
         return;
     }
     TheBaseAssets.MySYSLOG.WriteToLog(tLogID, MyText, NoLog);
 }
Exemplo n.º 9
0
        /// <summary>
        /// Virtual function that determines if a plugin has the rights to push back to a relay server from the cloud
        /// </summary>
        /// <param name="pMessage">Message to be inspected</param>
        /// <returns>True if the cloud can pushback, False prevents cloud from pushing back</returns>
        public virtual bool IsCloudAllowedToPushBack(TSM pMessage)
        {
            IBaseEngine tBase = TheThingRegistry.GetBaseEngine(pMessage.ENG);

            if (tBase == null || !tBase.GetEngineState().IsLiveEngine)
            {
                return(false);
            }
            else
            {
                return(true);
            }
        }
Exemplo n.º 10
0
 public void WriteToLogSafe(int LogID, eDEBUG_LEVELS logLevel, Func <TSM> createMyText, bool NoLog)
 {
     if (!TSM.L(logLevel))
     {
         TSM text;
         try
         {
             text = createMyText();
         }
         catch (Exception e) { text = new TSM(eEngineName.ContentService, "Error creating log message", eMsgLevel.l2_Warning, e.ToString()); }
         WriteToLog(LogID, text, NoLog);
     }
 }
Exemplo n.º 11
0
 /// <summary>
 /// Decrypts an encrypted string against a given token GUID
 /// </summary>
 /// <param name="pToDecrypt">Encrypted text</param>
 /// <param name="pToken">Guid token</param>
 /// <returns></returns>
 public static string DecryptWithConnToken(string pToDecrypt, Guid pToken)
 {
     try
     {
         return(cdeDecrypt(pToDecrypt, pToken.ToByteArray()));
     }
     catch (Exception e)
     {
         TheBaseAssets.MySYSLOG?.WriteToLog(TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("TheCommonUtils", "Error During EncryptWithConnToken", eMsgLevel.l1_Error)
         {
             PLS = e.ToString()
         }, 5102);
     }
     return(null);
 }
Exemplo n.º 12
0
 internal static void CreateRSAKeys(TheSessionState pSession, bool createXMLKeyAlways = false)
 {
     if (TheBaseAssets.MyServiceHostInfo.DisableRSAToBrowser || pSession == null)
     {
         return; //RSA Not working
     }
     lock (pSession)
     {
         if (string.IsNullOrEmpty(pSession.RSAKey) && pSession.MyRSA == null)
         {
             TheBaseAssets.MySYSLOG?.WriteToLog(TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("SSM", $"CreateRSAKey at {GetDateTimeString(DateTimeOffset.Now)}", eMsgLevel.l6_Debug), 5010, true);
             pSession.MyRSA     = TheBaseAssets.MyCrypto.CreateRSAKeys(out var tRSAKey, out var tRSAPublic, createXMLKeyAlways);
             pSession.RSAKey    = tRSAKey;
             pSession.RSAPublic = tRSAPublic;
             TheBaseAssets.MySYSLOG?.WriteToLog(TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("SSM", $"New Session {pSession.cdeMID} established and RSAKey created at {GetDateTimeString(DateTimeOffset.Now, 0)}", eMsgLevel.l6_Debug), 5011, true);
         }
     }
 }
Exemplo n.º 13
0
        private void Add(int pEventID, long pSerial, string pSource, TSM AMessage)
        {
            TheEventLogEntry tLog = new TheEventLogEntry
            {
                Message = AMessage,
                Serial  = pSerial,
                Source  = string.IsNullOrEmpty(pSource) ? AMessage.ENG : pSource,
                EventID = pEventID
            };

            MyMessageLog.AddAnItem(tLog);
            if (IsEventRegistered("NewLogEntry"))
            {
                FireEvent("NewLogEntry", new TheProcessMessage()
                {
                    Message = AMessage, Cookie = tLog
                }, true);                                                                                       //Prevents a call to AddScopeID for the TOPIC
            }
        }
Exemplo n.º 14
0
        private static void sinkRequestFailed(object state)
        {
            TheDiagnostics.SetThreadName("TimedRequestFailed", true);
            TheTimedRequest <T> req = state as TheTimedRequest <T>;

            if (state != null)
            {
                TheTimedRequest <T> tReq = req;
                lock (MyStoreRequestsLock)
                {
                    if (MyStoreRequests.ContainsKey(tReq.MagicID.ToString()))
                    {
                        TheBaseAssets.MySYSLOG.WriteToLog(472, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("TheTimedCallbacks", "Timed-Request Timed Out", eMsgLevel.l2_Warning));
                        MyStoreRequests.RemoveNoCare(tReq.MagicID.ToString());
                        tReq.MyRequest("Timed-Request Timed Out", (T)tReq.Cookie);
                    }
                }
            }
        }
Exemplo n.º 15
0
 public void WriteToLog(int pLogID, TSM MyText, bool NoLog)
 {
     if (MyText == null)
     {
         return;
     }
     if (!UseSysLogQueue)
     {
         TheCommonUtils.cdeRunAsync(string.Format("WriteLog:{0}", pLogID), false, o =>
         {
             WriteToLogInternal(pLogID, MyText, NoLog, TheCommonUtils.CLng(o));
         }, Interlocked.Increment(ref LogSerial));
     }
     else
     {
         if (!sysLogQueue.TryAdd(new LogArgs {
             pLogID = pLogID, MyText = MyText, NoLog = NoLog, tLogSerial = Interlocked.Increment(ref LogSerial)
         }))
         {
             // queue is full, log entry dropped
         }
     }
 }
Exemplo n.º 16
0
        /// <summary>
        /// Override to initalize the app with custom values but still call the base!
        /// </summary>
        /// <param name="pPlugInLst">List if ICDEPlugin instances</param>
        /// <param name="ArgList">Additional Parameters of the Application</param>
        /// <returns>True if all went well during startup</returns>
        public virtual bool StartBaseApplication2(List <ICDEPlugin> pPlugInLst, IDictionary <string, string> ArgList)
        {
            if (TheBaseAssets.MasterSwitch)
            {
                return(false);                              //SECURITY REVIEW: do not allow to call StartBaseApplication twice
            }
            TheBaseAssets.MasterSwitch = true;
            if (TheBaseAssets.MyServiceHostInfo == null)
            {
                TheBaseAssets.MasterSwitch = false;
                TheSystemMessageLog.ToCo("MyServiceHostInfo is not set! Exiting...");   //Will becalled because if MyServiceHostInfo==null TOCO will be called
                return(false);
            }
            if (TheBaseAssets.CryptoLoadMessage != null)
            {
                TheBaseAssets.MasterSwitch = false;
                TheSystemMessageLog.ToCo($"Security initialization failed with {TheBaseAssets.CryptoLoadMessage}. Exiting...");
                return(false);
            }
            try
            {
                TheBaseAssets.IsStarting = true;

                //AppDomain.CurrentDomain.UnhandledException += MyUnhandledExceptionHandler;

                if (ArgList == null)
                {
                    ArgList = new Dictionary <string, string>();    //DIC-Allowed!
                }
                if (!TheBaseAssets.MySettings.ReadAllAppSettings(ref ArgList))
                {
                    TheSystemMessageLog.ToCo("Not reading app.config: not supported by platform."); //Will never be called!
                }
                if (!TheBaseAssets.MasterSwitch)
                {
                    return(false);
                }
                TheBaseAssets.MyCmdArgs = ArgList; //MyCmdArgs ONLY contains "public" settings coming from app.config or via the host

                MyUserManager = new TheUserManager();
                TheBaseAssets.InitAssets(this);
                if (!TheBaseAssets.MasterSwitch)
                {
                    return(false);
                }
                TheBaseAssets.MyScopeManager.RegisterScopeChanged(EventScopeChanged);
                TheBaseAssets.MySYSLOG.WriteToLog(4140, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("TheBaseApplication", "Assets and SystemLog Initialized", eMsgLevel.l3_ImportantMessage));

                int minWorker = -1, minCompletionPort = -1, maxWorker = -1, maxCompletionPort = -1;
                try
                {
                    System.Threading.ThreadPool.GetMinThreads(out minWorker, out minCompletionPort);
                    System.Threading.ThreadPool.GetMaxThreads(out maxWorker, out maxCompletionPort);
                }
                catch { };

#if CDE_STANDARD
                var largeObjectHeapCompactionMode = System.Runtime.GCSettings.LargeObjectHeapCompactionMode;
#else
                const string largeObjectHeapCompactionMode = "n/a";
#endif
                TheBaseAssets.MySYSLOG.WriteToLog(4144, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(eEngineName.ContentService, $"CLR Info", eMsgLevel.l4_Message, $"Server GC: {System.Runtime.GCSettings.IsServerGC}. GC Latency Mode: {System.Runtime.GCSettings.LatencyMode}. LOHC Mode: {largeObjectHeapCompactionMode}. Bitness: {System.Runtime.InteropServices.Marshal.SizeOf(typeof(IntPtr)) * 8}. Threads Min W/CP, Max W/CP: {minWorker}/{minCompletionPort},{maxWorker}/{maxCompletionPort}. GC TotalMemory: {GC.GetTotalMemory(false)}"));

                if (!TheBaseAssets.MyActivationManager.InitializeLicenses())
                {
                    Shutdown(true);
                    TheBaseAssets.MySYSLOG.WriteToLog(4145, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("TheBaseApplication", "Licensing error", eMsgLevel.l3_ImportantMessage));
                    return(false);
                }

                //4.304: Workitem #2289 - Removed from OSS Release (as CheckLicense is always returning true in the CoreCrypto Lib
                if (!TheBaseAssets.MyActivationManager.CheckLicense(new Guid("{5737240C-AA66-417C-9B66-3919E18F9F4A}"), "", null, 1, false))
                {
                    if (TheBaseAssets.MyServiceHostInfo.ShutdownOnLicenseFailure)
                    {
                        TheBaseAssets.MySYSLOG.WriteToLog(4146, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("TheBaseApplication", "Licensing error: no activated license for Thing Service. Shutting down immediately as configured.", eMsgLevel.l2_Warning));
                        return(false);
                    }
                    else
                    {
                        TheBaseAssets.MySYSLOG.WriteToLog(4147, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("TheBaseApplication", "Licensing error: no activated license for Thing Service. Will shut down in 60 minutes if not activated.", eMsgLevel.l2_Warning));
                        TheCommonUtils.cdeRunAsync("LicenseCheck", true, (o) =>
                        {
                            TheCommonUtils.TaskDelayOneEye(60 * 60 * 1000, 100).ContinueWith((t) =>
                            {
                                if (TheBaseAssets.MasterSwitch)
                                {
                                    if (!TheBaseAssets.MyActivationManager.CheckLicense(new Guid("{5737240C-AA66-417C-9B66-3919E18F9F4A}"), "", null, 1, false))
                                    {
                                        TheBaseAssets.MySYSLOG.WriteToLog(4148, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("TheBaseApplication", "Licensing error: no activated license for Thing Service. Shutting down.", eMsgLevel.l1_Error));
                                        if (TheBaseAssets.IsInAgentStartup)
                                        {
                                            MyISMRoot?.Restart(true);
                                        }
                                        else
                                        {
                                            Shutdown(true);
                                        }
                                    }
                                }
                            });
                        });
                    }
                }


                TheCommCore.MyHttpService = new TheHttpService();
                TheBaseAssets.MySYSLOG.WriteToLog(4141, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("TheBaseApplication", "HttpService created", eMsgLevel.l3_ImportantMessage));

                if (TheBaseAssets.MyServiceHostInfo.StartISM && MyISMRoot == null && !string.IsNullOrEmpty(TheBaseAssets.MyServiceHostInfo.BaseDirectory))
                {
                    MyISMRoot = new TheISMManager {
                        eventShutdownRequired = sinkAppShutdown
                    };
                    MyISMRoot.InitISM("", "", "", TheBaseAssets.MyServiceHostInfo.CurrentVersion, TheBaseAssets.MyServiceHostInfo.ISMScanForUpdatesOnUSB, TheBaseAssets.MyServiceHostInfo.ISMScanOnStartup);
                    TheBaseAssets.MySYSLOG.WriteToLog(4142, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("TheBaseApplication", "ISM Started", eMsgLevel.l3_ImportantMessage));
                }
                else
                {
                    TheBaseAssets.MyServiceHostInfo.StartISM = false;
                }
                if (!TheBaseAssets.MasterSwitch)
                {
                    return(false);
                }

                if (MyCommonDisco == null)
                {
                    if (!TheBaseAssets.MyServiceHostInfo.IsIsolated && (TheCommonUtils.IsHostADevice() || TheBaseAssets.MyServiceHostInfo.cdeNodeType == cdeNodeType.Active))
                    {
                        TheBaseAssets.MySettings.SetSetting("DISCO_IsClientOnly", "True");
                    }
                    MyCommonDisco = new TheCommonDisco(); // Initialized the Discovery Service
                }

                TheCDEngines.eventAllEnginesStarted += sinkEnginesStarted;
                if (!TheCDEngines.StartEngines(pPlugInLst, null))                                           //Starts all SubEngines and Plugins. MyCmdArgs is a copy of the tParas sent to the Init Assets Function and can be used to set parameters for each engine during startup
                {
                    Shutdown(true);
                    TheBaseAssets.MySYSLOG.WriteToLog(4149, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("TheBaseApplication", "Failed to start engines", eMsgLevel.l3_ImportantMessage));
                    return(false);
                }
                return(true);
            }
            finally
            {
                TheBaseAssets.IsStarting = false;
            }
        }
Exemplo n.º 17
0
        void WriteToLogInternal(int pLogID, TSM MyText, bool NoLog, long tLogSerial)
        {
            bool AddEntry = true;

            if (LogFilter.Count > 0)
            {
                AddEntry = false;
                foreach (string t in LogFilter)
                {
                    if (MyText.ENG.Equals(t))
                    {
                        AddEntry = true;
                        break;
                    }
                }
            }
            if (LogOnly.Count > 0)
            {
                bool Found = false;
                foreach (string t in LogOnly)
                {
                    if (MyText.ENG == null || MyText.ENG.Equals(t))
                    {
                        Found = true;
                        break;
                    }
                }
                if (!Found)
                {
                    return;
                }
            }
            if (LogIgnore.Count > 0)
            {
                foreach (string t in LogIgnore)
                {
                    if (MyText.ENG == null || MyText.ENG.Equals(t))
                    {
                        return;
                    }
                }
            }
            if (!TheBaseAssets.MyServiceHostInfo.DisableConsole)
            {
                switch (MyText.LVL)
                {
                case eMsgLevel.l1_Error:
                    Console.ForegroundColor = ConsoleColor.Red;
                    break;

                case eMsgLevel.l2_Warning:
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    break;

                case eMsgLevel.l3_ImportantMessage:
                    Console.ForegroundColor = ConsoleColor.Green;
                    break;

                case eMsgLevel.l6_Debug:
                case eMsgLevel.l7_HostDebugMessage:
                    Console.ForegroundColor = ConsoleColor.Gray;
                    break;

                default:
                    Console.ForegroundColor = ConsoleColor.White;
                    break;
                }
                string tout = null;
                if (TheBaseAssets.MyServiceHostInfo.UseGELFLoggingFormat == true)
                {
                    var t = new TheGELFLogEntry()
                    {
                        version = "1.1",
                        host    = TheBaseAssets.MyServiceHostInfo.GetPrimaryStationURL(false),
                        level   = (int)MyText?.LVL,
#if CDE_NET45 || CDE_NET4 || CDE_NET35
                        timestamp = TheCommonUtils.CDbl($"{(MyText.TIM.Subtract(new DateTime(1970, 1, 1))).TotalSeconds}.{MyText.TIM.Millisecond}"),
#else
                        timestamp = TheCommonUtils.CDbl($"{MyText.TIM.ToUnixTimeSeconds()}.{MyText.TIM.Millisecond}"),
#endif
                        full_message  = TheBaseAssets.MyServiceHostInfo.ShowMarkupInLog ? TheCommonUtils.cdeStripHTML(MyText?.PLS) : MyText?.PLS,
                        short_message = TheBaseAssets.MyServiceHostInfo.ShowMarkupInLog? TheCommonUtils.cdeStripHTML(MyText?.TXT):MyText?.TXT,
                        _serial_no    = tLogSerial,
                        _log_id       = pLogID,
                        _engine       = MyText?.ENG,
                        _device_id    = MyText.ORG,
                        // _status_level = ?
                        // _topic = ?
                    };
                    tout = TheCommonUtils.SerializeObjectToJSONString <TheGELFLogEntry>(t);
                }
                else
                {
                    tout = $"ID:{pLogID} SN:{tLogSerial} {MyText.ToAllString()}";
                }
                Console.WriteLine(tout);
                Console.ForegroundColor = ConsoleColor.White;
            }
            if (AddEntry)
            {
                //if (MyText.Text == "True")              return;
                if (MyMessageLog != null)
                {
                    Add(pLogID, tLogSerial, "", MyText);
                }
                if (MyText.LVL == eMsgLevel.l1_Error)
                {
                    LastError = MyText;
                }
#if CDE_DEBUGVIEW
                System.Diagnostics.Debug.WriteLine(string.Format("ID:{0} SN:{1} {2}", pLogID, tLogSerial, MyText.ToAllString()));
#endif
                if (LogWriteBuffer > 0 && MyText.LVL < LogWriteFilterLevel)
                {
                    LogCounter++;
                    if (LogCounter > LogWriteBuffer)
                    {
                        LogCounter = 0;
                        WriteLogToFile(false);
                    }
                }
                if (TheBaseAssets.MyApplication != null && MyText.LVL < MessageFilterLevel)
                {
                    TheBaseAssets.MyApplication.ShowMessageToast(MyText, "");
                }
                if (TheCDEngines.MyIStorageService != null && TheBaseAssets.MyServiceHostInfo.StoreLoggedMessages && !NoLog &&
                    (MyText.LVL < LogFilterLevel) && TheCDEngines.MyIStorageService.GetBaseEngine().GetEngineState().IsEngineReady)
                {
                    TheCDEngines.MyIStorageService.EdgeDataStoreOnly(MyText, null);
                }
            }
        }
Exemplo n.º 18
0
        internal string GetNodeLog(TheSessionState pSession, string InTopic, bool ShowLinks)
        {
            string outText = "";

            if (!string.IsNullOrEmpty(InTopic))
            {
                InTopic = TheCommonUtils.cdeUnescapeString(InTopic);
            }
            outText += $"<div class=\"cdeInfoBlock\" style=\"clear:both; width:initial; \"><div class=\"cdeInfoBlockHeader cdeInfoBlockHeaderText\" id=\"systemLog\">Current SystemLog <a download=\"cdeSysLog_{TheCommonUtils.GetMyNodeName()}.csv\" href=\"#\" class=\'cdeExportLink\' onclick=\"return ExcellentExport.csv(this, 'cdeSysLog');\">(Export as CSV)</a></div>";
            try
            {
                outText += "<table class=\"cdeHilite\" id=\"cdeSysLog\" style=\"width:95%\">";
                outText += "<tr><th style=\"background-color:rgba(90,90,90, 0.25);font-size:small;\">Serial</th>";
                outText += "<th style=\"background-color:rgba(90,90,90, 0.25);font-size:small; \">LogID</th>";
                outText += "<th style=\"background-color:rgba(90,90,90, 0.25);font-size:small; \">Entry Date</th>";
                outText += "<th style=\"background-color:rgba(90,90,90, 0.25);font-size:small; \">Level</th>";
                //outText += "<th style=\"background-color:rgba(90,90,90, 0.25);font-size:small; \">ORG</th>";
                outText += "<th style=\"background-color:rgba(90,90,90, 0.25);font-size:small; \">Engine</th>";
                outText += "<th style=\"background-color:rgba(90,90,90, 0.25);font-size:small; \">Text</th><tr>";
                int MaxCnt = MyMessageLog.MyMirrorCache.Count;
                foreach (TheEventLogEntry tLogEntry in MyMessageLog.MyMirrorCache.MyRecords.Values.OrderByDescending(s => s.Serial).ToList()) //.cdeCTIM).ThenByDescending(s=>s.cdeCTIM.Millisecond).ToList())
                {
                    TSM tMsg = tLogEntry.Message;
                    if (!string.IsNullOrEmpty(InTopic) && !tMsg.ENG.Equals(InTopic))
                    {
                        continue;
                    }
                    if (tMsg.TXT == null)
                    {
                        tMsg.TXT = "";
                    }
                    var tColor = "black";
                    if (tMsg.TXT.Contains("ORG:2;"))
                    {
                        tColor = "blue";
                    }
                    else
                    {
                        if (tMsg.TXT.Contains("ORG:4;"))
                        {
                            tColor = "purple";
                        }
                        else
                        {
                            if (tMsg.TXT.Contains("ORG:3;"))
                            {
                                tColor = "navy";
                            }
                            else
                            {
                                if (tMsg.TXT.Contains("ORG:7;"))
                                {
                                    tColor = "brown";
                                }
                                else
                                {
                                    if (tMsg.TXT.Contains("ORG:8;") || TheCommonUtils.DoesContainLocalhost(tMsg.TXT))
                                    {
                                        tColor = "gray";
                                    }
                                }
                            }
                        }
                    }
                    switch (tMsg.LVL)
                    {
                    case eMsgLevel.l1_Error:
                        tColor = "red";
                        break;

                    case eMsgLevel.l2_Warning:
                        tColor = "orange";
                        break;

                    case eMsgLevel.l3_ImportantMessage:
                        tColor = "green";
                        break;

                    case eMsgLevel.l7_HostDebugMessage:
                        tColor = "gray";
                        break;

                    case eMsgLevel.l6_Debug:
                        tColor = "gray";
                        break;
                    }
                    outText += $"<tr>";
                    outText += $"<td class=\"cdeLogEntry\" style=\"color:{tColor}\">{tLogEntry.Serial}</td>";
                    outText += $"<td class=\"cdeLogEntry\" style=\"color:{tColor}\">{tLogEntry.EventID}</td>";
                    outText += $"<td class=\"cdeLogEntry\" style=\"color:{tColor}\">{TheCommonUtils.GetDateTimeString(tMsg.TIM, 0, "yyyy-MM-dd HH:mm:ss.fff")}</td>";
                    outText += $"<td class=\"cdeLogEntry\" style=\"color:{tColor}\">{tMsg.LVL}{(TSM.L(eDEBUG_LEVELS.ESSENTIALS)?tMsg.GetHash().ToString():"")}</td>";
                    //outText += $"<td class=\"cdeLogEntry\" style=\"color:{tColor}\">{tMsg.ORG}</td>";    //ORG-OK
                    if (ShowLinks && pSession != null)
                    {
                        outText += $"<td class=\"cdeLogEntry\"><SMALL><a href=\"/cdeStatus.aspx?Filter={TheCommonUtils.cdeEscapeString(tMsg.ENG)}\">{tMsg.ENG}</a></SMALL></td>";
                    }
                    else
                    {
                        outText += $"<td class=\"cdeLogEntry\"><SMALL>{tMsg.ENG.Replace(".", " ")}</SMALL></td>";
                    }
                    outText += $"<td class=\"cdeLogEntry\" style=\"color:{tColor}\">{tMsg.TXT}</td>";
                    outText += "</tr>";
                    if (!string.IsNullOrEmpty(tMsg.PLS))
                    {
                        outText += $"<tr><td class=\"cdeLogEntry\" style=\"color:{tColor}\">{tLogEntry.Serial}</td><td class=\"cdeLogEntry\" colspan=\"7\" style=\"color:{tColor}\"><SMALL>{TheCommonUtils.cdeESCXMLwBR(TheCommonUtils.cdeSubstringMax(tMsg.PLS, 2000))}</SMALL></td></tr>"; //Find a better way. This does not work with the sorttable
                    }
                    MaxCnt--;
                }
                outText += "</tbody></table></div>";
            }
            catch (Exception e)
            {
                outText += "Exception in Log: " + e;
            }
            return(outText);
        }
Exemplo n.º 19
0
        private static void ValSetter2(ref TSM tTSM, string ptr, object tval, bool IsJSON)
        {
            switch (ptr) //int
            {
            case "TXT":
                tTSM.TXT = TheCommonUtils.CStr(tval);
                break;

            case "TIM":
                if (IsJSON)
                {
                    if (tval != null)
                    {
                        long tim = TheCommonUtils.CLng(tval.ToString().Substring(6, tval.ToString().Length - 8));
                        tTSM.TIM = new DateTimeOffset(1970, 1, 1, 0, 0, 0, DateTimeOffset.Now.Offset).Add(new TimeSpan(tim * 10000));
                    }
                }
                else
                {
                    if (tval != null)
                    {
                        tTSM.TIM = TheCommonUtils.CDate(tval.ToString());
                    }
                }
                break;

            case "FLG":
                tTSM.FLG = (ushort)TheCommonUtils.CInt(tval);
                break;

            case "PLS":
                tTSM.PLS = TheCommonUtils.CStr(tval);
                break;

            case "ORG":
                tTSM.ORG = TheCommonUtils.CStr(tval);    //ORG-OK
                break;

            case "QDX":
                tTSM.QDX = TheCommonUtils.CInt(tval);
                break;

            case "LVL":
                if (tval.Equals("l1_Error"))
                {
                    tTSM.LVL = eMsgLevel.l1_Error;
                }
                else if (tval.Equals("l2_Warning"))
                {
                    tTSM.LVL = eMsgLevel.l2_Warning;
                }
                else if (tval.Equals("l3_ImportantMessage"))
                {
                    tTSM.LVL = eMsgLevel.l3_ImportantMessage;
                }
                else if (tval.Equals("l4_Message"))
                {
                    tTSM.LVL = eMsgLevel.l4_Message;
                }
                else if (tval.Equals("l5_HostMessage"))
                {
                    tTSM.LVL = eMsgLevel.l5_HostMessage;
                }
                else if (tval.Equals("l6_Debug"))
                {
                    tTSM.LVL = eMsgLevel.l6_Debug;
                }
                else if (tval.Equals("l7_HostDebugMessage"))
                {
                    tTSM.LVL = eMsgLevel.l7_HostDebugMessage;
                }
                else if (tval.Equals("ALL"))
                {
                    tTSM.LVL = eMsgLevel.ALL;
                }
                else
                {
                    tTSM.LVL = 0;
                }
                break;

            case "ENG":
                tTSM.ENG = TheCommonUtils.CStr(tval);
                break;

            case "FID":
                tTSM.FID = TheCommonUtils.CStr(tval);
                break;

            case "SID":
                tTSM.SID = TheCommonUtils.CStr(tval);
                break;

            case "SEID":
                tTSM.SEID = TheCommonUtils.CStr(tval);
                break;

            case "UID":
                tTSM.UID = TheCommonUtils.CStr(tval);
                break;

            case "CST":
                tTSM.CST = TheCommonUtils.CStr(tval);
                break;

            case "OWN":
                tTSM.OWN = TheCommonUtils.CStr(tval);
                break;

            case "PLB":
                if (tval != null)
                {
                    tTSM.PLB = Convert.FromBase64String(tval.ToString());
                }
                break;
            }
        }
Exemplo n.º 20
0
 public Dictionary <string, string> ScanLibrary(string assemblyPath, out TSM resTSM)
 {
     return(ScanLibrary(assemblyPath, out resTSM, out _));
 }
Exemplo n.º 21
0
        /// <summary>
        /// Deserializes the TSM from the C-DEngine binary format
        /// This is not used for the HTTP channel but reserverd for future use on other TCP/UPD channels
        /// </summary>
        /// <param name="pInBuffer"></param>
        /// <param name="pOffset"></param>
        /// <returns></returns>
        internal static TSM FromPacketBytes(byte[] pInBuffer, int pOffset)
        {
            int numberOfDataEntries = 0;

            byte[] dataBytes = null;
            TSM    tNewTSM   = new TSM(); //Save not to write ORG or SID

            using (MemoryStream byteStream = new MemoryStream(pInBuffer, pOffset, pInBuffer.Length - pOffset))
            {
                int packetSize = (byteStream.ReadByte() << 0);
                packetSize |= (byteStream.ReadByte() << 8);
                packetSize |= (byteStream.ReadByte() << 16);
                packetSize |= (byteStream.ReadByte() << 24);
                if (packetSize != pInBuffer.Length)
                {
                    throw new InvalidOperationException("Invalid packet size");
                }

                long timeBinary = byteStream.ReadByte();
                timeBinary |= ((long)byteStream.ReadByte()) << 8;
                timeBinary |= ((long)byteStream.ReadByte()) << 16;
                timeBinary |= ((long)byteStream.ReadByte()) << 24;
                timeBinary |= ((long)byteStream.ReadByte()) << 32;
                timeBinary |= ((long)byteStream.ReadByte()) << 40;
                timeBinary |= ((long)byteStream.ReadByte()) << 48;
                timeBinary |= ((long)byteStream.ReadByte()) << 56;

                int timeOffsetInMinutes = (byteStream.ReadByte() << 0);
                timeOffsetInMinutes |= (byteStream.ReadByte() << 8);

                tNewTSM.TIM = new DateTimeOffset(DateTime.FromFileTime(timeBinary), new TimeSpan(0, timeOffsetInMinutes, 0));

                tNewTSM.LVL         = (eMsgLevel)byteStream.ReadByte();
                tNewTSM.FLG         = (ushort)(((ushort)byteStream.ReadByte()) << 8);
                tNewTSM.FLG        += (ushort)byteStream.ReadByte();
                tNewTSM.QDX        += byteStream.ReadByte();
                numberOfDataEntries = byteStream.ReadByte();
                int PLBlength = byteStream.ReadByte();
                PLBlength += byteStream.ReadByte() << 8;
                PLBlength += byteStream.ReadByte() << 16;
                PLBlength += byteStream.ReadByte() << 24;
                dataBytes  = new byte[packetSize - (21 + PLBlength + pOffset)];
                byteStream.Read(dataBytes, 0, dataBytes.Length);

                if (PLBlength > 0)
                {
                    tNewTSM.PLB = new byte[PLBlength];
                    byteStream.Read(tNewTSM.PLB, 0, PLBlength);
                }
            }

            int byteIndex = 0;

            for (int n = 0; n < numberOfDataEntries; n++)
            {
                //int dataStringLength = BitConverter.ToInt32(dataBytes, byteIndex);
                int dataStringLength = (dataBytes[byteIndex] << 0);
                dataStringLength |= (dataBytes[byteIndex + 1] << 8);
                dataStringLength |= (dataBytes[byteIndex + 2] << 16);
                dataStringLength |= (dataBytes[byteIndex + 3] << 24);
                byteIndex        += 4;

                string dataString = TheCommonUtils.CArray2UTF8String(dataBytes, byteIndex, dataStringLength);
                byteIndex += dataStringLength;

                switch (n)
                {
                case 0: tNewTSM.TXT = dataString; break;

                case 1: tNewTSM.PLS = dataString; break;

                case 2: tNewTSM.ORG = dataString; break;    //ORG-OK

                case 3: tNewTSM.ENG = dataString; break;

                case 4: tNewTSM.FID = dataString; break;

                case 5: tNewTSM.SID = dataString; break;

                case 6: tNewTSM.SEID = dataString; break;

                case 7: tNewTSM.UID = dataString; break;

                case 8: tNewTSM.CST = dataString; break;

                case 9: tNewTSM.OWN = dataString; break;
                }
            }
            return(tNewTSM);
        }
Exemplo n.º 22
0
            public Dictionary <string, string> ScanLibrary(string assemblyPath, out TSM resTSM, out Assembly tAss)
            {
                resTSM = null;
                Dictionary <string, string> mList = new Dictionary <string, string>();

                tAss = null;
                if (!_platformDoesNotSupportReflectionOnlyLoadFrom)
                {
                    try
                    {
                        tAss = Assembly.ReflectionOnlyLoadFrom(assemblyPath);
                    }
                    catch (PlatformNotSupportedException) //No Assembly.ReflectionOnlyLoadFrom
                    {
                        _platformDoesNotSupportReflectionOnlyLoadFrom = true;
                    }
                }
                if (_platformDoesNotSupportReflectionOnlyLoadFrom)
                {
                    try
                    {
                        tAss = Assembly.LoadFrom(assemblyPath);
                    }
                    catch (PlatformNotSupportedException)
                    {
                        //If we end up here, the assembly was compiled with the Native Tool Chain (i.e. XBox Store)
                        //all names are stripped out and identification of a assembly can only be made by its "interface footprint"
                        var t = AppDomain.CurrentDomain.GetAssemblies();
                        foreach (var assembly in t)
                        {
                            try
                            {
                                var CDEPlugins = from tt in assembly.GetTypes()
                                                 let ifs = tt.GetInterfaces()
                                                           where ifs != null && ifs.Length > 0 && (ifs.Any(s => _KnownInterfaces.Contains(s.Name)))
                                                           select new { Type = t, tt.Namespace, tt.Name, tt.FullName };
                                if (CDEPlugins?.Any() == true)
                                {
                                    var IsCDEAss = from tt in assembly.GetTypes()
                                                   let ifs = tt.GetInterfaces()
                                                             where ifs != null && ifs.Length > 0 && (ifs.Any(s => "IBaseEngine".Equals(s.Name)))
                                                             select new { Type = t, tt.Namespace, tt.Name, tt.FullName };

                                    if (IsCDEAss.Any() == false)
                                    {
                                        tAss = assembly;
                                        break;
                                    }
                                }
                            }
                            catch (Exception)
                            {
                                //ignore
                            }
                        }
                    }
                }

                if (tAss != null)
                {
                    var CDEPlugins = from t in tAss.GetTypes()
                                     let ifs = t.GetInterfaces()
                                               where ifs != null && ifs.Length > 0 && (ifs.Any(s => _KnownInterfaces.Contains(s.Name)))
                                               select new { Type = t, t.Namespace, t.Name, t.FullName };
                    if (CDEPlugins == null || !CDEPlugins.Any())
                    {
                        if (!assemblyPath.ToLower().Contains(".resources."))
                        {
                            resTSM = new TSM("TheBaseAssets", $"File {assemblyPath} - found but did not contain C-DEngine Crypto Interface", eMsgLevel.l2_Warning);
                        }
                    }
                    else
                    {
                        resTSM = new TSM("TheCDEngines", $"Assembly {assemblyPath} found and added Crypto", "");
                        foreach (var Plugin in CDEPlugins)
                        {
                            if (!(Plugin?.Type?.IsAbstract == true))
                            {
                                var ints = Plugin.Type.GetInterfaces();
                                foreach (var tI in ints)
                                {
                                    if (_KnownInterfaces.Contains(tI.Name))
                                    {
                                        resTSM.PLS    += $"{Plugin.FullName};";
                                        mList[tI.Name] = Plugin.FullName;
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    resTSM = new TSM("TheCDEngines", $"Failed to load assembly {assemblyPath}", eMsgLevel.l1_Error);
                }
                return(mList);
            }
Exemplo n.º 23
0
        internal static void InitAssets(TheBaseApplication pApp)
        {
            if (IsInitialized)
            {
                return;
            }
            IsInitialized = true;
            if (MyServiceHostInfo == null || !(MySecrets?.IsApplicationIDValid() == true))
            {
                MasterSwitch = false;
                return;
            }
            MyApplication = pApp;

            #region step 1: Moved from StartApplication to here as all the following code is updating TheBaseAssets
            //The following section are "app.config" only settings required before cdeTPI is loaded. These settings cannot be set via the Provisioning Service
            int delay = TheCommonUtils.CInt(MySettings.GetSetting("StartupDelay"));
            if (delay > 0)
            {
                TheCommonUtils.SleepOneEye((uint)(delay * 1000), 100);
            }

            string temp = MySettings.GetSetting("AllowEnvironmentVarsToOverrideConfig");
            if (!string.IsNullOrEmpty(temp))
            {
                MyServiceHostInfo.AllowEnvironmentVarsToOverrideConfig = TheCommonUtils.CBool(temp);
            }
            temp = MySettings.GetSetting("AllowEnvironmentVars");
            if (!string.IsNullOrEmpty(temp))
            {
                MyServiceHostInfo.AllowEnvironmentVars = TheCommonUtils.CBool(temp);
            }
            temp = MySettings.GetSetting("DEBUGLEVEL");
            if (!string.IsNullOrEmpty(temp))
            {
                MyServiceHostInfo.DebugLevel = (eDEBUG_LEVELS)TheCommonUtils.CInt(temp);
            }
            //Clouds have special behavior and the CDE needs to know this upfront
            temp = MySettings.GetSetting("IsCloudService");
            if (!string.IsNullOrEmpty(temp))
            {
                MyServiceHostInfo.IsCloudService = TheCommonUtils.CBool(temp);
            }
            temp = MySettings.GetSetting("ISOEN");
            if (!string.IsNullOrEmpty(temp))
            {
                MyServiceHostInfo.IsIsolated  = true;
                MyServiceHostInfo.IsoEngine   = temp;
                MyServiceHostInfo.cdeNodeType = cdeNodeType.Active;
            }
            else
            {
                temp = MySettings.GetSetting("UseRandomDeviceID");
                if (!string.IsNullOrEmpty(temp))
                {
                    MyServiceHostInfo.UseRandomDeviceID = TheCommonUtils.CBool(temp);
                }
            }

            //Step 2: Restore from backup if exists
#if CDE_NET45 // Backup/Restore only support on NET45
            // To ensure that restored backups are not overwritten during shutdown, we write them to a temp directory and move them into place on start up
            if (!MyServiceHostInfo.UseRandomDeviceID && !MyServiceHostInfo.IsIsolated)
            {
                string cacheParentPath = TheCommonUtils.GetCurrentAppDomainBaseDirWithTrailingSlash() + "ClientBin\\";
                if (Directory.Exists(cacheParentPath + "__CacheToRestore"))
                {
                    // Keep the old Cache around just in case
                    try
                    {
                        // First make space for the old copy, in case there was one already
                        if (Directory.Exists(cacheParentPath + "__CacheOld"))
                        {
                            Directory.Delete(cacheParentPath + "__CacheOld", true);
                        }
                    }
                    catch
                    {
                        //ignored
                    }
                    try
                    {
                        Directory.Move(cacheParentPath + "Cache", cacheParentPath + "__CacheOld");
                    }
                    catch
                    {
                        //ignored
                    }

                    // Now move the restored cache into place
                    try
                    {
                        Directory.Move(cacheParentPath + "__CacheToRestore", cacheParentPath + "Cache");
                    }
                    catch
                    {
                        TheSystemMessageLog.ToCo("Failure while restoring backup");
                    }
                }
            }
#endif

            MyServiceHostInfo.EnableTaskKPIs = TheCommonUtils.CBool(MySettings.GetSetting("EnableTaskKPIs"));
            if (MyServiceHostInfo.EnableTaskKPIs)
            {
                var taskKpiThread = new Thread(() =>
                {
                    do
                    {
                        var kpis = TheCommonUtils.GetTaskKpis(null);
                        TheSystemMessageLog.ToCo($"Tasks {DateTime.Now}: {TheCommonUtils.SerializeObjectToJSONString(kpis)}");
                        Thread.Sleep(1000); // Keeping it simple here, to minimize interference on task scheduler/thread scheduler etc. (Assumption: not used on production systems) // TheCommonUtils.SleepOneEye(1000, 1000);
                    } while (MasterSwitch && !Engines.TheCDEngines.IsHostReady && MyServiceHostInfo.EnableTaskKPIs);
                    TheSystemMessageLog.ToCo($"Tasks {DateTime.Now}: KPIs Handoff to NodeHost");
                });
                taskKpiThread.Start();
            }
            #endregion

            if (MyActivationManager == null)
            {
                MyActivationManager = new TheDefaultActivationManager(MySecrets, MySYSLOG);
            }


            #region step 3: analyse os environment information
            OperatingSystem os           = Environment.OSVersion;
            var             osInfoForLog = $"C-DEngine version: {BuildVersion} OS:{Environment.OSVersion} OS Version:{os.VersionString} OS Version Numbers: {os.Version.Major}.{os.Version.Minor}.{os.Version.Build}.{os.Version.Revision} Platform:{os.Platform} SP:{os.ServicePack} Processor Count: {Environment.ProcessorCount} IsMono:{(Type.GetType("Mono.Runtime") != null)} IsNetCore:{TheCommonUtils.IsNetCore()} Product: {TheCommonUtils.GetAssemblyProduct(typeof(TheBaseAssets))} ";
            TheSystemMessageLog.ToCo(osInfoForLog);
            MyServiceHostInfo.OSInfo = osInfoForLog;
            string dotNetInfoForLog = string.Empty;
#if !CDE_NET35 && !CDE_NET4
            try
            {
                string frameworkDescription = null;
                string osDescription        = null;
                string processArchitecture  = null;
                string osArchitecture       = null;

#if CDE_STANDARD
                frameworkDescription = System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription;
                osDescription        = System.Runtime.InteropServices.RuntimeInformation.OSDescription;
                processArchitecture  = System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture.ToString();
                osArchitecture       = System.Runtime.InteropServices.RuntimeInformation.OSArchitecture.ToString();
#else
                var rtInfoType = Type.GetType("System.Runtime.InteropServices.RuntimeInformation, System.Runtime.InteropServices.RuntimeInformation, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
                if (rtInfoType != null)
                {
                    frameworkDescription = rtInfoType.GetProperty("FrameworkDescription").GetValue(null).ToString();
                    osDescription        = rtInfoType.GetProperty("OSDescription").GetValue(null).ToString();
                    processArchitecture  = rtInfoType.GetProperty("ProcessArchitecture").GetValue(null).ToString();
                    osArchitecture       = rtInfoType.GetProperty("OSArchitecture").GetValue(null).ToString();
                }
#endif
                if (!string.IsNullOrEmpty(frameworkDescription))
                {
                    dotNetInfoForLog = $"NetFrameWork:{frameworkDescription} Processor:{processArchitecture} OS:{osDescription } OS Arch:{osArchitecture}";
                    TheSystemMessageLog.ToCo(dotNetInfoForLog);
                    MyServiceHostInfo.OSInfo += $" {dotNetInfoForLog}";
                }
            }
            catch
            {
            }
#endif
            if (TheCommonUtils.IsMono()) // CODE REVIEW: Need to clean this up - do we mean Mono or Linux or case-insensitive file systems? CM: No- here we need this to find out if we are running in the MONO Runtime
            {
                MyServiceHostInfo.cdePlatform = cdePlatform.MONO_V3;
            }
            else
            {
#if CDE_NET35
                MyServiceHostInfo.cdePlatform = cdePlatform.X32_V3;
#elif CDE_NET4
                MyServiceHostInfo.cdePlatform = Environment.Is64BitProcess ? cdePlatform.NETV4_64 : cdePlatform.NETV4_32;
#elif CDE_STANDARD
                MyServiceHostInfo.cdePlatform = cdePlatform.NETSTD_V20;
#else
                MyServiceHostInfo.cdePlatform = TheCommonUtils.GetAssemblyPlatform(Assembly.GetEntryAssembly(), false, out var empty);// old: Environment.Is64BitProcess ? cdePlatform.X64_V3 : cdePlatform.X32_V4;
#endif
            }
            TheSystemMessageLog.ToCo("BaseDir: " + MyServiceHostInfo.BaseDirectory);
            #endregion

            #region step 4: Prepare essential Subsystems (Syslog, ScopeManager, Diagnostics, Caches, AppInfo)
            MySYSLOG = new TheSystemMessageLog(500); // No more ToCo after this point (will be ignored)
            TheCDEKPIs.Reset();

            MyServiceHostInfo.MiniHostInfo.MySYSLOG = MySYSLOG;
            MyServiceHostInfo.MiniHostInfo.MyKPIs   = new TheKPIs();
            if (MyScopeManager == null)
            {
                MyScopeManager = new TheDefaultScopeManager();
            }
            MyScopeManager.SetMiniHSI(MyServiceHostInfo.MiniHostInfo);
            MyScopeManager.RegisterScopeChanged(localEventScopeChanged);

            TheDiagnostics.InitDiagnostics();
            TheDiagnostics.SetThreadName("MAIN THREAD");
            TheQueuedSenderRegistry.Startup();

            MyBlobCache     = new TheMirrorCache <TheBlobData>(MyServiceHostInfo.TO.StorageCleanCycle);
            MyReceivedParts = new TheMirrorCache <TheReceivedParts>(MyServiceHostInfo.TO.StorageCleanCycle);
            //TODO: I hope there is a better way to do this for Metro!
            MyServiceTypes.Add(typeof(TheBaseAssets));

            MyServiceHostInfo.TO.MakeHeartNormal();

            MyAppInfo = new ThePluginInfo
            {
                cdeMID             = MyServiceHostInfo.cdeMID,
                CurrentVersion     = MyServiceHostInfo.CurrentVersion,
                Developer          = MyServiceHostInfo.VendorName,
                DeveloperUrl       = MyServiceHostInfo.VendorUrl,
                HomeUrl            = MyServiceHostInfo.SiteName,
                IconUrl            = MyServiceHostInfo.UPnPIcon,
                LongDescription    = MyServiceHostInfo.Description,
                Platform           = MyServiceHostInfo.cdePlatform,
                Copyrights         = MyServiceHostInfo.Copyrights,
                Price              = 0,
                ServiceDescription = MyServiceHostInfo.Title,
                ServiceName        = MyServiceHostInfo.ApplicationName,
                Capabilities       = new List <eThingCaps> {
                    eThingCaps.Host
                },
                Categories    = new List <string>(),
                FilesManifest = new List <string>()
            };
            if (MyServiceHostInfo.ManifestFiles != null)
            {
                MyAppInfo.FilesManifest.AddRange(MyServiceHostInfo.ManifestFiles);
            }
            #endregion

            //Now load provisioning and local settings then parse them
#pragma warning disable CS0618 // Type or member is obsolete - its allowed here
            if (!TheCDESettings.ParseSettings(MyCmdArgs, true, false))
#pragma warning restore CS0618 // Type or member is obsolete
            {
                MasterSwitch = false;
                return;
            }

            if (MyCodeSigner == null)
            {
                MyCodeSigner = new TheDefaultCodeSigning(MySecrets, MySYSLOG);
            }
            string tBaseDir = MyServiceHostInfo.BaseDirectory;
            if (MyServiceHostInfo.cdeHostingType == cdeHostType.IIS)
            {
                tBaseDir += "bin\\";
            }
            string uDir = tBaseDir;
            if (!string.IsNullOrEmpty(MyServiceHostInfo.ISMMainExecutable))
            {
                uDir += MyServiceHostInfo.ISMMainExecutable;
                if (MyServiceHostInfo.cdeHostingType != cdeHostType.IIS)
                {
                    var hostPath = uDir + ".exe";
                    if (!File.Exists(hostPath))
                    {
                        // We may be running under .Net Core with a .dll-based host
                        hostPath = uDir + ".dll";
                    }
                    uDir = hostPath;
                }
            }
            else
            {
                uDir += "C-DEngine.dll";
            }
            MyServiceHostInfo.CodeSignThumb = MyCodeSigner.GetAppCert(MyServiceHostInfo.DontVerifyTrust, uDir, MyServiceHostInfo.VerifyTrustPath, MyServiceHostInfo.DontVerifyIntegrity);  //Must be loaded here to set trust level in HSI

            if (MyLoc as TheDefaultLocalizationUtils != null)
            {
                (MyLoc as TheDefaultLocalizationUtils).DoPseudoLoc = TheCommonUtils.CBool(MySettings.GetSetting("DoPseudoLoc"));
            }

            #region step 5: output some system information
            if (MyServiceHostInfo.IsMemoryOptimized)
            {
                MySYSLOG.SetMaxLogEntries(10);
            }
            MySYSLOG.WriteToLog(4151, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("TheBaseAssets", osInfoForLog, eMsgLevel.l4_Message));

            if (!string.IsNullOrEmpty(dotNetInfoForLog))
            {
                MySYSLOG.WriteToLog(4152, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("TheBaseAssets", dotNetInfoForLog, eMsgLevel.l4_Message));
            }
            MySYSLOG.WriteToLog(4153, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("TheBaseAssets", "BaseDir: " + MyServiceHostInfo.BaseDirectory, eMsgLevel.l4_Message));
            #endregion

            #region step 6: determine WebSocket8 vs. WebSocketsSharp
            var ws8FlagTemp = MySettings.GetSetting("DisallowWebSocket8");
            if (!string.IsNullOrEmpty(ws8FlagTemp))
            {
                MyServiceHostInfo.IsWebSocket8Active = !TheCommonUtils.CBool(ws8FlagTemp);
                MySYSLOG.WriteToLog(4154, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("TheBaseAssets", $"Setting IsWebSocket8Active to {MyServiceHostInfo.IsWebSocket8Active} due to config", eMsgLevel.l4_Message));
            }
            else
            {
                MyServiceHostInfo.IsWebSocket8Active = true;
            }
            if ((os.Platform != PlatformID.Win32NT && !TheCommonUtils.IsNetCore()) || (os.Platform == PlatformID.Win32NT && (os.Version.Major < 6 || (os.Version.Major == 6 && os.Version.Minor < 2))))
            {
                MyServiceHostInfo.IsWebSocket8Active = false;
                string tWSMsg = "Older Windows or non-Windows OS Detected - No OS Support for WebSockets Found: ";
#if !CDE_USECSWS //OK
                TheBaseAssets.MyServiceHostInfo.DisableWebSockets = true;
                tWSMsg += "WebSockets are turned Off";
#else
                tWSMsg += "Switching to WebSockets-Sharp";
#endif
                MySYSLOG.WriteToLog(4155, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("TheBaseAssets", tWSMsg, eMsgLevel.l4_Message));
            }
            #endregion

            #region step 7: Initialize Localization subsystem (ILocalizationHooks)
            bool bLocInitialized = false;
            try
            {
                var entryAssembly = Assembly.GetEntryAssembly();    //This does not work in IIS!
                if (entryAssembly != null)
                {
                    var CDEPlugins = from t in entryAssembly.GetTypes()
                                     let ifs = t.GetInterfaces()
                                               where ifs != null && ifs.Length > 0 && (ifs.Contains(typeof(ILocalizationHooks)))
                                               select new { Type = t, t.Namespace, t.Name, t.FullName };
                    if (CDEPlugins != null && CDEPlugins.Any())
                    {
                        MyLoc = Activator.CreateInstance(CDEPlugins.First().Type) as ILocalizationHooks;
                    }
                    bLocInitialized = true;
                }
            }
            catch
            {
            }
            if (!bLocInitialized)
            {
                MySYSLOG.WriteToLog(4156, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("TheBaseAssets", "3rd Party ILocalization Hooks not found - using built-in", eMsgLevel.l4_Message));
            }
            #endregion

            #region step 8: Set MyStationUrl
            switch (MyServiceHostInfo.cdeHostingType)
            {
            case cdeHostType.Phone:
            case cdeHostType.Metro:
                MyServiceHostInfo.MyDeviceMoniker = "CDEV://";
                break;

            case cdeHostType.Silverlight:
                MyServiceHostInfo.MyDeviceMoniker = "CDES://";
                break;

            case cdeHostType.Device:
                MyServiceHostInfo.MyDeviceMoniker = "CDEC://";
                break;

            case cdeHostType.Mini:
                MyServiceHostInfo.MyDeviceMoniker = "CDEM://";
                break;

            default:     //Services
                MyServiceHostInfo.MyDeviceMoniker = "CDEB://";
                break;
            }
            if (TheCommonUtils.IsHostADevice())
            {
                MyServiceHostInfo.MyStationURL = MyServiceHostInfo.MyDeviceMoniker + "{" + MyServiceHostInfo.MyDeviceInfo.DeviceID + "}".ToUpper(); //MSU-OK
            }
            else
            {
                if (MyServiceHostInfo.MyAltStationURLs.Count(s => s.StartsWith("CDEB")) == 0)
                {
                    MyServiceHostInfo.MyAltStationURLs.Add("CDEB://{" + MyServiceHostInfo.MyDeviceInfo.DeviceID + "}"); //TODO: Backchannel Possibly save to Config File
                }
            }
            #endregion

            #region step 9: Start Localhost QSender and SessionStateManager
            MySession        = new TheSessionStateManager(MyServiceHostInfo);
            LocalHostQSender = new TheQueuedSender();                                                                                                                                                                                 //NO connected or Error Event necessary
            LocalHostQSender.StartSender(new TheChannelInfo(MyServiceHostInfo.MyDeviceInfo.DeviceID, MyScopeManager.ScopeID, MyServiceHostInfo.MyDeviceInfo.SenderType, MyServiceHostInfo.GetPrimaryStationURL(false)), null, false); //NEW:2.06 Setting Realscope here ///null correct - no subs on LocalhostQS in beginning //RScope-OK
            if ((MyServiceHostInfo.DisableWebSockets || MyServiceHostInfo.MyStationWSPort == 0) && !TheCommonUtils.IsHostADevice())
            {
                MySYSLOG.WriteToLog(4157, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("TheBaseAssets", $"WebSockets Disabled - no WSPort specified {MyServiceHostInfo.MyStationWSPort} or DisableWebSocket={MyServiceHostInfo.DisableWebSockets}", eMsgLevel.l4_Message));
            }
            #endregion

            // Post Device ID settings

            //Step 10: Save all settings to local cdeTPI
            MySettings.UpdateLocalSettings();
        }
Exemplo n.º 24
0
        /// <summary>
        /// Shutsdown the C-DEngine and all plugins
        /// Applications can override this function to add custom shutdown code
        /// </summary>
        /// <param name="ForceExit">If True and the C-DEngine will Stop or restart the hosting application. If it is hosted in IIS, the Application Pool hosting the app will be Stopped or Restarted depending on the next parameter</param>
        /// <param name="waitIfPending">Waits in case The shutdown is already initiated</param>
        public virtual void Shutdown(bool ForceExit, bool waitIfPending = false)
        {
            if (!waitIfPending)
            {
                if (!TheBaseAssets.MasterSwitch || TheCommonUtils.cdeIsLocked(ShutdownLock))
                {
                    return;                                                                                                            //Make sure we dont do this twice
                }
            }
            lock (ShutdownLock)
            {
                if (TheBaseAssets.MasterSwitch)
                {
                    if (TheBaseAssets.IsStarting)
                    {
                        TheBaseAssets.MySYSLOG?.WriteToLog(3, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM(TheBaseAssets.MyServiceHostInfo.ApplicationName, "Shutdown was requested, but startup has not finished. Waiting for startup to finish.", eMsgLevel.l3_ImportantMessage));
                        // Ensure we wait for user manager so CUOFS first-run-only settings are applied
                        var sw = System.Diagnostics.Stopwatch.StartNew();
                        while (TheBaseAssets.IsStarting && sw.ElapsedMilliseconds < 60000)
                        {
                            Thread.Sleep(100);
                        }
                        if (TheBaseAssets.IsStarting)
                        {
                            TheBaseAssets.MySYSLOG?.WriteToLog(3, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(TheBaseAssets.MyServiceHostInfo.ApplicationName, "Shutdown was requested, but startup has not finished after wait time (60 seconds). Shutting down regardless. Some first-run-only settings may not have been applied.", eMsgLevel.l1_Error));
                        }
                    }
                    if (TheBaseAssets.MyServiceHostInfo.PreShutDownDelay > 0)
                    {
                        var tcsPreHandlers = new TaskCompletionSource <bool>();
                        TheCommonUtils.cdeRunAsync("PreShutdownHandlers", true, (o) =>
                        {
                            TheCDEngines.MyContentEngine?.FireEvent(eEngineEvents.PreShutdown, null, TheBaseAssets.MyServiceHostInfo.PreShutDownDelay, false);
                            tcsPreHandlers.TrySetResult(true);
                        });
                        tcsPreHandlers.Task.Wait(TheBaseAssets.MyServiceHostInfo.PreShutDownDelay);
                    }
                    while (Interlocked.Read(ref TheBaseAssets.DelayShutDownCount) > 0)
                    {
                        TheCommonUtils.SleepOneEye(100, 100);
                    }
                    TheBaseAssets.MySYSLOG?.WriteToLog(3, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : new TSM(TheBaseAssets.MyServiceHostInfo.ApplicationName, TheBaseAssets.MyServiceHostInfo.ApplicationTitle + " Initiating shutdown at : " + TheCommonUtils.GetDateTimeString(DateTimeOffset.Now), eMsgLevel.l6_Debug));
                    TheBaseAssets.MasterSwitch  = false;
                    TheBaseAssets.ForceShutdown = ForceExit;
                    TheCDEngines.StopAllEngines();
                    TheBaseAssets.MySYSLOG?.WriteToLog(3, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : new TSM(TheBaseAssets.MyServiceHostInfo.ApplicationName, TheBaseAssets.MyServiceHostInfo.ApplicationTitle + " Shutdown: Engines stopped at: " + TheCommonUtils.GetDateTimeString(DateTimeOffset.Now), eMsgLevel.l6_Debug));

                    TheCommCore.StopCommunication();
                    TheBaseAssets.MySYSLOG?.WriteToLog(3, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : new TSM(TheBaseAssets.MyServiceHostInfo.ApplicationName, TheBaseAssets.MyServiceHostInfo.ApplicationTitle + " Shutdown: Communications stopped at: " + TheCommonUtils.GetDateTimeString(DateTimeOffset.Now), eMsgLevel.l6_Debug));
                    if (MyCommonDisco != null)
                    {
                        MyCommonDisco.ShutdownDiscoService();
                        TheBaseAssets.MySYSLOG?.WriteToLog(3, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : new TSM(TheBaseAssets.MyServiceHostInfo.ApplicationName, TheBaseAssets.MyServiceHostInfo.ApplicationTitle + " Shutdown: Discovery Service stopped at: " + TheCommonUtils.GetDateTimeString(DateTimeOffset.Now), eMsgLevel.l6_Debug));
                    }
                    if (TheBaseAssets.MySYSLOG != null)
                    {
                        string iis = "";
                        switch (TheBaseAssets.MyServiceHostInfo.cdeHostingType)
                        {
                        case cdeHostType.IIS: iis = " (Hosted in IIS)"; break;

                        case cdeHostType.ASPCore: iis = " (Hosted in ASP.NET Core)"; break;
                        }
                        TheBaseAssets.MySYSLOG.WriteToLog(3, new TSM(TheBaseAssets.MyServiceHostInfo.ApplicationName, TheBaseAssets.MyServiceHostInfo.ApplicationTitle + iis + " Stopped at : " + TheCommonUtils.GetDateTimeString(DateTimeOffset.Now), eMsgLevel.l4_Message)); //Log Entry that service has been started
                        TheBaseAssets.MySYSLOG.Shutdown();
                    }
                }
            }
        }