Ejemplo n.º 1
0
 public void Dispose()
 {
     _log.LogInformation("Shutting down CDE...");
     _cdeApp?.Shutdown(false, true);
     _cdeApp?.Dispose();
     _log.LogInformation("...CDE shut down.");
 }
Ejemplo n.º 2
0
        public static bool Stop()
        {
            if (MyBaseApplication != null)
            {
                MyBaseApplication.Shutdown(true);
                MyBaseApplication = null;
                return(true);
            }

            return(false);
        }
Ejemplo n.º 3
0
        public static bool Stop()
        {
            if (MyBaseApplication != null)
            {
                MyBaseApplication.Shutdown(true);
                MyBaseApplication = null;

                // Give C-DEngine time to shutdown.
                System.Threading.Thread.Sleep(1000);
                return(true);
            }

            return(false);
        }
Ejemplo n.º 4
0
 private static void StopHostInternal(bool force)
 {
     lock (appStartLock)
     {
         if (force || Interlocked.Decrement(ref activeHosts) <= 0)
         {
             TestContext.Out.WriteLine($"{DateTimeOffset.Now} Stopping host");
             // TODO Re-creating a host does not work reliably: all unit tests must use the same host (at least for now)
             MyBaseApplication?.Shutdown(true, true);
             TheBaseAssets.MyApplication = null;
         }
         else
         {
             TestContext.Out.WriteLine($"{DateTimeOffset.Now} Not stopping host: other tests still running");
         }
     }
 }
Ejemplo n.º 5
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);
        }
Ejemplo n.º 6
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
        }
Ejemplo n.º 7
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);
        }
Ejemplo n.º 8
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
        }