public static List <ServedDevice> WalkControls(Control TopControl, List <ServedDevice> deviceList) { //ServerForm.LogMessage(0, 0, 0, "WalkControls", $"Top control: {TopControl.Name}"); foreach (Control control in TopControl.Controls) { if (control.HasChildren) { if (control is ServedDevice) { if (int.Parse(control.Name.Substring("ServedDevice".Length)) < ServerForm.MaximumNumberOfDevices) { deviceList.Add(control as ServedDevice); ServerForm.LogMessage(0, 0, 0, "WalkControls", $"Found served device: {control.Name}"); } else { ServerForm.LogMessage(0, 0, 0, "WalkControls", $"Ignoring served device: {control.Name}"); } } else { //ServerForm.LogMessage(0, 0, 0, "WalkControls", $"Found control with children: {x.Name}. Recursing down..."); WalkControls(control, deviceList); } } } return(deviceList); }
/// <summary> /// Send a command to the driver /// </summary> /// <param name="requestData">Details of the command to send</param> /// <returns>Background thread on which the command is executing</returns> public Thread DriverCommand(RequestData requestData) { try // Process the command { Application.DoEvents(); // Process the command on a separate thread allowing other requests to be handled concurrently through this thread, which is running the Windows message loop Thread driverThread = new Thread(new ParameterizedThreadStart(ProcessCommand)); // Create a new thread on which to make the call to the COM driver if (ServerForm.DebugTraceState) { ServerForm.LogMessage1(requestData, requestData.Elements[ServerForm.URL_ELEMENT_METHOD], $"DriverCommand has received a command for {deviceKey} on FORM thread {Thread.CurrentThread.ManagedThreadId} Apartment state: {Thread.CurrentThread.GetApartmentState()} Is background: {Thread.CurrentThread.IsBackground} Is thread pool thread: {Thread.CurrentThread.IsThreadPoolThread}"); } driverThread.Start(requestData); // Start the thread supplying the request data to the method if (ServerForm.DebugTraceState) { ServerForm.LogMessage1(requestData, requestData.Elements[ServerForm.URL_ELEMENT_METHOD], $"DriverCommand has started the command for {deviceKey} on FORM thread { Thread.CurrentThread.ManagedThreadId}"); } return(driverThread); // Return the thread so that the calling method can wait for it to complete and so that this thread can start waiting for the next command } catch (Exception ex) // Something serious has gone wrong with the ASCOM Remote server itself so report this to the user { ServerForm.LogException1(requestData, "DriverCommand", ex.ToString()); restServer.Return500Error(requestData, "Internal server error (DriverOnSeparateThread): " + ex.ToString()); } return(null); }
private void CmbDeviceType_SelectedIndexChanged(object sender, EventArgs e) { try { ServerForm.LogMessage(0, 0, 0, this.Name, "cmbDeviceType_Changed - Clearing items"); cmbDevice.Items.Clear(); ServerForm.LogMessage(0, 0, 0, this.Name, "cmbDeviceType_Changed - Setting selected index to -1"); cmbDevice.SelectedIndex = -1; ServerForm.LogMessage(0, 0, 0, this.Name, "cmbDeviceType_Changed - Resetting instance number"); DeviceNumber = 0; if (cmbDeviceType.SelectedItem.ToString() == SharedConstants.DEVICE_NOT_CONFIGURED) { ServerForm.LogMessage(0, 0, 0, this.Name, "cmbDeviceType_Changed - \"None\" device type selected"); cmbDevice.Items.Clear(); cmbDevice.SelectedIndex = -1; cmbDevice.ResetText(); cmbDevice.Enabled = false; description = ""; progID = SharedConstants.DEVICE_NOT_CONFIGURED; } else { cmbDevice.Enabled = true; ServerForm.LogMessage(0, 0, 0, this.Name, "cmbDeviceType_Changed - Real device type has been selected"); } if (recalculate) { setupForm.RecalculateDeviceNumbers(); recalculate = false; } // Set up device list so we can translate ProgID to description ArrayList installedDevices = profile.RegisteredDevices(cmbDeviceType.SelectedItem.ToString()); ServerForm.LogMessage(0, 0, 0, this.Name, "cmbDeviceType_Changed - Created registered device array list"); deviceDictionary.Clear(); foreach (KeyValuePair kvp in installedDevices) { if (!deviceDictionary.ContainsKey(kvp.Value)) { deviceDictionary.Add(kvp.Key, kvp.Value); } cmbDevice.Items.Add(kvp.Value); } if (cmbDevice.Items.Count > 0) { cmbDevice.SelectedIndex = 0; } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
private void NumMaxDevices_ValueChanged(object sender, EventArgs e) { maxDevicesHasChanged = true; ServerForm.MaximumNumberOfDevices = (int)NumMaxDevices.Value; ServerForm.ReadProfile(); }
/// <summary> /// Called when the user presses the OK button to commit any new set up values /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void BtnOK_Click(object sender, EventArgs e) { if (addressList.Text == SharedConstants.LOCALHOST_NAME) { ServerForm.ServerIPAddressString = SharedConstants.LOCALHOST_ADDRESS; } else { ServerForm.ServerIPAddressString = addressList.Text; } ServerForm.ServerPortNumber = numPort.Value; ServerForm.StartWithDevicesConnected = chkAutoConnect.Checked; ServerForm.AccessLogEnabled = chkAccessLog.Checked; ServerForm.TraceState = chkTrace.Checked; ServerForm.DebugTraceState = chkDebugTrace.Checked; ServerForm.ManagementInterfaceEnabled = chkManagementInterfaceEnabled.Checked; ServerForm.StartWithApiEnabled = ChkStartWithApiEnabled.Checked; ServerForm.RunDriversOnSeparateThreads = ChkRunDriversInSeparateThreadss.Checked; foreach (ServedDevice item in this.Controls.OfType <ServedDevice>()) { ServerForm.ConfiguredDevices[item.Name].DeviceType = item.DeviceType; ServerForm.ConfiguredDevices[item.Name].ProgID = item.ProgID; ServerForm.ConfiguredDevices[item.Name].Description = item.Description; ServerForm.ConfiguredDevices[item.Name].DeviceNumber = item.DeviceNumber; ServerForm.ConfiguredDevices[item.Name].AllowConnectedSetFalse = item.AllowConnectedSetFalse; ServerForm.ConfiguredDevices[item.Name].AllowConnectedSetTrue = item.AllowConnectedSetTrue; } ServerForm.WriteProfile(); this.DialogResult = DialogResult.OK; this.Close(); }
static void Main() { #if !DEBUG // Exclude the unhandled exception handlers from the Debug version so that the application can be debugged in Visual Studio // Add the event handler for handling UI thread exceptions to the event. Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException); // Set the unhandled exception mode to force all Windows Forms errors to go through our handler. Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); // Add the event handler for handling non-UI thread exceptions to the event. AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); #endif Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); ServerForm serverForm = new ServerForm(); Application.Run(serverForm); if (serverForm.RestartApplication) { Application.Restart(); // Restart the application if the network permissions have been changed } #if DEBUG // When debugging, include a log to show the time of close down TraceLogger TL = new TraceLogger("ASCOMRemoteEnded") { Enabled = true }; TL.LogMessage("ASCOMRemoteEnded", "Application has exited"); TL.Enabled = false; TL.Dispose(); TL = null; #endif }
public void RecalculateDeviceNumbers() { // Add a zero entry for each device type on this system deviceNumberIndexes.Clear(); foreach (string device in registeredDeviceTypes) { deviceNumberIndexes.Add(device, 0); } ServerForm.LogMessage(0, 0, 0, "RecalculateDeviceNumbers", "Initialised device numbers"); foreach (string deviceType in registeredDeviceTypes) { ServerForm.LogMessage(0, 0, 0, "RecalculateDeviceNumbers", "Processing device type: " + deviceType); SortedDictionary <string, ServedDevice> servedDevices = new SortedDictionary <string, ServedDevice>(); foreach (ServedDevice c in this.Controls.OfType <ServedDevice>().Where(asd => asd.DeviceType == deviceType)) { servedDevices.Add(c.Name, c); } ServerForm.LogMessage(0, 0, 0, "RecalculateDeviceNumbers", "Added served devices"); Dictionary <string, string> x = new Dictionary <string, string>(); foreach (KeyValuePair <string, ServedDevice> item in servedDevices) { ServerForm.LogMessage(0, 0, 0, "RecalculateDeviceNumbers", "Processing item number: " + item.Value.Name + " "); if (item.Value.DeviceType == deviceType) { ServerForm.LogMessage(0, 0, 0, "RecalculateDeviceNumbers", "Setting " + deviceType + " item number: " + deviceNumberIndexes[deviceType].ToString()); item.Value.DeviceNumber = deviceNumberIndexes[deviceType]; deviceNumberIndexes[deviceType] += 1; } } } }
/// <summary> /// Destroy the driver /// </summary> public void DestroyDriver() { ServerForm.LogMessage(0, 0, 0, "DriverHostForm", "Destroy driver method has been called on thread: " + Thread.CurrentThread.ManagedThreadId); ServerForm.DestroyDriver(deviceKey); ServerForm.LogMessage(0, 0, 0, "DriverHostForm", "Destroy driver method completed on thread: " + Thread.CurrentThread.ManagedThreadId); Application.ExitThread(); // Close all forms on this thread, which will also terminate the thread itself }
/// <summary> /// Form load event - Create the driver /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void DriverHostForm_Load(object sender, EventArgs e) { deviceKey = string.Format("{0}/{1}", configuredDevice.Value.DeviceType.ToLowerInvariant(), configuredDevice.Value.DeviceNumber); ServerForm.LogMessage(0, 0, 0, "DriverHostForm", string.Format("Creating driver {0} ({1}) on thread {2}", deviceKey, configuredDevice.Key, Thread.CurrentThread.ManagedThreadId)); restServer.CreateInstance(configuredDevice); // Create the driver on this thread ServerForm.LogMessage(0, 0, 0, "DriverHostForm", string.Format("Created driver {0} ({1}) on thread {2}", deviceKey, configuredDevice.Key, Thread.CurrentThread.ManagedThreadId)); ServerForm.ActiveObjects[deviceKey].DriverHostForm = this; // Save the driver host form reference so that calls can be made to the driver }
/// <summary> /// Main constructor for the form. Save state variables to use when creating, using and destroying the driver /// </summary> /// <param name="traceLoggerPlus">TraceLogger object</param> /// <param name="device">ConfiguredDevice object with details of the driver to be created</param> /// <param name="server">Handle to the main server form</param> public DriverHostForm(KeyValuePair <string, ConfiguredDevice> device, ServerForm server) { InitializeComponent(); configuredDevice = device; restServer = server; this.FormClosed += DriverHostForm_FormClosed; this.Load += DriverHostForm_Load; ServerForm.LogMessage(0, 0, 0, "DriverHostForm", "Form has been instantiated on thread: " + Thread.CurrentThread.ManagedThreadId); }
public void SetValue <T>(string KeyName, string SubKey, T Value) { if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "SetValue", string.Format("Setting {0} value '{1}' in subkey '{2}' to: '{3}'", typeof(T).Name, KeyName, SubKey, Value.ToString())); } if (SubKey == "") { baseRegistryKey.SetValue(KeyName, Value.ToString()); } else { baseRegistryKey.CreateSubKey(SubKey).SetValue(KeyName, Value.ToString()); } }
public Configuration() { try { if (ServerForm.DebugTraceState) { ServerForm.LogMessage(0, 0, 0, "Configuration New", "About to create base key"); } baseRegistryKey = RegistryKey.OpenBaseKey(SharedConstants.ASCOM_REMOTE_CONFIGURATION_HIVE, RegistryView.Default).CreateSubKey(SharedConstants.ASCOM_REMOTE_CONFIGURATION_KEY); if (ServerForm.DebugTraceState) { ServerForm.LogMessage(0, 0, 0, "Configuration New", "Created base key: " + baseRegistryKey.Name); } } catch (Exception ex) { ServerForm.LogException(0, 0, 0, "Configuration New", ex.ToString()); } }
/// <summary> /// Send a command to the driver /// </summary> /// <param name="requestData">Details of the command to send</param> public void DriverCommand(RequestData requestData) { try // Process the command { if (ServerForm.DebugTraceState) { ServerForm.LogMessage1(requestData, requestData.Elements[ServerForm.URL_ELEMENT_METHOD], string.Format("DriverCommand has received a command for {0} on thread {1}", deviceKey, Thread.CurrentThread.ManagedThreadId)); } Application.DoEvents(); restServer.ProcessDriverCommand(requestData); if (ServerForm.DebugTraceState) { ServerForm.LogMessage1(requestData, requestData.Elements[ServerForm.URL_ELEMENT_METHOD], string.Format("DriverCommand has completed the command for {0} on thread {1}", deviceKey, Thread.CurrentThread.ManagedThreadId)); } } catch (Exception ex) // Something serious has gone wrong with the ASCOM Rest server itself so report this to the user { ServerForm.LogException1(requestData, "DriverCommand", ex.ToString()); restServer.Return500Error(requestData, "Internal server error (DriverOnSeparateThread): " + ex.ToString()); } }
/// <summary> /// Send a command to the driver /// </summary> /// <param name="requestData">Details of the command to send</param> public void DriverCommand(RequestData requestData) { try // Process the command { if (ServerForm.DebugTraceState) { ServerForm.LogMessage(requestData.ClientID, requestData.ClientTransactionID, requestData.ServerTransactionID, "DriverCommand", string.Format("Received command for {0} on thread {1}", deviceKey, Thread.CurrentThread.ManagedThreadId)); } Application.DoEvents(); restServer.ProcessDriverCommand(requestData.ClientID, requestData.ClientTransactionID, requestData.ServerTransactionID, requestData.SuppliedParameters, requestData.Request, requestData.Response, requestData.Elements, requestData.DeviceKey); if (ServerForm.DebugTraceState) { ServerForm.LogMessage(requestData.ClientID, requestData.ClientTransactionID, requestData.ServerTransactionID, "DriverCommand", string.Format("Completed command for {0} on thread {1}", deviceKey, Thread.CurrentThread.ManagedThreadId)); } } catch (Exception ex) // Something serious has gone wrong with the ASCOM Rest server itself so report this to the user { ServerForm.LogException(requestData.ClientID, requestData.ClientTransactionID, requestData.ServerTransactionID, "DriverCommand", ex.ToString()); restServer.Return500Error(requestData.Request, requestData.Response, "Internal server error (DriverOnSeparateThread): " + ex.ToString(), requestData.ClientID, requestData.ClientTransactionID, requestData.ServerTransactionID); } }
public void InitUI(SetupForm parent) { setupForm = parent; ServerForm.LogMessage(0, 0, 0, "ServedDevice.InitUI", "Start"); profile = new Profile(); ServerForm.LogMessage(0, 0, 0, "ServedDevice.InitUI", "Created Profile"); cmbDeviceType.Items.Add(SharedConstants.DEVICE_NOT_CONFIGURED); ServerForm.LogMessage(0, 0, 0, "ServedDevice.InitUI", "Added Device not configured"); foreach (string deviceType in profile.RegisteredDeviceTypes) { ServerForm.LogMessage(0, 0, 0, "ServedDevice.InitUI", "Adding item: " + deviceType); cmbDeviceType.Items.Add(deviceType); deviceTypes.Add(deviceType); // Remember the device types on this system } ServerForm.LogMessage(0, 0, 0, "ServedDevice.InitUI", "Setting selected index to 0"); cmbDeviceType.SelectedIndex = 0; ServerForm.LogMessage(0, 0, 0, "ServedDevice.InitUI", "Finished"); }
private void Form_Load(object sender, EventArgs e) { // Declare local variables IPHostEntry host; bool foundAnIPAddress = false; bool foundTheIPAddress = false; int selectedIndex = 0; ServerForm.LogMessage(0, 0, 0, "SetupForm Load", "Start"); profile = new Profile(); host = Dns.GetHostEntry(Dns.GetHostName()); // Get an IPHostEntry so that we can get the list of IP addresses on this PC deviceNumberIndexes = new Dictionary <string, int>(); // Create a dictionary to hold the current device instance numbers of every device type // Create a list of valid IP addresses on this PC so that the user can select one on which to run the ASCOM device server. addressList.Items.Add(SharedConstants.LOCALHOST_NAME); // Make "localhost" the first entry in the list of addresses foreach (IPAddress ip in host.AddressList) // Add the other addresses on this PC { if ((ip.AddressFamily == AddressFamily.InterNetwork) & !foundAnIPAddress) // Only process IPv4 addresses and ignore the rest including IPv6 { ServerForm.LogMessage(0, 0, 0, "SetupForm Load", string.Format("Found {0} Address: {1}", ip.AddressFamily.ToString(), ip.ToString())); foundAnIPAddress = true; addressList.Items.Add(ip.ToString()); if (ip.ToString() == ServerForm.ServerIPAddressString) { selectedIndex = addressList.Items.Count - 1; foundTheIPAddress = true; } } else { ServerForm.LogMessage(0, 0, 0, "SetupForm Load", string.Format("Ignored {0} Address: {1}", ip.AddressFamily.ToString(), ip.ToString())); } } ServerForm.LogMessage(0, 0, 0, "SetupForm Load", string.Format("Found an IP address: {0}, Found the IP address: {1}, Stored IP Address: {2}", foundAnIPAddress, foundTheIPAddress, ServerForm.ServerIPAddressString)); if ((!foundTheIPAddress) & (ServerForm.ServerIPAddressString != "")) // Add the last stored IP address if it isn't found in the search above { addressList.Items.Add(ServerForm.ServerIPAddressString); // Add the stored address to the list selectedIndex = addressList.Items.Count - 1; // Select this item in the list } // Add the wild card addresses at the end of the list if (ServerForm.ServerIPAddressString != SharedConstants.STRONG_WILDCARD_NAME) { addressList.Items.Add(SharedConstants.STRONG_WILDCARD_NAME); // Include the strong wild card character in the list of addresses if not already in use } if (ServerForm.ServerIPAddressString != SharedConstants.WEAK_WILDCARD_NAME) { addressList.Items.Add(SharedConstants.WEAK_WILDCARD_NAME); // Include the weak wild card character in the list of addresses if not already in use } // Set up the GUI components addressList.SelectedIndex = selectedIndex; numPort.Value = ServerForm.ServerPortNumber; chkAutoConnect.Checked = ServerForm.StartWithDevicesConnected; chkAccessLog.Checked = ServerForm.AccessLogEnabled; chkTrace.Checked = ServerForm.TraceState; chkDebugTrace.Checked = ServerForm.DebugTraceState; chkDebugTrace.Enabled = ServerForm.TraceState; // Enable or disable the debug trace check box depending on whether normal trace is enabled chkManagementInterfaceEnabled.Checked = ServerForm.ManagementInterfaceEnabled; ChkStartWithApiEnabled.Checked = ServerForm.StartWithApiEnabled; LblDevicesNotDisconnoected.Visible = ServerForm.devicesAreConnected; ChkRunDriversInSeparateThreadss.Checked = ServerForm.RunDriversOnSeparateThreads; ChkLogClientIPAddress.Checked = ServerForm.LogClientIPAddress; ChkIncludeDriverExceptionsInJsonResponses.Checked = ServerForm.IncludeDriverExceptionInJsonResponse; // Populate the device types list foreach (string deviceType in profile.RegisteredDeviceTypes) { ServerForm.LogMessage(0, 0, 0, "SetupForm Load", "Adding device type: " + deviceType); registeredDeviceTypes.Add(deviceType); // Remember the device types on this system } ServerForm.LogMessage(0, 0, 0, "SetupForm Load", string.Format("Number of configured devices: {0}.", ServerForm.ConfiguredDevices.Count)); foreach (string deviceName in ServerForm.ConfiguredDevices.Keys) { ServerForm.LogMessage(0, 0, 0, "SetupForm Load", string.Format("ConfiguredDevices contains key {0}.", deviceName)); } // Initialise each of the device GUI components foreach (ServedDevice item in this.Controls.OfType <ServedDevice>()) { ServerForm.LogMessage(0, 0, 0, "SetupForm Load", string.Format("Starting Init for {0}.", item.Name)); item.InitUI(this); ServerForm.LogMessage(0, 0, 0, "SetupForm Load", string.Format("Completed Init for {0}, now setting its parameters.", item.Name)); item.DeviceType = ServerForm.ConfiguredDevices[item.Name].DeviceType; item.ProgID = ServerForm.ConfiguredDevices[item.Name].ProgID; item.DeviceNumber = ServerForm.ConfiguredDevices[item.Name].DeviceNumber; item.AllowConnectedSetFalse = ServerForm.ConfiguredDevices[item.Name].AllowConnectedSetFalse; item.AllowConnectedSetTrue = ServerForm.ConfiguredDevices[item.Name].AllowConnectedSetTrue; item.DevicesAreConnected = ServerForm.devicesAreConnected; ServerForm.LogMessage(0, 0, 0, "SetupForm Load", string.Format("Completed Init for {0}.", item.Name)); } RecalculateDeviceNumbers(); }
public void SetValueInvariant <T>(string KeyName, string SubKey, T Value) { if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "SetValue DateTime", string.Format("Setting {0} value '{1}' in subkey '{2}' to: '{3}'", typeof(T).Name, KeyName, SubKey, Value.ToString())); } if ((typeof(T) == typeof(Int32)) | (typeof(T) == typeof(int))) { int intValue = Convert.ToInt32(Value); if (SubKey == "") { baseRegistryKey.SetValue(KeyName, intValue.ToString(CultureInfo.InvariantCulture)); } else { baseRegistryKey.CreateSubKey(SubKey).SetValue(KeyName, intValue.ToString(CultureInfo.InvariantCulture)); } return; } if (typeof(T) == typeof(bool)) { bool boolValue = Convert.ToBoolean(Value); if (SubKey == "") { baseRegistryKey.SetValue(KeyName, boolValue.ToString(CultureInfo.InvariantCulture)); } else { baseRegistryKey.CreateSubKey(SubKey).SetValue(KeyName, boolValue.ToString(CultureInfo.InvariantCulture)); } return; } if (typeof(T) == typeof(decimal)) { decimal decimalValue = Convert.ToDecimal(Value); if (SubKey == "") { baseRegistryKey.SetValue(KeyName, decimalValue.ToString(CultureInfo.InvariantCulture)); } else { baseRegistryKey.CreateSubKey(SubKey).SetValue(KeyName, decimalValue.ToString(CultureInfo.InvariantCulture)); } return; } if (typeof(T) == typeof(DateTime)) { DateTime dateTimeValue = Convert.ToDateTime(Value); if (SubKey == "") { baseRegistryKey.SetValue(KeyName, dateTimeValue.ToString("HH:mm:ss", CultureInfo.InvariantCulture)); } else { baseRegistryKey.CreateSubKey(SubKey).SetValue(KeyName, dateTimeValue.ToString("HH:mm:ss", CultureInfo.InvariantCulture)); } return; } throw new DriverException("SetValueInvariant: Unknown type: " + typeof(T).Name); }
public T GetValue <T>(string KeyName, string SubKey, T DefaultValue) { if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "GetValue", string.Format("Getting {0} value '{1}' in subkey '{2}', default: '{3}'", typeof(T).Name, KeyName, SubKey, DefaultValue.ToString())); } if (typeof(T) == typeof(bool)) { string registryValue; if (SubKey == "") { if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "GetValue", "SubKey is empty so getting value directly"); } registryValue = (string)baseRegistryKey.GetValue(KeyName); if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "GetValue", "Value retrieved OK: " + registryValue); } } else { if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "GetValue", "SubKey has a value so using it..."); } registryValue = (string)baseRegistryKey.CreateSubKey(SubKey).GetValue(KeyName); if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "GetValue", "Value retrieved OK: " + registryValue); } } if (registryValue == null) { SetValueInvariant <T>(KeyName, SubKey, DefaultValue); bool defaultValue = Convert.ToBoolean(DefaultValue); registryValue = defaultValue.ToString(CultureInfo.InvariantCulture); } bool RetVal = Convert.ToBoolean(registryValue, CultureInfo.InvariantCulture); if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "GetValue", string.Format("Retrieved {0} = {1}", KeyName, RetVal.ToString())); } return((T)((object)RetVal)); } if (typeof(T) == typeof(string)) { string RetVal; if (SubKey == "") { if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "GetValue", "SubKey is empty so getting value directly"); } RetVal = (string)baseRegistryKey.GetValue(KeyName); if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "GetValue", "Value retrieved OK: " + RetVal); } } else { if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "GetValue", "SubKey has a value so using it..."); } RetVal = (string)baseRegistryKey.CreateSubKey(SubKey).GetValue(KeyName); if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "GetValue", "Value retrieved OK: " + RetVal); } } if (RetVal == null) { SetValue <T>(KeyName, SubKey, DefaultValue); RetVal = DefaultValue.ToString(); } if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "GetValue", string.Format("Retrieved {0} = {1}", KeyName, RetVal.ToString())); } return((T)((object)RetVal)); } if (typeof(T) == typeof(decimal)) { string registryValue; if (SubKey == "") { if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "GetValue", "SubKey is empty so getting value directly"); } registryValue = (string)baseRegistryKey.GetValue(KeyName); if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "GetValue", "Value retrieved OK: " + registryValue); } } else { if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "GetValue", "SubKey has a value so using it..."); } registryValue = (string)baseRegistryKey.CreateSubKey(SubKey).GetValue(KeyName); if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "GetValue", "Value retrieved OK: " + registryValue); } } if (registryValue == null) { SetValueInvariant <T>(KeyName, SubKey, DefaultValue); decimal defaultValue = Convert.ToDecimal(DefaultValue); registryValue = defaultValue.ToString(CultureInfo.InvariantCulture); } decimal RetVal = Convert.ToDecimal(registryValue, CultureInfo.InvariantCulture); if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "GetValue", string.Format("Retrieved {0} = {1}", KeyName, RetVal.ToString())); } return((T)((object)RetVal)); } if (typeof(T) == typeof(DateTime)) { string registryValue; if (SubKey == "") { if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "GetValue", "SubKey is empty so getting value directly"); } registryValue = (string)baseRegistryKey.GetValue(KeyName); if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "GetValue", "Value retrieved OK: " + registryValue); } } else { if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "GetValue", "SubKey has a value so using it..."); } registryValue = (string)baseRegistryKey.CreateSubKey(SubKey).GetValue(KeyName); if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "GetValue", "Value retrieved OK: " + registryValue); } } if (registryValue == null) { SetValueInvariant <T>(KeyName, SubKey, DefaultValue); return(DefaultValue); } if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "GetValue DateTime", $"String value prior to Convert: {registryValue}"); } if (DateTime.TryParse(registryValue, CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out DateTime RetVal)) { // The string parsed OK so return the parsed value; if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "GetValue DateTime", string.Format("Retrieved {0} = {1}", KeyName, RetVal.ToString())); } return((T)((object)RetVal)); } else // If the string fails to parse, overwrite with the default value and return this { if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "GetValue DateTime", $"Failed to parse registry value, persisting and returning the default value: {DefaultValue}"); } SetValueInvariant <T>(KeyName, SubKey, DefaultValue); return(DefaultValue); } } if ((typeof(T) == typeof(Int32)) | (typeof(T) == typeof(int))) { string registryValue; if (SubKey == "") { if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "GetValue", "SubKey is empty so getting value directly"); } registryValue = (string)baseRegistryKey.GetValue(KeyName); if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "GetValue", "Value retrieved OK: " + registryValue); } } else { if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "GetValue", "SubKey has a value so using it..."); } registryValue = (string)baseRegistryKey.CreateSubKey(SubKey).GetValue(KeyName); if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "GetValue", "Value retrieved OK: " + registryValue); } } if (registryValue == null) { SetValueInvariant <T>(KeyName, SubKey, DefaultValue); int defaultValue = Convert.ToInt32(DefaultValue); registryValue = defaultValue.ToString(CultureInfo.InvariantCulture); } int RetVal = Convert.ToInt32(registryValue, CultureInfo.InvariantCulture); if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "GetValue", string.Format("Retrieved {0} = {1}", KeyName, RetVal.ToString())); } return((T)((object)RetVal)); } throw new DriverException("GetValue: Unknown type: " + typeof(T).Name); }
/// <summary> /// Create a list of valid IP addresses on this PC so that the user can select one on which to run the ASCOM device server. /// </summary> private void PopulateAddressList() { bool foundAnIPAddress = false; bool foundTheIPAddress = false; int selectedIndex = 0; ServerForm.LogMessage(0, 0, 0, "PopulateAddressList", "Start"); addressList.Items.Clear(); deviceNumberIndexes = new Dictionary <string, int>(); // Create a dictionary to hold the current device instance numbers of every device type // Add IPv4 addresses if (RadIpV4.Checked | RadIpV4AndV6.Checked) // IPv4 addresses are required { // Add a local host entry addressList.Items.Add(SharedConstants.LOCALHOST_NAME_IPV4); // Make "localhost" the first entry in the list of IPv4 addresses foreach (IPAddress ipAddress in HostPc.IpV4Addresses) { addressList.Items.Add(ipAddress.ToString()); ServerForm.LogMessage(0, 0, 0, "PopulateAddressList", string.Format(" Added {0} Address: {1}", ipAddress.AddressFamily.ToString(), ipAddress.ToString())); foundAnIPAddress = true; if (ipAddress.ToString() == ServerForm.ServerIPAddressString) { selectedIndex = addressList.Items.Count - 1; foundTheIPAddress = true; } } } // Add IPv6 addresses if (RadIpV6.Checked | RadIpV4AndV6.Checked) // IPv6 addresses are required { foreach (IPAddress ipAddress in HostPc.IpV6Addresses) { addressList.Items.Add($"[{ipAddress}]"); ServerForm.LogMessage(0, 0, 0, "PopulateAddressList", string.Format(" Added {0} Address: {1}", ipAddress.AddressFamily.ToString(), ipAddress.ToString())); foundAnIPAddress = true; if ($"[{ipAddress}]" == ServerForm.ServerIPAddressString) { selectedIndex = addressList.Items.Count - 1; foundTheIPAddress = true; } } } ServerForm.LogMessage(0, 0, 0, "PopulateAddressList", string.Format($"Found an IP address: {foundAnIPAddress}, Found the IP address: {foundTheIPAddress}, Stored IP Address: {ServerForm.ServerIPAddressString}")); if ((!foundTheIPAddress) & (ServerForm.ServerIPAddressString != "")) // Add the last stored IP address if it isn't found in the search above { if (ServerForm.ServerIPAddressString == SharedConstants.BIND_TO_ALL_INTERFACES_IP_ADDRESS_STRONG) // Handle the "Strong bind all addresses" special case { addressList.Items.Add(SharedConstants.BIND_TO_ALL_INTERFACES_DESCRIPTION); // Add the "All interfaces" description to the list selectedIndex = addressList.Items.Count - 1; // Select this item in the list } else if (ServerForm.ServerIPAddressString == SharedConstants.BIND_TO_ALL_INTERFACES_IP_ADDRESS_WEAK) // Handle the "Weak bind all addresses" special case { addressList.Items.Add(SharedConstants.BIND_TO_ALL_INTERFACES_IP_ADDRESS_WEAK); // Add the "Weak bind" * character to the list selectedIndex = addressList.Items.Count - 1; // Select this item in the list } else // One specific address so add it if it parses OK { IPAddress serverIpAddress = IPAddress.Parse(ServerForm.ServerIPAddressString); if (((serverIpAddress.AddressFamily == AddressFamily.InterNetwork) & ((RadIpV4.Checked | RadIpV4AndV6.Checked))) | ((serverIpAddress.AddressFamily == AddressFamily.InterNetworkV6) & ((RadIpV6.Checked | RadIpV4AndV6.Checked)))) // Address parses OK so add it { addressList.Items.Add(ServerForm.ServerIPAddressString); // Add the stored address to the list selectedIndex = addressList.Items.Count - 1; // Select this item in the list } else // Address does not parse so ignore it, should not occur because IP addresses are validated on entry through the Setup GUI { selectedIndex = 0; } } } // Include the "All interfaces" name at the end of the list of addresses if not already in use if (ServerForm.ServerIPAddressString != SharedConstants.BIND_TO_ALL_INTERFACES_IP_ADDRESS_STRONG) { addressList.Items.Add(SharedConstants.BIND_TO_ALL_INTERFACES_DESCRIPTION); } addressList.SelectedIndex = selectedIndex; }
private void BtnSetup_Click(object sender, EventArgs e) { // This device's ProgID is held in the variable progID so try and run its SetupDialog method ServerForm.LogMessage(0, 0, 0, "Setup", string.Format("Setup button pressed for device: {0}, ProgID: {1}", cmbDevice.Text, progID)); try { // Get an instance of the driver from its ProgID and store this in a dynamic variable so that we can call its method directly Type ProgIdType = Type.GetTypeFromProgID(progID); //ServerForm.LogMessage(0, 0, 0, "Setup", string.Format("Found type: {0}", ProgIdType.Name)); dynamic oDrv = Activator.CreateInstance(ProgIdType); //ServerForm.LogMessage(0, 0, 0, "Setup", "Created driver instance OK"); try { if (GetConnectdState(oDrv)) // Driver is connected and the Setup dialogue must be run with the device disconnected so ask whether we can disconnect it { DialogResult dialogResult = MessageBox.Show("Device is connected, OK to disconnect and run Setup?", "Disconnect Device?", MessageBoxButtons.OKCancel); if (dialogResult == DialogResult.OK) // OK to disconnect and run setup dialogue { //ServerForm.LogMessage(0, 0, 0, "Setup", "User gave permission to disconnect device - setting Connected to false"); try { oDrv.Connected = false; } catch { }; // Set Connected to false ignoring errors try { oDrv.Link = false; } catch { }; // Set Link to false (for IFocuserV1 devices) ignoring errors int RemainingObjectCount = Marshal.FinalReleaseComObject(oDrv); oDrv = null; oDrv = Activator.CreateInstance(ProgIdType); //ServerForm.LogMessage(0, 0, 0, "Setup", string.Format("Connected has bee set false and destroyed. New Connected value: {0}", oDrv.Connected)); //ServerForm.LogMessage(0, 0, 0, "Setup", "Device is now disconnected, calling SetupDialog method"); oDrv.SetupDialog(); //ServerForm.LogMessage(0, 0, 0, "Setup", "Completed SetupDialog method, setting Connected to true"); try { oDrv.Connected = true; // Try setting Connected to true } catch (Exception ex2) when(DeviceType.ToLowerInvariant() == "focuser") { // Connected failed so try Link in case this is an IFocuserV1 device ServerForm.LogException(0, 0, 0, "Setup", $"Error setting Connected to true for focuser device {ProgID}, now trying Link for IFocuserV1 devices: \r\n{ex2.ToString()}"); oDrv.Link = true; } //ServerForm.LogMessage(0, 0, 0, "Setup", "Driver is now Connected"); } else // Not OK to disconnect so just do nothing and exit { ServerForm.LogMessage(0, 0, 0, "Setup", "User did not give permission to disconnect device - no action taken"); } } else // Driver is not connected { //ServerForm.LogMessage(0, 0, 0, "Setup", "Device is disconnected so just calling SetupDialog method"); oDrv.SetupDialog(); //ServerForm.LogMessage(0, 0, 0, "Setup", "Completed SetupDialog method"); try { oDrv.Dispose(); } catch { }; // Dispose the driver if possible // Release the COM object properly try { //ServerForm.LogMessage(0, 0, 0, "Setup", " Releasing COM object"); int LoopCount = 0; int RemainingObjectCount = 0; do { LoopCount += 1; // Increment the loop counter so that we don't go on for ever! RemainingObjectCount = Marshal.ReleaseComObject(oDrv); //ServerForm.LogMessage(0, 0, 0, "Setup", " Remaining object count: " + RemainingObjectCount.ToString() + ", LoopCount: " + LoopCount); } while ((RemainingObjectCount > 0) & (LoopCount < 20)); } catch (Exception ex2) { ServerForm.LogMessage(0, 0, 0, "Setup", " ReleaseComObject Exception: " + ex2.Message); } oDrv = null; } } catch (Exception ex1) { string errMsg = string.Format("Exception calling SetupDialog method: {0}", ex1.Message); MessageBox.Show(errMsg); ServerForm.LogMessage(0, 0, 0, "Setup", errMsg); ServerForm.LogException(0, 0, 0, "Setup", ex1.ToString()); } } catch (Exception ex) { string errMsg = string.Format("Exception creating driver {0} - {1}", progID, ex.Message); MessageBox.Show(errMsg); ServerForm.LogMessage(0, 0, 0, "Setup", errMsg); ServerForm.LogException(0, 0, 0, "Setup", ex.ToString()); } }
private void Form_Load(object sender, EventArgs e) { try { ServerForm.LogMessage(0, 0, 0, "SetupForm Load", "Start"); // Set up the GUI components numPort.Value = ServerForm.ServerPortNumber; chkAutoConnect.Checked = ServerForm.StartWithDevicesConnected; chkAccessLog.Checked = ServerForm.AccessLogEnabled; chkTrace.Checked = ServerForm.TraceState; chkDebugTrace.Checked = ServerForm.DebugTraceState; chkDebugTrace.Enabled = ServerForm.TraceState; // Enable or disable the debug trace check box depending on whether normal trace is enabled chkManagementInterfaceEnabled.Checked = ServerForm.ManagementInterfaceEnabled; ChkStartWithApiEnabled.Checked = ServerForm.StartWithApiEnabled; LblDevicesNotDisconnoected.Visible = ServerForm.devicesAreConnected; ChkRunDriversInSeparateThreadss.Checked = ServerForm.RunDriversOnSeparateThreads; ChkLogClientIPAddress.Checked = ServerForm.LogClientIPAddress; ChkIncludeDriverExceptionsInJsonResponses.Checked = ServerForm.IncludeDriverExceptionInJsonResponse; TxtRemoteServerLocation.Text = ServerForm.RemoteServerLocation; ChkEnableCors.Checked = ServerForm.CorsSupportIsEnabled; // Set the CORS enabled checkbox (this doesn't fire associated event handlers if support is disabled) NumCorsMaxAge.Value = ServerForm.CorsMaxAge; ChkCorsSupportCredentials.Checked = ServerForm.CorsCredentialsPermitted; ChkEnableDiscovery.Checked = ServerForm.AlpacaDiscoveryEnabled; NumDiscoveryPort.Value = ServerForm.AlpacaDiscoveryPort; NumMaxDevices.Value = ServerForm.MaximumNumberOfDevices; // Set the IP v4 / v6 radio boxes if (ServerForm.IpV4Enabled & ServerForm.IpV6Enabled) // Both IPv4 and v6 are enabled so set the "both" button { RadIpV4AndV6.Checked = true; } else // Only one of v4 or v6 is enabled so set accordingly { RadIpV4.Checked = ServerForm.IpV4Enabled; RadIpV6.Checked = ServerForm.IpV6Enabled; } // Populate the address list combo box PopulateAddressList(); // CORS tab event handler ChkEnableCors_CheckedChanged(ChkEnableCors, new EventArgs()); // Fire the event handlers to ensure that the controls reflect the CORS enabled / disabled state DataGridCorsOrigins_EnabledChanged(DataGridCorsOrigins, new EventArgs()); using (Profile profile = new Profile()) { // Populate the device types list foreach (string deviceType in profile.RegisteredDeviceTypes) { ServerForm.LogMessage(0, 0, 0, "SetupForm Load", "Adding device type: " + deviceType); registeredDeviceTypes.Add(deviceType); // Remember the device types on this system } } ServerForm.LogMessage(0, 0, 0, "SetupForm Load", string.Format("Number of configured devices: {0}.", ServerForm.ConfiguredDevices.Count)); foreach (string deviceName in ServerForm.ConfiguredDevices.Keys) { ServerForm.LogMessage(0, 0, 0, "SetupForm Load", string.Format("ConfiguredDevices contains key {0}.", deviceName)); } // Populate the device list with all configured controls deviceList = WalkControls(this, new List <ServedDevice>()); // Initialise each of the device GUI components foreach (ServedDevice item in deviceList) { string devicenumberString = item.Name.Substring("ServedDevice".Length); ServerForm.LogMessage(0, 0, 0, "SetupForm Load", $"Init - Found device {item.Name} - {devicenumberString}"); if (int.Parse(item.Name.Substring("ServedDevice".Length)) < ServerForm.MaximumNumberOfDevices) //string.Compare(item.Name, $"ServedDevice{ServerForm.MaximumNumberOfDevices - 1}") <= 0) //item.Name <= $"servedDevice{ServerForm.MaximumNumberOfDevices-1}") { ServerForm.LogMessage(0, 0, 0, "SetupForm Load", string.Format("Starting Init for {0}.", item.Name)); item.InitUI(this); ServerForm.LogMessage(0, 0, 0, "SetupForm Load", string.Format("Completed Init for {0}, now setting its parameters.", item.Name)); item.DeviceType = ServerForm.ConfiguredDevices[item.Name].DeviceType; item.ProgID = ServerForm.ConfiguredDevices[item.Name].ProgID; item.DeviceNumber = ServerForm.ConfiguredDevices[item.Name].DeviceNumber; item.AllowConnectedSetFalse = ServerForm.ConfiguredDevices[item.Name].AllowConnectedSetFalse; item.AllowConnectedSetTrue = ServerForm.ConfiguredDevices[item.Name].AllowConnectedSetTrue; item.AllowConcurrentAccess = ServerForm.ConfiguredDevices[item.Name].AllowConcurrentAccess; item.DevicesAreConnected = ServerForm.devicesAreConnected; ServerForm.LogMessage(0, 0, 0, "SetupForm Load", string.Format("Completed Init for {0}.", item.Name)); } } switch (ServerForm.MaximumNumberOfDevices) { case 10: DeviceTabs.TabPages.Remove(DeviceTab1); DeviceTabs.TabPages.Remove(DeviceTab2); DeviceTabs.TabPages.Remove(DeviceTab3); DeviceTabs.TabPages.Remove(DeviceTab4); DeviceTabs.TabPages.Remove(DeviceTab5); DeviceTabs.TabPages.Remove(DeviceTab6); DeviceTabs.TabPages.Remove(DeviceTab7); DeviceTabs.TabPages.Remove(DeviceTab8); DeviceTabs.TabPages.Remove(DeviceTab9); break; case 20: DeviceTabs.TabPages.Remove(DeviceTab2); DeviceTabs.TabPages.Remove(DeviceTab3); DeviceTabs.TabPages.Remove(DeviceTab4); DeviceTabs.TabPages.Remove(DeviceTab5); DeviceTabs.TabPages.Remove(DeviceTab6); DeviceTabs.TabPages.Remove(DeviceTab7); DeviceTabs.TabPages.Remove(DeviceTab8); DeviceTabs.TabPages.Remove(DeviceTab9); break; case 30: DeviceTabs.TabPages.Remove(DeviceTab3); DeviceTabs.TabPages.Remove(DeviceTab4); DeviceTabs.TabPages.Remove(DeviceTab5); DeviceTabs.TabPages.Remove(DeviceTab6); DeviceTabs.TabPages.Remove(DeviceTab7); DeviceTabs.TabPages.Remove(DeviceTab8); DeviceTabs.TabPages.Remove(DeviceTab9); break; case 40: DeviceTabs.TabPages.Remove(DeviceTab4); DeviceTabs.TabPages.Remove(DeviceTab5); DeviceTabs.TabPages.Remove(DeviceTab6); DeviceTabs.TabPages.Remove(DeviceTab7); DeviceTabs.TabPages.Remove(DeviceTab8); DeviceTabs.TabPages.Remove(DeviceTab9); break; case 50: DeviceTabs.TabPages.Remove(DeviceTab5); DeviceTabs.TabPages.Remove(DeviceTab6); DeviceTabs.TabPages.Remove(DeviceTab7); DeviceTabs.TabPages.Remove(DeviceTab8); DeviceTabs.TabPages.Remove(DeviceTab9); break; case 60: DeviceTabs.TabPages.Remove(DeviceTab6); DeviceTabs.TabPages.Remove(DeviceTab7); DeviceTabs.TabPages.Remove(DeviceTab8); DeviceTabs.TabPages.Remove(DeviceTab9); break; case 70: DeviceTabs.TabPages.Remove(DeviceTab7); DeviceTabs.TabPages.Remove(DeviceTab8); DeviceTabs.TabPages.Remove(DeviceTab9); break; case 80: DeviceTabs.TabPages.Remove(DeviceTab8); DeviceTabs.TabPages.Remove(DeviceTab9); break; case 90: DeviceTabs.TabPages.Remove(DeviceTab9); break; case 100: break; } RecalculateDeviceNumbers(); // Add this event handler after the initial value has been set so that this doesn't trigger an even this.NumMaxDevices.ValueChanged += new System.EventHandler(this.NumMaxDevices_ValueChanged); } catch (Exception ex) { ServerForm.LogException(0, 0, 0, "SetupForm Load", string.Format("Exception on loading form: {0}.", ex.ToString())); MessageBox.Show(string.Format("Setup exception: {0}\r\nThe form may not function correctly.", ex.Message), "Setup form load error", MessageBoxButtons.OK, MessageBoxIcon.Warning); } }
public T GetValue <T>(string KeyName, string SubKey, T DefaultValue) { if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "GetValue", string.Format("Getting {0} value '{1}' in subkey '{2}', default: '{3}'", typeof(T).Name, KeyName, SubKey, DefaultValue.ToString())); } if (typeof(T) == typeof(bool)) { string registryValue; if (SubKey == "") { if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "GetValue", "SubKey is empty so getting value directly"); } registryValue = (string)baseRegistryKey.GetValue(KeyName); if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "GetValue", "Value retrieved OK: " + registryValue); } } else { if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "GetValue", "SubKey has a value so using it..."); } registryValue = (string)baseRegistryKey.CreateSubKey(SubKey).GetValue(KeyName); if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "GetValue", "Value retrieved OK: " + registryValue); } } if (registryValue == null) { SetValue <T>(KeyName, SubKey, DefaultValue); registryValue = DefaultValue.ToString(); } bool RetVal = Convert.ToBoolean(registryValue, CultureInfo.InvariantCulture); if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "GetValue", string.Format("Retrieved {0} = {1}", KeyName, RetVal.ToString())); } return((T)((object)RetVal)); } if (typeof(T) == typeof(string)) { string RetVal; if (SubKey == "") { if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "GetValue", "SubKey is empty so getting value directly"); } RetVal = (string)baseRegistryKey.GetValue(KeyName); if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "GetValue", "Value retrieved OK: " + RetVal); } } else { if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "GetValue", "SubKey has a value so using it..."); } RetVal = (string)baseRegistryKey.CreateSubKey(SubKey).GetValue(KeyName); if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "GetValue", "Value retrieved OK: " + RetVal); } } if (RetVal == null) { SetValue <T>(KeyName, SubKey, DefaultValue); RetVal = DefaultValue.ToString(); } if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "GetValue", string.Format("Retrieved {0} = {1}", KeyName, RetVal.ToString())); } return((T)((object)RetVal)); } if (typeof(T) == typeof(decimal)) { string registryValue; if (SubKey == "") { if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "GetValue", "SubKey is empty so getting value directly"); } registryValue = (string)baseRegistryKey.GetValue(KeyName); if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "GetValue", "Value retrieved OK: " + registryValue); } } else { if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "GetValue", "SubKey has a value so using it..."); } registryValue = (string)baseRegistryKey.CreateSubKey(SubKey).GetValue(KeyName); if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "GetValue", "Value retrieved OK: " + registryValue); } } if (registryValue == null) { SetValue <T>(KeyName, SubKey, DefaultValue); registryValue = DefaultValue.ToString(); } decimal RetVal = Convert.ToDecimal(registryValue, CultureInfo.InvariantCulture); if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "GetValue", string.Format("Retrieved {0} = {1}", KeyName, RetVal.ToString())); } return((T)((object)RetVal)); } if ((typeof(T) == typeof(Int32)) | (typeof(T) == typeof(int))) { string registryValue; if (SubKey == "") { if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "GetValue", "SubKey is empty so getting value directly"); } registryValue = (string)baseRegistryKey.GetValue(KeyName); if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "GetValue", "Value retrieved OK: " + registryValue); } } else { if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "GetValue", "SubKey has a value so using it..."); } registryValue = (string)baseRegistryKey.CreateSubKey(SubKey).GetValue(KeyName); if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "GetValue", "Value retrieved OK: " + registryValue); } } if (registryValue == null) { SetValue <T>(KeyName, SubKey, DefaultValue); registryValue = DefaultValue.ToString(); } Int32 RetVal = Convert.ToInt32(registryValue, CultureInfo.InvariantCulture); if (LOG_CONFIGURATION_CALLS) { ServerForm.LogMessage(0, 0, 0, "GetValue", string.Format("Retrieved {0} = {1}", KeyName, RetVal.ToString())); } return((T)((object)RetVal)); } throw new DriverException("GetValue: Unknown type: " + typeof(T).Name); }
/// <summary> /// Called when the user presses the OK button to commit any new set up values /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void BtnOK_Click(object sender, EventArgs e) { try { if (addressList.Text == SharedConstants.LOCALHOST_NAME_IPV4) { ServerForm.ServerIPAddressString = SharedConstants.LOCALHOST_ADDRESS_IPV4; } else { ServerForm.ServerIPAddressString = addressList.Text; } ServerForm.ServerPortNumber = numPort.Value; ServerForm.StartWithDevicesConnected = chkAutoConnect.Checked; ServerForm.AccessLogEnabled = chkAccessLog.Checked; ServerForm.TraceState = chkTrace.Checked; ServerForm.DebugTraceState = chkDebugTrace.Checked; ServerForm.ManagementInterfaceEnabled = chkManagementInterfaceEnabled.Checked; ServerForm.StartWithApiEnabled = ChkStartWithApiEnabled.Checked; ServerForm.RunDriversOnSeparateThreads = ChkRunDriversInSeparateThreadss.Checked; ServerForm.LogClientIPAddress = ChkLogClientIPAddress.Checked; ServerForm.IncludeDriverExceptionInJsonResponse = ChkIncludeDriverExceptionsInJsonResponses.Checked; ServerForm.RemoteServerLocation = TxtRemoteServerLocation.Text; ServerForm.CorsSupportIsEnabled = ChkEnableCors.Checked; ServerForm.CorsMaxAge = NumCorsMaxAge.Value; ServerForm.CorsCredentialsPermitted = ChkCorsSupportCredentials.Checked; ServerForm.AlpacaDiscoveryEnabled = ChkEnableDiscovery.Checked; ServerForm.AlpacaDiscoveryPort = NumDiscoveryPort.Value; ServerForm.MaximumNumberOfDevices = (int)NumMaxDevices.Value; // Set the IP v4 and v6 variables as necessary if (RadIpV4.Checked) // The IPv4 radio button is checked so set the IP v4 and IP v6 variables accordingly { ServerForm.IpV4Enabled = true; ServerForm.IpV6Enabled = false; } if (RadIpV6.Checked) // The IPv6 radio button is checked so set the IP v4 and IP v6 variables accordingly { ServerForm.IpV4Enabled = false; ServerForm.IpV6Enabled = true; } if (RadIpV4AndV6.Checked) // The IPv4 and IPV6 radio button is checked so set the IP v4 and IP v6 variables accordingly { ServerForm.IpV4Enabled = true; ServerForm.IpV6Enabled = true; } foreach (ServedDevice item in deviceList) { ServerForm.ConfiguredDevices[item.Name].DeviceType = item.DeviceType; // Update the unique ID if the ProgID has changed if (ServerForm.ConfiguredDevices[item.Name].ProgID != item.ProgID) { if (item.ProgID == SharedConstants.DEVICE_NOT_CONFIGURED) // Device has been de-configured { ServerForm.ConfiguredDevices[item.Name].UniqueID = SharedConstants.DEVICE_NOT_CONFIGURED; } else // Device has been changed so create a new unique ID { ServerForm.ConfiguredDevices[item.Name].UniqueID = Guid.NewGuid().ToString().ToUpperInvariant(); } } ServerForm.ConfiguredDevices[item.Name].ProgID = item.ProgID; ServerForm.ConfiguredDevices[item.Name].Description = item.Description; ServerForm.ConfiguredDevices[item.Name].DeviceNumber = item.DeviceNumber; ServerForm.ConfiguredDevices[item.Name].AllowConnectedSetFalse = item.AllowConnectedSetFalse; ServerForm.ConfiguredDevices[item.Name].AllowConnectedSetTrue = item.AllowConnectedSetTrue; ServerForm.ConfiguredDevices[item.Name].AllowConcurrentAccess = item.AllowConcurrentAccess; } ServerForm.CorsPermittedOrigins = corsPermittedOriginsCopy.ToListString(); // Copy the edited list back to the master copy ServerForm.WriteProfile(); if (maxDevicesHasChanged) { MessageBox.Show("The maximum number of devices has changed, please close and restart the Remote Server before adding further devices.", "Maximum Number of Devices", MessageBoxButtons.OK, MessageBoxIcon.Warning); } this.DialogResult = DialogResult.OK; this.Close(); } catch (Exception ex) { ServerForm.LogException(0, 0, 0, "OK Button", string.Format("Exception on closing form: {0}.", ex.ToString())); } }
/// <summary> /// Create a list of valid IP addresses on this PC so that the user can select one on which to run the ASCOM device server. /// </summary> private void PopulateAddressList() { bool foundAnIPAddress = false; bool foundTheIPAddress = false; int selectedIndex = 0; ServerForm.LogMessage(0, 0, 0, "PopulateAddressList", "Start"); addressList.Items.Clear(); deviceNumberIndexes = new Dictionary <string, int>(); // Create a dictionary to hold the current device instance numbers of every device type // Add IPv4 addresses if (RadIpV4.Checked | RadIpV4AndV6.Checked) // IPv4 addresses are required { // Add a local host entry addressList.Items.Add(SharedConstants.LOCALHOST_NAME_IPV4); // Make "localhost" the first entry in the list of IPv4 addresses foreach (IPAddress ipAddress in HostPc.IpV4Addresses) { addressList.Items.Add(ipAddress.ToString()); ServerForm.LogMessage(0, 0, 0, "PopulateAddressList", string.Format(" Added {0} Address: {1}", ipAddress.AddressFamily.ToString(), ipAddress.ToString())); foundAnIPAddress = true; if (ipAddress.ToString() == ServerForm.ServerIPAddressString) { selectedIndex = addressList.Items.Count - 1; foundTheIPAddress = true; } } } // Add IPv6 addresses if (RadIpV6.Checked | RadIpV4AndV6.Checked) // IPv6 addresses are required { foreach (IPAddress ipAddress in HostPc.IpV6Addresses) { addressList.Items.Add($"[{ipAddress}]"); ServerForm.LogMessage(0, 0, 0, "PopulateAddressList", string.Format(" Added {0} Address: {1}", ipAddress.AddressFamily.ToString(), ipAddress.ToString())); foundAnIPAddress = true; if ($"[{ipAddress}]" == ServerForm.ServerIPAddressString) { selectedIndex = addressList.Items.Count - 1; foundTheIPAddress = true; } } } ServerForm.LogMessage(0, 0, 0, "PopulateAddressList", string.Format($"Found an IP address: {foundAnIPAddress}, Found the IP address: {foundTheIPAddress}, Stored IP Address: {ServerForm.ServerIPAddressString}")); if ((!foundTheIPAddress) & (ServerForm.ServerIPAddressString != "")) // Add the last stored IP address if it isn't found in the search above { if (ServerForm.ServerIPAddressString == "+") // Handle the "all addresses special case { addressList.Items.Add(ServerForm.ServerIPAddressString); // Add the stored address to the list selectedIndex = addressList.Items.Count - 1; // Select this item in the list } else // One specific address so add it if it parses OK { IPAddress serverIpAddress = IPAddress.Parse(ServerForm.ServerIPAddressString); if ( ((serverIpAddress.AddressFamily == AddressFamily.InterNetwork) & ((RadIpV4.Checked | RadIpV4AndV6.Checked))) | ((serverIpAddress.AddressFamily == AddressFamily.InterNetworkV6) & ((RadIpV6.Checked | RadIpV4AndV6.Checked))) ) { addressList.Items.Add(ServerForm.ServerIPAddressString); // Add the stored address to the list selectedIndex = addressList.Items.Count - 1; // Select this item in the list } else { selectedIndex = 0; } } } // Add the wild card addresses at the end of the list // Include the strong wild card character in the list of addresses if not already in use if (ServerForm.ServerIPAddressString != SharedConstants.STRONG_WILDCARD_NAME) { addressList.Items.Add(SharedConstants.STRONG_WILDCARD_NAME); } //if (ServerForm.ServerIPAddressString != SharedConstants.WEAK_WILDCARD_NAME) addressList.Items.Add(SharedConstants.WEAK_WILDCARD_NAME); // Include the weak wild card character in the list of addresses if not already in use addressList.SelectedIndex = selectedIndex; }