Пример #1
0
        public static bool Start()
        {
            bool bResult = false;

            TheScopeManager.SetScopeIDFromEasyID(strScopeID);   // Set a ScopeID - the security context of this node. You can replace tScope with any random 8 characters or numbers

            Dictionary <string, string> ArgList = new Dictionary <string, string>();

            // Scan command line settings.
            for (int i = 0; i < Program.args.Length; i++)
            {
                string[] tArgs = Program.args[i].Split('=');
                if (tArgs.Length == 2)
                {
                    string key = tArgs[0].ToUpper();
                    ArgList[key] = tArgs[1];
                }
            }
            ArgList["DontVerifyTrust"]   = "True";        // NEW: 3.2 If this is NOT set, all plugins have to be signed with the same certificate as the host application or C-DEngine.DLL
            ArgList["UseRandomDeviceID"] = "True";        // ATTENTION: ONLY if you set this to false, some of these parameters will be stored on disk and loaded at a later time. "true" assigns a new node ID everytime the host starts and no configuration data will be cached on disk.
            ArgList["ScopeUserLevel"]    = "255";         // Set the Scope Access Level

            MyBaseApplication = new TheBaseApplication(); // Create a new Base (C-DEngine IoT) Application

            if (MyBaseApplication != null)
            {
                // Start the C-DEngine Application. If a PluginService class is added DIRECTLY
                // to the host project you can instantiate the Service here replacing the null
                // with "new cdePluginService1()"
                bResult = MyBaseApplication.StartBaseApplication(null, ArgList);
            }

            return(bResult);
        }
Пример #2
0
        public void OnStartInternal()
        {
            StartupLog?.Log("Service: Initializing");
            try
            {
                if (!Initialize())
                {
                    StartupLog?.Log("Service: Initializing FAILED");
                    return;
                }
            }
            catch (Exception e)
            {
                StartupLog?.Log($"Service: Exception initializing: {e}");
            }
            StartupLog?.Log("Service: Parsing parameters");
            MyBaseApplication = new TheBaseApplication();
            if (CU.CBool(TheBaseAssets.MySettings.GetSetting("UseRandomScope")) && CU.CBool(TheBaseAssets.MySettings.GetSetting("UseRandomDeviceID")))
            {
                TheBaseAssets.MyServiceHostInfo.SealID = TheScopeManager.GenerateNewScopeID();
                TheScopeManager.SetScopeIDFromEasyID(TheBaseAssets.MyServiceHostInfo.SealID);
            }
            StartupLog?.Log("Service: StartBaseApplication");

            try
            {
                if (!MyBaseApplication.StartBaseApplication(null, MyArgList))
                {
                    StartupLog?.Log("Service: StartBaseApplication failed");

                    AfterStartup(false);
                    return;
                }
                if (StartupLog != null && MyArgList.ContainsKey("DisableConsole") && CU.CBool(MyArgList["DisableConsole"]))
                {
                    TheBaseAssets.MySYSLOG.RegisterEvent2("NewLogEntry", (pmsg, pNewLogEntry) =>
                    {
                        var tLog = pmsg?.Cookie as TheEventLogEntry;
                        if (tLog != null)
                        {
                            StartupLog?.Log($"ID:{tLog.EventID} SN:{tLog.Serial} {tLog.Message?.ToAllString()}", tLog.Message.LVL);
                        }
                    });
                }
            }
            catch (Exception ee)
            {
                StartupLog?.Log($"Service: StartBaseApplication failed with Exception: {ee}");

                AfterStartup(false);
                return;
            }
            StartupLog?.Log("Service: StartBaseApplication success");
            AfterStartup(true);
        }
Пример #3
0
        public static bool Start()
        {
            bool bResult = false;

            MyBaseApplication = new TheBaseApplication();    // Create a new Base (C-DEngine IoT) Application

            if (MyBaseApplication != null)
            {
                // Start the C-DEngine Application. If a PluginService class is added DIRECTLY
                // to the host project you can instantiate the Service here replacing the null
                // with "new cdePluginService1()"
                bResult = MyBaseApplication.StartBaseApplication(null, settings.ArgList);
            }

            return(bResult);
        }
Пример #4
0
        public static bool StartTheSite(TheBaseApplication pApplication, HttpContext pContext)
        {
            if (TheCommonUtils.cdeIsLocked(lockStart))
            {
                return(false);
            }
            lock (lockStart)
            {
                if (!WasHereBefore && !TheBaseAssets.MasterSwitch)
                {
                    WasHereBefore = true;
                }
                else
                {
                    return(false);
                }
            }
            Dictionary <string, string> ArgList = new Dictionary <string, string>();

            MySite = TheCommonUtils.CStr(System.Configuration.ConfigurationManager.AppSettings["MyStationURL"]);  //MSU-OK
            if (string.IsNullOrEmpty(MySite) && pContext != null)
            {
                MySite = pContext.Request.Url.Scheme + "://" + pContext.Request.Url.Host; //.Authority;
                if (pContext.Request.Url.Port > 0 && pContext.Request.Url.Port != TheBaseAssets.MyServiceHostInfo.MyStationPort)
                {
                    TheBaseAssets.MyServiceHostInfo.MyStationPort = (ushort)pContext.Request.Url.Port;
                    if ((pContext.Request.Url.Scheme.Equals("https") && pContext.Request.Url.Port != 443) ||
                        (pContext.Request.Url.Scheme.Equals("http") && pContext.Request.Url.Port != 80))
                    {
                        MySite += ":" + pContext.Request.Url.Port;
                    }
                }
            }
            ArgList["MyStationURL"] = MySite;

            if (!pApplication.StartBaseApplication(null, ArgList))
            {
                return(false);
            }

            if (!TheBaseAssets.MyActivationManager.CheckLicense(new Guid("{5737240C-AA66-417C-9B66-3919E18F9F4A}"), "", null, 1))
            {
                ExpiredText = "...Cloud has Expired - contact C-Labs for updated version";
                return(false);
            }
            return(true);
        }
Пример #5
0
        public async void ConnectToCloud(string pScopeID)
        {
            if (TheBaseAssets.MasterSwitch)
            {
                await UpdateLog("SYSTEM: Already Connected");

                return;
            }
            TheScopeManager.SetApplicationID("/cVjzPfjlO;{@QMj:jWpW]HKKEmed[llSlNUAtoE`]G?"); //SDK Non-Commercial ID. FOR COMMERCIAL APP GET THIS ID FROM C-LABS!

            TheBaseAssets.MyServiceHostInfo = new TheServiceHostInfo(cdeHostType.Application)
            {
                ApplicationName  = "My-Relay",                                                     //Friendly Name of Application
                cdeMID           = TheCommonUtils.CGuid("{4DB8E613-093F-4581-8E84-FE60FFA05A8E}"), //TODO: Give a Unique ID to this Host Service
                Title            = "HackChatXAML (C) C-Labs. Corp 2019",                           //Title of this Host Service
                ApplicationTitle = "HackChat",                                                     //Title visible in the NMI Portal
                CurrentVersion   = 1.0001,                                                         //Version of this Service, increase this number when you publish a new version that the store displays the correct update icon
                DebugLevel       = eDEBUG_LEVELS.VERBOSE,                                          //Define a DebugLevel for the SystemLog output.
                SiteName         = "http://cloud.c-labs.com",                                      //Link to the main Cloud Node of this host. this is not required and for documentation only

                ISMMainExecutable = "HCXaml",                                                      //Name of the executable (without .exe)
            };

            #region Args Parsing
            Dictionary <string, string> ArgList = new Dictionary <string, string>();
            #endregion

            ArgList.Add("ServiceRoute", "wss://cloud.c-labs.com");
            ArgList.Add("UseRandomDeviceID", "true");                        //Set the Scope Access Level
            ArgList.Add("ScopeUserLevel", "255");                            //Set the Scope Access Level
            TheBaseApplication MyBaseApplication = new TheBaseApplication(); //Create a new Base (C-DEngine IoT) Application
            TheCDEngines.eventAllEnginesStarted += sinkReady;
            var tChatPlugin = new cdePluginService1();
            if (!MyBaseApplication.StartBaseApplication(tChatPlugin, ArgList))         //Start the C-DEngine Application. If a PluginService class is added DIRECTLY to the host project you can instantiate the Service here replacing the null with "new cdePluginService1()"
            {
                await UpdateLog("SYSTEM: Start BaseApp failed!");

                return;                                                         //If the Application fails to start, quit the app. StartBaseApplication returns very fast as all the C-DEngine code is running asynchronously
            }
            else
            {
                TheScopeManager.SetScopeIDFromEasyID(pScopeID);
                await UpdateLog("SYSTEM: Start BaseApp started!");
            }
        }
Пример #6
0
        public static bool Start()
        {
            bool bResult = false;

            TheBaseAppSettings settings = new TheBaseAppSettings();

            // Directly add keys to settings table.
            // settings.AddKey("UseTcpListenerInsteadOfHttpListener", true);
            settings.SetKeyUnlessAlreadySet("DEBUGLEVEL", eDEBUG_LEVELS.VERBOSE);

            // Allow resources fetches without authenticating with a Scope ID.
            settings.AddKey("AllowDistributedResourceFetch", true);

            // Select either user manager or scope manager. But not both!!
            // settings.InitUserManager();
            // strScopeID = settings.InitScopeManager(strScopeID, 255);

            // Rely on helper functions to initialize other settings.
            settings.InitEnvironmentVarSettings(true, true);
            settings.DisableCodeSigningValidation(true);
            settings.InitClientBinPersistence(true);

            // Initialize ports for web server and web sockets.
            settings.InitWebPorts(8700, 0);

            MyBaseApplication = new TheBaseApplication();    // Create a new Base (C-DEngine IoT) Application

            if (MyBaseApplication != null)
            {
                // Start the C-DEngine Application. If a PluginService class is added DIRECTLY
                // to the host project you can instantiate the Service here replacing the null
                // with "new cdePluginService1()"
                bResult = MyBaseApplication.StartBaseApplication(null, settings.ArgList);
            }

            return(bResult);
        }
Пример #7
0
        public static bool Start()
        {
            bool bResult = false;

            if (MyBaseApplication == null)
            {
                MyBaseApplication = new TheBaseApplication();    // Create a new Base (C-DEngine IoT) Application
            }
            if (MyBaseApplication != null)
            {
                // Start the C-DEngine Application. If a PluginService class is added DIRECTLY
                // to the host project you can instantiate the Service here replacing the null
                // with "new cdePluginService1()"
                bResult = MyBaseApplication.StartBaseApplication(null, MySettings.ArgList);
                if (bResult)
                {
                    // Select either user manager or scope manager. But not both!!
                    // MySettings.InitUserManager();
                    strScopeID = MySettings.InitScopeManager(strScopeID, 255);
                }
            }

            return(bResult);
        }
Пример #8
0
        static void Main(string[] args)
        {
            Thread.CurrentThread.Name = "Main thread";  // Helps Debugging

            // SDK Non-Commercial ID. FOR COMMERCIAL APP GET THIS ID FROM C-LABS!
            TheScopeManager.SetApplicationID("/cVjzPfjlO;{@QMj:jWpW]HKKEmed[llSlNUAtoE`]G?");

            //
            //  Establish service parameters
            //
            TheBaseAssets.MyServiceHostInfo = new TheServiceHostInfo(cdeHostType.Application)
            {
                // TODO: Generate host service unique ID
                cdeMID = TheCommonUtils.CGuid("<<CREATE WITH GUID TOOL>>"),

                // TCP/IP Port Assignments
                MyStationPort = 80,                                  // Port for REST access to this node.
                                                                     // If your PC already uses port 80 for another webserver, change this port.
                                                                     // We recommend using Port 8700 and higher for UPnP to work properly.

                MyStationWSPort = 81,                                // Enables WebSockets on the station port.
                                                                     // If UseRandomDeviceID is false, this Value cannot be changed here once the
                                                                     // app runs for the first time.
                                                                     // On Windows 8 and later, MyStationPort and MyStationWSPort
                                                                     // can be the same port if running as Administrator.

                IgnoreAdminCheck = true,                             // If false, the host requires admin priviledges to start

                ISMMainExecutable = "__safeprojectname__",           // Name of the executable (without .exe)
                ApplicationName   = "My-Relay",                      // Friendly Name of Application
                Title             = "My-Relay (c) C-Labs 2013-2019", // Title of this Host Service
                ApplicationTitle  = "My-Relay Portal",               // Title visible in the NMI Portal

                LocalServiceRoute = "LOCALHOST",                     // Will be replaced by the full DNS name of the host during startup.
                SiteName          = "http://cloud.c-labs.com",       // Link to the main Cloud Node of this host.
                                                                     // Not required, for documentation only

                CurrentVersion = 1.0001,                             // Service version of this Service.
                                                                     // Increase when you publish a new version so the
                                                                     // online store can display the correct update icon
                DebugLevel = eDEBUG_LEVELS.OFF,                      // Define a DebugLevel for the SystemLog output.
            };

            // Generate random Scope ID every time we run.
            strScope = TheScopeManager.GenerateNewScopeID();     // TIP: instead of creating a new random ID every
                                                                 // time your host starts, you can put a breakpoint in the
                                                                 // next line, record the ID and feed it in the "SetScopeIDFromEasyID".
                                                                 // Or even set a fixed ScopeID here. (FOR TESTING ONLY!!)

            TheScopeManager.SetScopeIDFromEasyID(strScope);      // Set a ScopeID - the security context of this node.
                                                                 // Replace strScope with any random 8 characters or numbers

            //
            // Create dictionary to hold configuration settings.
            //
            ArgList = new Dictionary <string, string>();
            for (int i = 0; i < args.Length; i++)
            {
                string[] tArgs = args[i].Split('=');      // Read config settings from command line
                if (tArgs.Length == 2)
                {
                    string key = tArgs[0].ToUpper();
                    ArgList[key] = tArgs[1];
                }
            }

            ArgList.Add("DontVerifyTrust", "True");       // When "false", all plugins have to be signed with the
                                                          // same certificate as the host application or C-DEngine.DLL.
                                                          // When "true", ignore code signing security check (dev only!)

            ArgList.Add("UseRandomDeviceID", "true");     // When "true", assigns a new device ID everytime
                                                          // the host starts. No configuration data retained on disk.
                                                          // When "false", enables persistence between system starts

            ArgList.Add("ScopeUserLevel", "255");         // Set the Scope Access Level

            // Create a new Base (C-DEngine IoT) Application
            MyBaseApplication = new TheBaseApplication();

            // Start the C-DEngine Host Application.
            // If a PluginService class is added DIRECTLY to the host project you can
            // instantiate the Service here. Replace null with "new cdePluginService1()"
            if (!MyBaseApplication.StartBaseApplication(null, ArgList))
            {
                // If the Application fails to start, quit the app.
                // StartBaseApplication returns very fast because all
                // C-DEngine code is running asynchronously
                return;
            }

            // MyBaseApplication.MyCommonDisco.RegisterUPnPUID("*", null);  // (Optional) Whether to use Universal Plug
            // and Play (UPnP) to find devices

            // Set up URL for our node.
            string strStationURL = TheBaseAssets.MyServiceHostInfo.GetPrimaryStationURL(false);

            strStationURL = String.Format("{0}/nmi", strStationURL);

            // User input loop
            while (true)
            {
                Console.WriteLine("\r\nStation URL: " + strStationURL);
                Console.WriteLine("\r\nScope ID: " + strScope);
                Console.WriteLine("\r\n[Esc] key to quit. 'B' (or 'b') to launch browser");
                ConsoleKeyInfo key = Console.ReadKey();
                if (key.Key == ConsoleKey.Escape)
                {
                    break;
                }
                if (key.KeyChar == 'b' || key.KeyChar == 'B')
                {
                    try
                    {
                        System.Diagnostics.Process.Start(strStationURL);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Error launching browser {0}", e);
                    }
                }
            }
            MyBaseApplication.Shutdown(true);
        }
Пример #9
0
        void StartCDEngineHost()
        {
            // SDK Non-Commercial ID. FOR COMMERCIAL APP GET THIS ID FROM C-LABS!
            TheScopeManager.SetApplicationID("/cVjzPfjlO;{@QMj:jWpW]HKKEmed[llSlNUAtoE`]G?");

            //
            //  Establish service parameters
            //
            TheBaseAssets.MyServiceHostInfo = new TheServiceHostInfo(cdeHostType.Device)
            {
                // TODO: Generate host service unique ID
                cdeMID = TheCommonUtils.CGuid("5872AA06-0EAD-4A07-89B9-CC9D632FC50C"),

                IgnoreAdminCheck = true,                             // If false, the host requires admin priviledges to start

                ISMMainExecutable = "ChatClientWPF",                 // Name of the executable (without .exe)
                ApplicationName   = "My-ChatClient",                 // Friendly Name of Application
                Title             = "My-Relay (c) C-Labs 2013-2019", // Title of this Host Service
                ApplicationTitle  = "My-Relay Portal",               // Title visible in the NMI Portal

                LocalServiceRoute = "LOCALHOST",                     // Will be replaced by the full DNS name of the host during startup.
                SiteName          = "http://cloud.c-labs.com",       // Link to the main Cloud Node of this host.
                                                                     // Not required, for documentation only

                CurrentVersion = 1.0001,                             // Service version of this Service.
                                                                     // Increase when you publish a new version so the
                                                                     // online store can display the correct update icon
                DebugLevel        = eDEBUG_LEVELS.VERBOSE,           // Define a DebugLevel for the SystemLog output.
                CloudServiceRoute = strCloudServiceRoute,
            };

            //
            // Create dictionary to hold configuration settings.
            //
            ArgList = new Dictionary <string, string>();

            ArgList.Add("DontVerifyTrust", "True");       // When "false", all plugins have to be signed with the
                                                          // same certificate as the host application or C-DEngine.DLL.
                                                          // When "true", ignore code signing security check (dev only!)

            ArgList.Add("UseRandomDeviceID", "true");     // When "true", assigns a new device ID everytime
                                                          // the host starts. No configuration data retained on disk.
                                                          // When "false", enables persistence between system starts

            ArgList.Add("ScopeUserLevel", "255");         // Set the Scope Access Level

            // Create a new Base (C-DEngine IoT) Application
            MyBaseApplication = new TheBaseApplication();

            // Start the C-DEngine Host Application.
            // If a PluginService class is added DIRECTLY to the host project you can
            // instantiate the Service here. Replace null with "new cdePluginService1()"
            if (!MyBaseApplication.StartBaseApplication(null, ArgList))
            {
                // If the Application fails to start, quit the app.
                // StartBaseApplication returns very fast because all
                // C-DEngine code is running asynchronously
                MessageBox.Show("Failed to start CDEngine.");
                return;
            }

            // Generate random Scope ID every time we run.
            //strScope = TheScopeManager.GenerateNewScopeID();     // TIP: instead of creating a new random ID every
            // time your host starts, you can put a breakpoint in the
            // next line, record the ID and feed it in the "SetScopeIDFromEasyID".
            // Or even set a fixed ScopeID here. (FOR TESTING ONLY!!)

            TheScopeManager.SetScopeIDFromEasyID(strScope);      // Set a ScopeID - the security context of this node.
                                                                 // Replace strScope with any random 8 characters or numbers



            Task.Delay(-1, TheBaseAssets.MasterSwitchCancelationToken).ContinueWith((t) =>
            {
                MessageBox.Show("CDEngine is shutting down.");
            });

            // MyBaseApplication.MyCommonDisco.RegisterUPnPUID("*", null);  // (Optional) Whether to use Universal Plug
            // and Play (UPnP) to find devices

            // Set up URL for our node.
            string strStationURL = TheBaseAssets.MyServiceHostInfo.GetPrimaryStationURL(false);

            strStationURL = String.Format("{0}/nmi", strStationURL);
        }
Пример #10
0
        static public bool StartHost()
        {
            // TODO Figure out how to launch multiple hosts without killing the process
            lock (appStartLock)
            {
                if (Interlocked.Increment(ref activeHosts) != 1)
                {
                    TestContext.Out.WriteLine($"{DateTimeOffset.Now} Not starting host: already running");
                    return(false);
                }
                else
                {
                    TestContext.Out.WriteLine($"{DateTimeOffset.Now} Starting host");
                }

                if (TheBaseAssets.MyApplication != null)
                {
                    TestContext.Out.WriteLine($"{DateTimeOffset.Now} Host already started");
                    return(false);
                }

                //Assert.IsTrue(TheBaseAssets.MyApplication == null, "Not starting test host: BaseApplication already created.");

                TheScopeManager.SetApplicationID("/cVjzPfjlO;{@QMj:jWpW]HKKEmed[llSlNUAtoE`]G?"); //SDK Non-Commercial ID. FOR COMMERCIAL APP GET THIS ID FROM C-LABS!

                ushort port = 8716;
                // MSTest does not stop the Net3.5 host before starting the Net4.5 host, so need to use different ports
                var connections = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners();
                while (connections.FirstOrDefault(c => c.Port == port) != null)
                {
                    port += 2;
                }


                TheBaseAssets.MyServiceHostInfo = new TheServiceHostInfo(cdeHostType.Application)
                {
                    ApplicationName  = "My-Relay",                      //Friendly Name of Application
                    cdeMID           = Guid.NewGuid(),                  //TODO: Give a Unique ID to this Host Service
                    Title            = "My-Relay (C) C-Labs 2013-2017", //Title of this Host Service
                    ApplicationTitle = "My-Relay Portal",               //Title visible in the NMI Portal
                    CurrentVersion   = 1.0001,                          //Version of this Service, increase this number when you publish a new version that the store displays the correct update icon
                    DebugLevel       = eDEBUG_LEVELS.ESSENTIALS,        //Define a DebugLevel for the SystemLog output.
                    SiteName         = "http://cloud.c-labs.com",       //Link to the main Cloud Node of this host. this is not required and for documentation only

                    ISMMainExecutable = "OPCUAClientUnitTest",          //Name of the executable (without .exe)

                    LocalServiceRoute = "LOCALHOST",                    //Will be replaced by the full DNS name of the host during startup.

                    MyStationPort   = port,                             //Port for REST access to this Host node. If your PC already uses port 80 for another webserver, change this port. We recommend using Port 8700 and higher for UPnP to work properly.
                    MyStationWSPort = (ushort)(port + 1),               //Enables WebSockets on the station port. If UseRandomDeviceID is false, this Value cannot be changed here once the App runs for the first time. On Windows 8 and higher running under "Adminitrator" you can use the same port
                };

                #region Args Parsing
                Dictionary <string, string> ArgList = new Dictionary <string, string>();

                // TODO Get this from the text context?
                //for (int i = 0; i < args.Length; i++)
                //{
                //    string[] tArgs = args[i].Split('=');
                //    if (tArgs.Length == 2)
                //    {
                //        string key = tArgs[0].ToUpper();
                //        ArgList[key] = tArgs[1];
                //    }
                //}
                #endregion

                ArgList.Add("DontVerifyTrust", "True");                                          //NEW: 3.2 If this is NOT set, all plugins have to be signed with the same certificate as the host application or C-DEngine.DLL

                ArgList.Add("UseRandomDeviceID", "true");                                        //ATTENTION: ONLY if you set this to false, some of these parameters will be stored on disk and loaded at a later time. "true" assigns a new node ID everytime the host starts and no configuration data will be cached on disk.
                ArgList.Add("ScopeUserLevel", "255");                                            //Set the Scope Access Level
                ArgList.Add("AROLE", eEngineName.NMIService + ";" + eEngineName.ContentService); //Make NMI and Content Service known to this host
                ArgList.Add("SROLE", eEngineName.NMIService + ";" + eEngineName.ContentService); //Add NMI and Content Service as Service to run on this host. If you omit these entries, this host will become an end-node (not able to relay) and will try to find a proper relay node to talk to.
                string tScope = TheScopeManager.GenerateNewScopeID();                            //TIP: instead of creating a new random ID every time your host starts, you can put a breakpoint in the next line, record the ID and feed it in the "SetScopeIDFromEasyID". Or even set a fixed ScopeID here. (FOR TESTING ONLY!!)
                TestContext.Out.WriteLine("Current Scope:" + tScope);
                TheScopeManager.SetScopeIDFromEasyID(tScope);                                    //Set a ScopeID - the security context of this node. You can replace tScope with any random 8 characters or numbers
                MyBaseApplication = new TheBaseApplication();                                    //Create a new Base (C-DEngine IoT) Application

                //TheBaseAssets.MasterSwitch = false;
                var appStarted = MyBaseApplication.StartBaseApplication(null, ArgList);

                Assert.IsTrue(appStarted, "Failed to StartBaseApplication");         //Start the C-DEngine Application. If a PluginService class is added DIRECTLY to the host project you can instantiate the Service here replacing the null with "new cdePluginService1()"
                                                                                     //If the Application fails to start, quit the app. StartBaseApplication returns very fast as all the C-DEngine code is running asynchronously
                                                                                     //MyBaseApplication.MyCommonDisco.RegisterUPnPUID("*", null);     //Only necessary if UPnP is used to find devices

                bool started           = false;
                var  engineStartedTask = TheBaseEngine.WaitForEnginesStartedAsync();
                if (engineStartedTask.Wait(20000))
                {
                    started = engineStartedTask.Result;
                    Assert.IsTrue(started, "Failed to start engines");
                }
                else
                {
                    ///Assert.IsTrue(started, "Failed to start engines (timeout)");
                    TestContext.Out.WriteLine("Failed to start engines (timeout)");
                }
                AppDomain.CurrentDomain.DomainUnload += OnDomainUnload;
            }
            myContentService = TheThingRegistry.GetBaseEngineAsThing(eEngineName.ContentService);
            Assert.IsNotNull(myContentService);
            TestContext.Out.WriteLine("{DateTimeOffset.Now} Host started");
            return(true);
        }
Пример #11
0
        static void Main(string[] args)
        {
            Thread.CurrentThread.Name = "Main thread";  // Helps Debugging

            //SDK Non-Commercial ID. FOR COMMERCIAL APP GET THIS ID FROM C-LABS!
            TheScopeManager.SetApplicationID("/cVjzPfjlO;{@QMj:jWpW]HKKEmed[llSlNUAtoE`]G?");

            //
            //  Establish service parameters
            //
            TheBaseAssets.MyServiceHostInfo = new TheServiceHostInfo(cdeHostType.Application)
            {
                // TODO: Generate host service unique ID
                cdeMID = TheCommonUtils.CGuid("{65CB9142-7D26-40E4-AE54-3E4DD75B3760}"),

                // TCP/IP Port Assignments
                MyStationPort = 8720,                     // Port for REST access to this node.
                                                          // If your PC already uses port 80 for another webserver, change this port.
                                                          // We recommend using Port 8700 and higher for UPnP to work properly.

                MyStationWSPort = 8721,                   // Enables WebSockets on the station port.
                                                          // If UseRandomDeviceID is false, this Value cannot be changed here once the
                                                          // app runs for the first time.
                                                          // On Windows 8 and later, MyStationPort and MyStationWSPort
                                                          // can be the same port if running as Administrator.

                ISMMainExecutable = "MyTestHost2",        // Name of the executable (without .exe)
                ApplicationName   = "My-Relay",           // Friendly Name of Application
                Title             = "My-Relay (C) 2020 ", // Title of this Host Service
                ApplicationTitle  = "My-Relay Portal",    // Title visible in the NMI Portal

                SiteName = "http://cloud.c-labs.com",     // Link to the main Cloud Node of this host.
                                                          // Not required, for documentation only

                CurrentVersion = 1.0001,                  // Service version of this Service.
                                                          // Increase when you publish a new version so the
                                                          // online store can display the correct update icon
                DebugLevel   = eDEBUG_LEVELS.OFF,         // Define a DebugLevel for the SystemLog output.
                ServiceRoute = "wss://cloud.c-labs.com",  // Points at the cloud
            };

            // Generate random Scope ID every time we run.
            strScope = TheScopeManager.GenerateNewScopeID();   // TIP: instead of creating a new random ID every
                                                               // time your host starts, you can put a breakpoint in the
                                                               // next line, record the ID and feed it in the "SetScopeIDFromEasyID".
                                                               // Or even set a fixed ScopeID here. (FOR TESTING ONLY!!)

            TheScopeManager.SetScopeIDFromEasyID("1234");      // Set a ScopeID - the security context of this node.
                                                               // Replace strScope with any random 8 characters or numbers

            //
            // Create dictionary to hold configuration settings.
            //
            #region Args Parsing
            ArgList = new Dictionary <string, string>();
            for (int i = 0; i < args.Length; i++)
            {
                string[] tArgs = args[i].Split('=');
                if (tArgs.Length == 2)
                {
                    string key = tArgs[0].ToUpper();
                    ArgList[key] = tArgs[1];
                }
            }
            #endregion

            ArgList["DontVerifyTrust"] = "True";       // When "false", all plugins have to be signed with the
                                                       // same certificate as the host application or C-DEngine.DLL.
                                                       // When "true", ignore code signing security check (dev only!)

            ArgList["UseRandomDeviceID"] = "True";     // When "true", assigns a new device ID everytime
                                                       // the host starts. No configuration data retained on disk.
                                                       // When "false", enables persistence between system starts

            ArgList["ScopeUserLevel"] = "255";         // Set the Scope Access Level

            // Create a new Base (C-DEngine IoT) Application
            MyBaseApplication = new TheBaseApplication();

            // Start the C-DEngine Host Application.
            // If a PluginService class is added DIRECTLY to the host project you can
            // instantiate the Service here. Replace null with "new cdePluginService1()"
            if (!MyBaseApplication.StartBaseApplication(null, ArgList))
            {
                // If the Application fails to start, quit the app.
                // StartBaseApplication returns very fast because all
                // C-DEngine code is running asynchronously
                return;
            }

            // (Optional) Whether to use Universal Plug
            // and Play (UPnP) to find devices.
            // MyBaseApplication.MyCommonDisco.RegisterUPnPUID("*", null);

            // Set up URL for our node.
            string strStationURL = TheBaseAssets.MyServiceHostInfo.GetPrimaryStationURL(false);
            strStationURL = String.Format("{0}/lnmi", strStationURL);

            // Set up messaging (for basic sample)
            TheCDEngines.RegisterPubSubTopic("MyTestEngine");                    // The engine for MyTestHost
            IBaseEngine eng = TheCDEngines.RegisterPubSubTopic("MyTestEngine2"); // The engine for THIS host
            eng.RegisterEvent(eEngineEvents.IncomingMessage, HandleMessage);

            #region Waiting for ESC Key pressed
            try
            {
                // User input loop
                while (true)
                {
                    Console.WriteLine("\r\nStation URL: " + strStationURL);
                    Console.WriteLine("\r\nScope ID: " + strScope);
                    Console.WriteLine("\r\n[Esc] key to quit. 'B' (or 'b') to launch browser");

                    // Loop until (1) C-DEngine master switch, or (2) Keyboard input
                    while (TheBaseAssets.MasterSwitch && Console.KeyAvailable == false) // Console.KeyAvailable throws exception in Docker
                    {
                        Thread.Sleep(250);
                    }

                    // Check C-DEngine master switch.
                    if (!TheBaseAssets.MasterSwitch)
                    {
                        // Exit user input loop.
                        break;
                    }

                    ConsoleKeyInfo key = Console.ReadKey();
                    if (key.Key == ConsoleKey.Escape)
                    {
                        break;
                    }
                    if (key.KeyChar == 'b' || key.KeyChar == 'B')
                    {
                        try
                        {
                            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                            {
                                strStationURL = strStationURL.Replace("&", "^&");
                                Process.Start(new ProcessStartInfo("cmd.exe", $"/c start {strStationURL}")
                                {
                                    CreateNoWindow = true
                                });
                            }
                            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                            {
                                System.Diagnostics.Process.Start("xdg-open", strStationURL);
                            }
                            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                            {
                                System.Diagnostics.Process.Start("open", strStationURL);
                            }
                            else
                            {
                                Console.WriteLine($"Error launching browser for URL {strStationURL}");
                            }
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine($"Error launching browser for URL {strStationURL}");
                            Console.WriteLine($"Exception details: {e.ToString()}");
                        }
                    }
                } // while (true)
            }
            catch (InvalidOperationException)
            {
                TheBaseAssets.MasterSwitchCancelationToken.WaitHandle.WaitOne();
            }

            MyBaseApplication.Shutdown(true);
            #endregion
        }
Пример #12
0
        static void Main(string[] args)
        {
            Console.Title = "SAF CDE Test Host with SAF Plugin";

            Thread.CurrentThread.Name = "Main thread";

            var settings = ConfigurationManager.AppSettings.AllKeys.ToDictionary(key => key, key => ConfigurationManager.AppSettings[key]);

            AssignConfigValue(settings, "ApplicationID", value => TheScopeManager.SetApplicationID(value));

            TheBaseAssets.MyServiceHostInfo = new TheServiceHostInfo(cdeHostType.Application)
            {
                Title             = GetConfigValue(settings, "ApplicationTitle"),
                ApplicationName   = GetConfigValue(settings, "ApplicationName"),
                ApplicationTitle  = GetConfigValue(settings, "PortalTitle"),
                DebugLevel        = GetDebugLevel(settings, "DebugLevel", eDEBUG_LEVELS.ESSENTIALS),
                MyStationPort     = Convert.ToUInt16(GetConfigValue(settings, "HTTPPort")),
                MyStationWSPort   = Convert.ToUInt16(GetConfigValue(settings, "WSPort")),
                cdeMID            = TheCommonUtils.CGuid(GetConfigValue(settings, "StorageID")),
                FailOnAdminCheck  = Convert.ToBoolean(GetConfigValue(settings, "FailOnAdminCheck")),
                CloudServiceRoute = GetConfigValue(settings, "CloudServiceRoutes"),
                LocalServiceRoute = GetConfigValue(settings, "LocalServiceRoutes"),
                IsCloudService    = Convert.ToBoolean(GetConfigValue(settings, "IsCloudService")),
                ISMMainExecutable = "Host",
                CurrentVersion    = 1.0001,
                AllowLocalHost    = Convert.ToBoolean(GetConfigValue(settings, "AllowLocalHost"))
            };

            TheBaseAssets.MyServiceHostInfo.IgnoredEngines.AddRange(GetConfigValue(settings, "LogIgnore").Split(';'));

            Debug.WriteLine($"Ports: {TheBaseAssets.MyServiceHostInfo.MyStationWSPort}/{TheBaseAssets.MyServiceHostInfo.MyStationPort}");

            var arguments = new Dictionary <string, string>
            {
                { "DontVerifyTrust", $"{Convert.ToBoolean(GetConfigValue(settings, "DontVerifyTrust"))}" },
                { "UseUserMapper", $"{Convert.ToBoolean(GetConfigValue(settings, "UseUserMapper"))}" },
                { "UseRandomDeviceID", $"{Convert.ToBoolean(GetConfigValue(settings, "UseRandomDeviceID"))}" },
                { "AROLE", eEngineName.NMIService + ";" + eEngineName.ContentService },
                { "SROLE", eEngineName.NMIService + ";" + eEngineName.ContentService }
            };

            var scopeId = ConfigurationManager.AppSettings["ScopeID"];

            if (!string.IsNullOrEmpty(scopeId))
            {
                if (scopeId.Length == 8)
                {
                    Console.WriteLine("Current Scope:" + scopeId);
                    TheScopeManager.SetScopeIDFromEasyID(scopeId);
                }
            }

            var app = new TheBaseApplication();

            if (!app.StartBaseApplication(null, arguments))
            {
                return;
            }

            while (true)
            {
                var key = Console.ReadKey();
                if (key.Key == ConsoleKey.Escape)
                {
                    break;
                }
            }

            app.Shutdown(false, true);
        }
Пример #13
0
        private async Task <TheBaseApplication> StartCde(CdeConfiguration config)
        {
            try
            {
                LoadAlternateCryptoLib(config.CryptoLibConfig);

                TheScopeManager.SetApplicationID(config.ApplicationId);

                TheBaseAssets.MyServiceHostInfo = new TheServiceHostInfo(cdeHostType.Application)
                {
                    Title             = config.ApplicationTitle,
                    ApplicationName   = config.ApplicationName,
                    ApplicationTitle  = config.PortalTitle,
                    DebugLevel        = GetDebugLevel(config.DebugLevel, eDEBUG_LEVELS.ESSENTIALS),
                    MyStationPort     = config.HttpPort,
                    MyStationWSPort   = config.WsPort,
                    cdeMID            = TheCommonUtils.CGuid(config.StorageId),
                    FailOnAdminCheck  = config.FailOnAdminCheck,
                    CloudServiceRoute = config.CloudServiceRoutes,
                    LocalServiceRoute = config.LocalServiceRoutes,
                    IsCloudService    = config.IsCloudService,
                    ISMMainExecutable = Assembly.GetEntryAssembly()?.GetName().Name,
                    CurrentVersion    = config.ApplicationVersion,
                    AllowLocalHost    = config.AllowLocalHost,
                    PreShutDownDelay  = config.PreShutdownDelay
                };

                TheBaseAssets.MyServiceHostInfo.IgnoredEngines.AddRange(config.LogIgnore.Split(';'));
                IDictionary <string, string> arguments = new Dictionary <string, string>
                {
                    { "DontVerifyTrust", $"{config.DontVerifyTrust}" },
                    { "UseUserMapper", $"{config.UseUserMapper}" },
                    { "UseRandomDeviceID", $"{config.UseRandomDeviceId}" },
                    { "AROLE", eEngineName.NMIService + ";" + eEngineName.ContentService },
                    { "SROLE", eEngineName.NMIService + ";" + eEngineName.ContentService }
                };

                if (!string.IsNullOrEmpty(config.ScopeId))
                {
                    arguments["EasyScope"] = config.ScopeId;
                }

                arguments = MergeDictionaries(arguments, config.AdditionalArguments);

                var app       = new TheBaseApplication();
                var startTime = DateTimeOffset.UtcNow;
                if (!app.StartBaseApplication(null, arguments))
                {
                    throw new InvalidOperationException("Failed to start CDE base application!");
                }

                if (config.UseRandomScopeId && string.IsNullOrEmpty(TheScopeManager.GetScrambledScopeID()))
                {
                    if (!TheScopeManager.SetScopeIDFromEasyID(TheScopeManager.GenerateNewScopeID()))
                    {
                        throw new InvalidOperationException("Failed to apply random scope!");
                    }
                }

                _log.LogDebug("Started CDE Base application after {milliseconds} ms", DateTimeOffset.UtcNow.Subtract(startTime).TotalMilliseconds);
                startTime = DateTimeOffset.UtcNow;

                await TheBaseEngine.WaitForEnginesStartedAsync();

                _log.LogDebug("Started CDE engines after {milliseconds} ms", DateTimeOffset.UtcNow.Subtract(startTime).TotalMilliseconds);
                startTime = DateTimeOffset.UtcNow;

                await TheBaseEngine.WaitForStorageReadinessAsync(true);

                _log.LogDebug("Started CDE Storage after {milliseconds} ms", DateTimeOffset.UtcNow.Subtract(startTime).TotalMilliseconds);

                return(app);
            }
            catch (Exception ex)
            {
                _log.LogCritical(ex, "Failed to start CDE");
                throw;
            }
        }
Пример #14
0
        static void Main(string[] args)
        {
            Thread.CurrentThread.Name = "Main thread";                                        //Helps Debugging

            TheScopeManager.SetApplicationID("/cVjzPfjlO;{@QMj:jWpW]HKKEmed[llSlNUAtoE`]G?"); //SDK Non-Commercial ID. FOR COMMERCIAL APP GET THIS ID FROM C-LABS!

            TheBaseAssets.MyServiceHostInfo = new TheServiceHostInfo(cdeHostType.Application)
            {
                ApplicationName  = "My-Relay",                                                     //Friendly Name of Application
                cdeMID           = TheCommonUtils.CGuid("{5BD695B9-C545-4966-8342-E26FC168C7D1}"), //TODO: Give a Unique ID to this Host Service
                Title            = "My-Relay",                                                     //Title of this Host Service
                ApplicationTitle = "My-Relay Portal",                                              //Title visible in the NMI Portal
                DebugLevel       = eDEBUG_LEVELS.OFF,                                              //Define a DebugLevel for the SystemLog output. the higher the more output

                ISMMainExecutable = "SDKTestRelay",                                                //Name of the executable (without .exe)

                //CloudServiceRoute = "wss://cloud.c-labs.com",                 //try it with cloud access
                MyStationPort   = 8713,                                         //Port for REST access to this Host node. If your PC already uses port 80 for another webserver, change this port. We recommend using Port 8700 and higher for UPnP to work properly.
                MyStationWSPort = 8713,                                         //Enables WebSockets on the station port. If UseRandomDeviceID is false, this Value cannot be changed here once the App runs for the first time. On Windows 8 and higher running under "Adminitrator" you can use the same port
            };

            #region Args Parsing
            Dictionary <string, string> ArgList = new Dictionary <string, string>();
            for (int i = 0; i < args.Length; i++)
            {
                string[] tArgs = args[i].Split('=');
                if (tArgs.Length == 2)
                {
                    string key = tArgs[0].ToUpper();
                    ArgList[key] = tArgs[1];
                }
            }
            #endregion

            ArgList.Add("AllowRemoteISBConnect", "true");       //Allows connect from CORS offline/hosted NMI
            ArgList.Add("Access-Control-Allow-Origin", "*");    //Allows CORS access from other domains
            ArgList.Add("DontVerifyTrust", "true");             //No Code Signing check
            ArgList.Add("UseRandomDeviceID", "false");          //Set to true if you dont want to store anything - no settings, ThingRegistry or cache values- on the harddrive
            ArgList.Add("ShowSamples", "true");                 //Show all samples in Plugins
            ArgList.Add("ScopeUserLevel", "255");               //Give logged user the user-level 255 (admin)
            ArgList.Add("EnableKPIs", "true");                  //Enable KPI collection
            ArgList.Add("TokenLifeTime", "180");                //Allow to refresh the browser for 180 seconds

            //Also keep in mind that setting can be overwritten in the App.Config

            TheBaseApplication MyBaseApplication = new TheBaseApplication();    //Create a new Base (C-DEngine IoT) Application
            TheCDEngines.eventAllEnginesStarted += sinkReady;
            if (!MyBaseApplication.StartBaseApplication(null, ArgList))         //Start the C-DEngine Application. If a PluginService class is added DIRECTLY to the host project you can instantiate the Service here replacing the null with "new cdePluginService1()"
            {
                return;                                                         //If the Application fails to start, quit the app. StartBaseApplication returns very fast as all the C-DEngine code is running asynchronously
            }
            //MyBaseApplication.MyCommonDisco.RegisterUPnPUID("*", null);     //Only necessary if UPnP is used to find devices
            string strScope = TheScopeManager.GenerateNewScopeID();               //TIP: instead of creating a new random ID every time your host starts, you can put a breakpoint in the next line, record the ID and feed it in the "SetScopeIDFromEasyID". Or even set a fixed ScopeID here. (FOR TESTING ONLY!!)
            Console.WriteLine($"=======> Node Scope : {strScope}");
            TheScopeManager.SetScopeIDFromEasyID(strScope);                       //Set a ScopeID - the security context of this node. You can replace tScope with any random 8 characters or numbers

            #region Waiting for ESC Key pressed
            string strStationURL = TheBaseAssets.MyServiceHostInfo.GetPrimaryStationURL(false);
            strStationURL = String.Format("{0}/nmi", strStationURL);
            // User input loop
            while (true)
            {
                Console.WriteLine("\r\nStation URL: " + strStationURL);
                Console.WriteLine("\r\nScope ID: " + strScope);
                Console.WriteLine("\r\n[Esc] key to quit. 'B' (or 'b') to launch browser");
                ConsoleKeyInfo key = Console.ReadKey();
                if (key.Key == ConsoleKey.Escape)
                {
                    break;
                }
                if (key.KeyChar == 'b' || key.KeyChar == 'B')
                {
                    try
                    {
                        ProcessStartInfo psi = new ProcessStartInfo(strStationURL);
                        psi.UseShellExecute = true;
                        Process.Start(psi);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Error launching browser {0}", e);
                    }
                }
            }
            MyBaseApplication.Shutdown(true);
            #endregion
        }