public static bool Init(string strGuid, string strUserScopeID, string strAppID) { TheScopeManager.SetApplicationID(strAppID); // SDK Non-Commercial ID. FOR COMMERCIAL APP GET THIS ID FROM C-LABS! TheBaseAssets.MyServiceHostInfo = new TheServiceHostInfo(cdeHostType.Application) { ApplicationName = "$safeprojectname$", // Friendly Name of Application cdeMID = TheCommonUtils.CGuid(strGuid), Title = "My-Relay (C) $registeredorganization$ $year$", // Title of this Host Service ApplicationTitle = "$safeprojectname$", // 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.OFF, // 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 = "$safeprojectname$", // Name of the executable (without .exe) IgnoreAdminCheck = true, // if set to true, the host will not start if launched without admin priviledges. LocalServiceRoute = "LOCALHOST", // Will be replaced by the full DNS name of the host during startup. MyStationPort = 8700, // 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 = 8701, // 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 }; if (strUserScopeID.Length > 0) { strScopeID = strUserScopeID; } else { strScopeID = 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!!) } return(true); }
bool Initialize() { if (Configuration != null) { TheBaseAssets.MySettings = new TheNetCoreSettings(Configuration); } MyArgList = (Configuration.GetChildren().ToDictionary(x => x.Key, x => x.Value)); UpdateArgList(MyArgList); StartupLog?.Log("Service: Loading C-LabsCryptoLib"); TheBaseAssets.LoadCrypto("C-LabsCryptoLib.dll", StartupLog, MyArgList.ContainsKey("DontVerifyTrust") && CU.CBool(MyArgList["DontVerifyTrust"]), null, MyArgList.ContainsKey("VerifyTrustPath") && CU.CBool(MyArgList["VerifyTrustPath"]), MyArgList.ContainsKey("DontVerifyIntegrity") && CU.CBool(MyArgList["DontVerifyIntegrity"])); if (TheBaseAssets.CryptoLoadMessage != null) { StartupLog?.Log($"Security initialization failed with {TheBaseAssets.CryptoLoadMessage}. Exiting..."); return(false); } StartupLog?.Log("Service: Setting apid"); if (!TheScopeManager.SetApplicationID(ServiceApplicationID)) { StartupLog?.Log("Application ID Illegal...exiting"); return(false); } StartupLog?.Log("Service: Creating service host"); TheBaseAssets.MyServiceHostInfo = new TheServiceHostInfo(m_hostType) { CurrentVersion = CU.GetAssemblyVersion(this), DebugLevel = eDEBUG_LEVELS.OFF, UPnPIcon = "iconTopLogo.png", LocalServiceRoute = "LOCALHOST", }; TheBaseAssets.MyServiceHostInfo.TO.HeartBeatRate = 3; TheBaseAssets.MyServiceHostInfo.StatusColors = ";#65bb00;orange"; TheBaseAssets.MyServiceHostInfo.ApplicationName = "Factory-Relay"; UpdateServiceHostInfo(TheBaseAssets.MyServiceHostInfo); if (m_hostType == cdeHostType.Application) { TheBaseAssets.MyServiceHostInfo.AddManifestFiles(new List <string> { TheBaseAssets.MyServiceHostInfo.ISMMainExecutable, "C-DEngine.dll", "C-DMyNMIHtml5.dll" }); } StartupLog?.Log("Service: Created service host"); return(true); }
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!"); } }
public static bool Init(string strGuid, string strUserScopeID, string strAppID) { TheScopeManager.SetApplicationID(strAppID); // SDK Non-Commercial ID. FOR COMMERCIAL APP GET THIS ID FROM C-LABS! TheBaseAssets.MyServiceHostInfo = new TheServiceHostInfo(cdeHostType.Application) { ApplicationName = "AppHostTest", // Friendly Name of Application cdeMID = TheCommonUtils.CGuid(strGuid), Title = "My-Relay (C) 2019", // Title of this Host Service ApplicationTitle = "AppHostTest", // 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 SiteName = "http://cloud.c-labs.com", // Link to the main Cloud Node of this host. this is not required and for documentation only ISMMainExecutable = "AppHostTest", // Name of the executable (without .exe) ServiceRoute = "https://cloud.c-labs.com", }; strScopeID = strUserScopeID; settings = new TheBaseAppSettings(); // Directly add keys to settings table. settings.AddKey("UseTcpListenerInsteadOfHttpListener", true); settings.SetKeyUnlessAlreadySet("DEBUGLEVEL", eDEBUG_LEVELS.OFF); // 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(false); // Initialize ports for web server and web sockets. settings.InitWebPorts(8720, 8721); return(true); }
public static bool Init(string strGuid, string strUserScopeID) { TheScopeManager.SetApplicationID(strAppID); // SDK Non-Commercial ID. FOR COMMERCIAL APP GET THIS ID FROM C-LABS! TheBaseAssets.MyServiceHostInfo = new TheServiceHostInfo(cdeHostType.Application) { ApplicationName = "AppHostTest", // Friendly Name of Application cdeMID = TheCommonUtils.CGuid(strGuid), Title = "My-Relay (C) 2019", // Title of this Host Service ApplicationTitle = "AppHostTest", // 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 SiteName = "http://cloud.c-labs.com", // Link to the main Cloud Node of this host. this is not required and for documentation only ISMMainExecutable = "AppHostTest", // Name of the executable (without .exe) // CloudServiceRoute = "https://cloud.c-labs.com", MyStationWSPort = 0, }; strScopeID = strUserScopeID; return(true); }
public static bool Init(string strGuid, string strUserScopeID, string strAppID, ushort usPort, string strCloudServiceRoute, bool bEnableRest, bool bEnableMeshRequest, bool bEnableMeshResponse) { TheScopeManager.SetApplicationID(strAppID); // SDK Non-Commercial ID. FOR COMMERCIAL APP GET THIS ID FROM C-LABS! TheBaseAssets.MyServiceHostInfo = new TheServiceHostInfo(cdeHostType.Application) { ApplicationName = "AppHostTest", // Friendly Name of Application cdeMID = TheCommonUtils.CGuid(strGuid), Title = "My-Relay", // Title of this Host Service ApplicationTitle = "AppHostTest", // 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 SiteName = "http://cloud.c-labs.com", // Link to the main Cloud Node of this host. this is not required and for documentation only ISMMainExecutable = "AppHostTest", // Name of the executable (without .exe) }; strScopeID = strUserScopeID; MySettings = new TheBaseAppSettings(); ushort usWsPort = usPort; usWsPort++; // Initialize ports for web server and web sockets. MySettings.InitWebPorts(usPort, usWsPort); MySettings.AddKey("CloudServiceRoute", strCloudServiceRoute); MySettings.AddKey("DontVerifyTrust", "true"); // Web-to-Mesh Settings: // CDMyWebToMeshSample_EnableREST // +++ In CDMyWebToMeshSample plugin, whether to be REST server. MySettings.SetKeyUnlessAlreadySet("CDMyWebToMeshSample_EnableREST", bEnableRest); // CDMyWebToMeshSample_EnableMeshDataQuery // +++ In CDMyWebToMeshSample plugin, whether to look for // requested REST data in other nodes or whether to provide // it locally. MySettings.SetKeyUnlessAlreadySet("CDMyWebToMeshSample_EnableMeshDataQuery", bEnableMeshRequest); // CDMyWebToMeshSample_EnableMeshDataResponse // +++ In CDMyWebToMeshSample plugin, whether to look for // requested REST data in other nodes or whether to provide // it locally. MySettings.SetKeyUnlessAlreadySet("CDMyWebToMeshSample_EnableMeshDataResponse", bEnableMeshResponse); // Directly add keys to settings table. MySettings.SetKeyUnlessAlreadySet("DEBUGLEVEL", eDEBUG_LEVELS.VERBOSE); MySettings.SetKeyUnlessAlreadySet("EventViewerScope", strScopeID); MySettings.SetKeyUnlessAlreadySet("EventViewerMode", "StandardEventViewer"); // Rely on helper functions to initialize other settings. MySettings.InitEnvironmentVarSettings(true, true); MySettings.DisableCodeSigningValidation(true); MySettings.InitClientBinPersistence(false); return(true); }
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); }
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); }
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); }
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 }
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); }
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; } }
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 }