private void initializeIrrlichtDevice(object sender, EventArgs e) { if (comboBoxVideoDriver.SelectedItem == null) return; // if rendering in progress, we are sending cancel request and waiting for its finishing if (backgroundRendering.IsBusy) { backgroundRendering.CancelAsync(); while (backgroundRendering.IsBusy) Application.DoEvents(); // this is not very correct way, but its very short, so we use it // redraw the panel, otherwise last rendered frame will stay as garbage panelRenderingWindow.Invalidate(); } // collect settings and start background worker with these settings DeviceSettings s = new DeviceSettings( checkBoxUseSeparateWindow.Checked ? IntPtr.Zero : panelRenderingWindow.Handle, (DriverType)comboBoxVideoDriver.SelectedItem, (byte)(comboBoxAntiAliasing.SelectedIndex == 0 ? 0 : Math.Pow(2, comboBoxAntiAliasing.SelectedIndex)), comboBoxBackground.SelectedIndex == 0 ? null : new Color(comboBoxBackground.SelectedIndex == 1 ? 0xFF000000 : 0xFFFFFFFF), checkBoxUseVSync.Checked ); backgroundRendering.RunWorkerAsync(s); labelRenderingStatus.Text = "Starting rendering..."; }
private bool EnrollDevice(DeviceSettings device) { string alias = device.alias ?? defaults.alias; string mac = device.mac ?? defaults.mac; string ip = device.ip ?? defaults.ip; string ssid = device.ssid ?? defaults.ssid; string password = device.password ?? defaults.password; var enctype = device.encryptionType ?? defaults.encryptionType ?? WLanKeyType.WPA; var iface = new PlugInterface(ip); try { var sysconfig = new PlugSystem(iface); var clock = new Clock(iface); var wlan = new WLan(iface); sysconfig.Refresh(); if (!string.IsNullOrEmpty(mac)) { if (mac != sysconfig.MacAddress) { Console.WriteLine($"Skipping device (mac mismatch {mac} != {sysconfig.MacAddress}"); return(true); } } Console.WriteLine($"MAC={sysconfig.MacAddress} DID={sysconfig.DeviceId} FID={sysconfig.FirmwareId} Alias={sysconfig.Alias}"); if (!string.IsNullOrEmpty(alias)) { Console.Write("Setting alias..."); sysconfig.SetAlias(alias); Console.WriteLine("OK"); } Console.Write("Setting date/time..."); clock.DateTime = DateTime.Now; Console.WriteLine("OK"); Console.Write("Setting WLAN params..."); wlan.AssociateWithStation(ssid, password, enctype); Console.WriteLine("OK"); return(true); } catch (Exception any) { Console.WriteLine($"error: {any.Message}"); return(false); } }
public void Commit() { if (this.Device != null) { DeviceSettings.Set(this.Device.WinMoDeviceId, "SyncAutomatically", this.SyncAutomatically); DeviceSettings.Set(this.Device.WinMoDeviceId, "ImportPictures", this.ImportPictures); DeviceSettings.Set(this.Device.WinMoDeviceId, "ResizePhotos", this.ResizePhotos); DeviceSettings.Set(this.Device.WinMoDeviceId, "VideoOptimizationStrategy", this.VideoOptimizationStrategy); if (this.Device.Name != this.Name) { this.Device.SetFriendlyName(this.Name); } } }
static void RegisterModuleSimulators(DeviceSettings deviceSettings, IServiceCollection services) { if (deviceSettings == null) { throw new ArgumentNullException(nameof(deviceSettings)); } if (deviceSettings.SimulationSettings == null) { throw new ArgumentNullException("No device simulation configuration has been configured."); } if (services == null) { throw new ArgumentNullException(nameof(services)); } if (deviceSettings.SimulationSettings.EnableModules) { var modules = Configuration.Get <ModulesSettings>(); if (modules != null && modules.Modules != null && modules.Modules.Any()) { IServiceProvider serviceProvider = services.BuildServiceProvider(); if (serviceProvider == null) { throw new ApplicationException("IServiceProvider has not been resolved."); } ILoggerFactory loggerFactory = serviceProvider.GetService <ILoggerFactory>(); if (loggerFactory == null) { throw new ApplicationException("ILoggerFactory has not been resolved."); } foreach (var item in modules.Modules) { var simulator = new ModuleSimulationService( item, item.SimulationSettings, serviceProvider.GetService <ITelemetryMessageService>(), serviceProvider.GetService <IErrorMessageService>(), serviceProvider.GetService <ICommissioningMessageService>(), loggerFactory); services.AddSingleton <IModuleSimulationService, ModuleSimulationService>(iServiceProvider => simulator); } } } }
/// <summary> /// This callback function is called immediately before a device is created to allow the /// application to modify the device settings. The supplied settings parameter /// contains the settings that the framework has selected for the new device, and the /// application can make any desired changes directly to this structure. Note however that /// the sample framework will not correct invalid device settings so care must be taken /// to return valid device settings, otherwise creating the Device will fail. /// </summary> public void ModifyDeviceSettings(DeviceSettings settings, Caps caps) { // This application is designed to work on a pure device by not using // any get methods, so create a pure device if supported and using HWVP. if ((caps.DeviceCaps.SupportsPureDevice) && ((settings.BehaviorFlags & CreateFlags.HardwareVertexProcessing) != 0)) { settings.BehaviorFlags |= CreateFlags.PureDevice; } // We will be using multiple threads settings.presentParams.ForceNoMultiThreadedFlag = false; settings.BehaviorFlags |= CreateFlags.MultiThreaded; }
public static DeviceSettings ToDeviceSettings(this SettingsViewModel model) { DeviceSettings settings = DeviceSettings.Default(); settings.sleepAfterSeconds = (byte)(model.SleepWhenInactive ? model.SleepAfterSeconds : 0); settings.accelerationPercentage = (byte)model.AccelerationPercentage; settings.continuousScroll = model.LoopAroundItems; //_settingsViewModel.DoubleTapTime settings.volumeMinColor.SetBytes(BitConverter.GetBytes(model.VolumeMinColor)); settings.volumeMaxColor.SetBytes(BitConverter.GetBytes(model.VolumeMaxColor)); settings.mixChannelAColor.SetBytes(BitConverter.GetBytes(model.MixChannelAColor)); settings.mixChannelBColor.SetBytes(BitConverter.GetBytes(model.MixChannelBColor)); return(settings); }
public void DeviceSendStart(Actor actor, DeviceSettings deviceInfo) { DeviceSendStart(actor.ActorService.Context.ServiceName.ToString(), actor.ActorService.Context.ServiceTypeName, actor.ActorService.Context.ReplicaId, actor.ActorService.Context.PartitionId, actor.ActorService.Context.CodePackageActivationContext.ApplicationName, actor.ActorService.Context.CodePackageActivationContext.ApplicationTypeName, actor.ActorService.Context.NodeContext.NodeName, deviceInfo.SimulationSettings.SimulationId, deviceInfo.SimulationSettings.SimulationName, deviceInfo.DeviceServiceSettings.DeviceName, deviceInfo.DeviceServiceSettings.DeviceType); }
private void Initialize() { if (_initialized) { return; } DeviceSettings settings = DeviceSettings.Instance; _host = new AppServiceHost(settings.ServerPrefix, settings.ServiceRootPath, settings.ServiceActionRootPath, settings.ServiceCredentials); DisplayIpAddress(); _host.Init(); _initialized = true; }
public DesignMainController() { this.CurrentDevice = new DesignDevice(); DeviceSettings.InitSettingsModel(this.CurrentDevice.WinMoDeviceId); this.CurrentSyncPartnership = new DesignSyncPartnership(); this.MainViewModel = new DesignMainViewModel(this); this.MainViewModel.DeviceViewModel.Device = this.CurrentDevice; this.ConnectedDevices = new List <IDevicePropertiesViewModel>(); this.ConnectedDevices.Add(new DevicePropertiesViewModel(this.CurrentDevice)); this.CurrentDeviceIndex = 0; DesignDevice device = new DesignDevice("Second Device"); this.ConnectedDevices.Add(new DevicePropertiesViewModel(device)); }
private bool Initialize() { if (!_initialized) { try { // initialize PiCar _piCar = PiCarClientFactory.CreatePiCar(_controlTopic.Server, _controlTopic.Credential); if (_piCar != null) { _piCar.Initialize(_controlTopic.ServerAddress, _controlTopic.VideoPort); _cameraHorizontalServo = new ServoStat { Servo = _piCar.HeadHorizontalServo }; _cameraVertialServo = new ServoStat { Servo = _piCar.HeadVerticalServo }; _rightLed = new LedState { Led = _piCar.RightLed }; _leftLed = new LedState { Led = _piCar.LeftLed }; // initialize AppServiceHost DeviceSettings settings = DeviceSettings.Instance; _host = new AppServiceHost(settings.ServerPrefix, settings.ServiceRootPath, settings.ServiceActionRootPath, settings.ServiceCredentials); _host.Init(); _initialized = true; } } catch (Exception err) { responseLabel.Text = "Failed to initialize PiCar \n" + err.ToString(); } } if (_initialized) { CommandButton.IsEnabled = true; GpioButton.IsEnabled = true; ServiceOnOffButton.IsEnabled = true; } else { CommandButton.IsEnabled = false; GpioButton.IsEnabled = false; ServiceOnOffButton.IsEnabled = false; } return(_initialized); }
public void DeviceFailedConnection(Actor actor, DeviceSettings deviceInfo, int retryCount) { DeviceFailedConnection(actor.ActorService.Context.ServiceName.ToString(), actor.ActorService.Context.ServiceTypeName, actor.ActorService.Context.ReplicaId, actor.ActorService.Context.PartitionId, actor.ActorService.Context.CodePackageActivationContext.ApplicationName, actor.ActorService.Context.CodePackageActivationContext.ApplicationTypeName, actor.ActorService.Context.NodeContext.NodeName, deviceInfo.SimulationSettings.SimulationId, deviceInfo.SimulationSettings.SimulationName, deviceInfo.DeviceServiceSettings.DeviceName, deviceInfo.DeviceServiceSettings.DeviceType, retryCount); }
private void InitLabels() { labelVersion.Text = labelVersion.Text + Spinetester.instance.Model.VersionString; // Hardware labelSerialVal.Text = Spinetester.instance.Model.SerialString; labelFirmwareVal.Text = Spinetester.instance.Model.FirmwareString; labelCOMVal.Text = ConnectionManager.instance.PortName; labelUSBChipVal.Text = ConnectionManager.instance.ChipName; labelHXVal.Text = Spinetester.instance.Model.Amplifier; labelBluetoothVal.Text = Common.NoData; // Sensors labelCurrentL.Text = Spinetester.instance.Settings.ScaleLeft.ToString(); labelCurrentR.Text = Spinetester.instance.Settings.ScaleRight.ToString(); labelFactoryL.Text = Spinetester.instance.Factory.ScaleLeft.ToString(); labelFactoryR.Text = Spinetester.instance.Factory.ScaleRight.ToString(); // Spine labelCurrentSpineVal.Text = Spinetester.instance.Settings.FixedDeflection.ToString(); labelFactorySpineVal.Text = Spinetester.instance.Factory.FixedDeflection.ToString(); // Amplifier freq labelAmpCurrentVal.Text = Spinetester.instance.Settings.HX711Frequency.ToString(); labelAmpFactoryVal.Text = Spinetester.instance.Factory.HX711Frequency.ToString(); // Spine threashold labelSpThCurrentVal.Text = Spinetester.instance.Settings.SpineDifference.ToString(); labelSpThFactoryVal.Text = Spinetester.instance.Factory.SpineDifference.ToString(); // Speaker volume labelVolumeVal.Text = Spinetester.instance.Settings.SpeakerVolume.ToString(); labelVolumeFactory.Text = Spinetester.instance.Factory.SpeakerVolume.ToString(); // Language labelLanguageVal.Text = DeviceSettings.GetLanguageName(Spinetester.instance.Settings.Language); labelLanguageFactory.Text = DeviceSettings.GetLanguageName(0); if (Spinetester.instance.Model.Firmware < 1.1) { groupBoxConfiguration.Visible = false; } if (!Settings.DebugMode) { tensionUC.Visible = false; } }
public void SetUp() { _d3D = new Direct3D(); _form = new Form(); _deviceSettings = new DeviceSettings { PresentParameters = new PresentParameters { BackBufferWidth = 10, BackBufferHeight = 10, EnableAutoDepthStencil = false, DeviceWindowHandle = _form.Handle, } }; }
public void UnpartnerWithPhone() { if (((this.CurrentSyncPartnership.CurrentState == PartnershipState.Idle) && (MessageBox.Show(Resources.ForgetDeviceWarningText, Resources.ForgetDeviceWarningTitle, MessageBoxButton.YesNo, MessageBoxImage.Exclamation, MessageBoxResult.No) == MessageBoxResult.Yes)) && (this.CurrentDevice != null)) { if (DeviceSettings.ForgetDeviceSettings(this.CurrentDevice.WinMoDeviceId)) { this.repository.RemoveSyncPartnership(this.CurrentDevice.WinMoDeviceId); this.MainViewModel.SetMainView(MainViewState.FirstConnectPanel); this.MainViewModel.NextDeviceCommand.Execute(null); } else { Errors.ShowError(Microsoft.WPSync.UI.Properties.Resources.ForgetPhoneFilesError, new object[0]); } } }
/// <summary> /// get the service port in ":nnnn" /// </summary> public string GetServicePort() { DeviceSettings settings = DeviceSettings.Instance; string port; int index = settings.ServerPrefix.IndexOf(':', 6); // skip http: or https: if (index > 1) { port = settings.ServerPrefix.Substring(index); } else { port = string.Empty; } return(port); }
private bool ReadStartupSettings() { bool res = true; try { string ssfilename = ApplicationData.Current.LocalFolder.Path + "\\" + GlobalVars.HardWareID + ".012"; CurrentDeviceSettings = (Deserialize <DeviceSettings>(File.ReadAllText(ssfilename))); } catch { res = false; CurrentDeviceSettings = new DeviceSettings(); } return(res); }
private void InitSources() { if (DeviceSettings.GetDeviceDirectories().Count <string>() > 0) { switch ((GlobalSetting.GetApplicationSetting("MusicSyncSource") as string)) { case "ITunes": this.musicSyncSource = DependencyContainer.ResolveITunesMusicSyncSource(); break; case "WindowsLibraries": this.musicSyncSource = DependencyContainer.ResolveWindowsLibraryMusicSyncSource(); break; } } this.photoSyncSource = DependencyContainer.ResolvePhotosSyncSource(); }
public bool Validate() { string applicationSetting = (string)GlobalSetting.GetApplicationSetting("MusicSyncSource"); if (applicationSetting != this.MusicSyncSource) { if (!this.controller.CanResetMusicSyncSourceType()) { MessageBox.Show(Resources.CantSwitchSyncSourceText, Resources.CantSwitchSyncSourceTitle, MessageBoxButton.OK, MessageBoxImage.Exclamation); return(false); } if ((DeviceSettings.GetDeviceDirectories().FirstOrDefault <string>() != null) && (MessageBox.Show(Resources.SwitchSyncSourceWarningText, Resources.SwitchSyncSourceWarningTitle, MessageBoxButton.YesNo, MessageBoxImage.Exclamation, MessageBoxResult.No) == MessageBoxResult.No)) { return(false); } } return(true); }
public void SaveSettings(Settings settings) { foreach (DeviceVisualizer visualizer in deviceVisualizers) { DeviceSettings deviceSetting = settings.Devices.Where(x => x.Id == visualizer.Id).FirstOrDefault(); if (deviceSetting != null) { deviceSetting.Location = visualizer.Location; } else { deviceSetting = new DeviceSettings(); deviceSetting.Id = visualizer.Id; deviceSetting.Location = visualizer.Location; settings.Devices.Add(deviceSetting); } } }
public Task ProcessEventsAsync(PartitionContext context, IEnumerable <EventData> messages) { try { foreach (EventData eventData in messages) { // This case shows the new planed convention. Use EventType as Key and CommandType as Value if (eventData.Properties.ContainsKey(Commands.EventType.D2C_COMMAND) && ((string)eventData.Properties[Commands.EventType.D2C_COMMAND] == Commands.CommandType.CAPTURE_UPLOADED)) { string serializedDeviceState = Encoding.UTF8.GetString(eventData.GetBytes()); DeviceSettings DeviceSettings = JsonConvert.DeserializeObject <DeviceSettings>(serializedDeviceState); Task.Factory.StartNew(() => ProcessImage(DeviceSettings)); } // UPDATE_DASHBOARD_CONTROLS else if (eventData.Properties.ContainsKey(IsmIoTPortal.CommandType.D2C_COMMAND) && (string)eventData.Properties[IsmIoTPortal.CommandType.D2C_COMMAND] == IsmIoTPortal.CommandType.UPDATE_DASHBOARD_CONTROLS) { string serializedDeviceSettings = Encoding.UTF8.GetString(eventData.GetBytes()); DeviceSettings DeviceSettings = JsonConvert.DeserializeObject <DeviceSettings>(serializedDeviceSettings); Task.Factory.StartNew(() => UpdateDashboardDeviceStateControls(DeviceSettings)); } else if (eventData.Properties.ContainsKey(IsmIoTPortal.CommandType.D2C_COMMAND) && (string)eventData.Properties[IsmIoTPortal.CommandType.D2C_COMMAND] == IsmIoTPortal.CommandType.FIRMWARE_UPDATE_STATUS) { string serializedUpdateState = Encoding.UTF8.GetString(eventData.GetBytes()); var updateState = JsonConvert.DeserializeObject <UpdateState>(serializedUpdateState); Task.Factory.StartNew(() => UpdateFirmwareUpdateStatus(updateState)); } } } catch (Exception ex) { //... } context.CheckpointAsync(); if (this.checkpointStopWatch.Elapsed > TimeSpan.FromMinutes(5)) { lock (this) { this.checkpointStopWatch.Reset(); return(context.CheckpointAsync()); } } return(Task.FromResult <object>(null)); }
private void batch_Yes_Click(object sender, RoutedEventArgs e) { batchInput.Visibility = Visibility.Collapsed; var input = batch_botText.Text; var inputRows = input.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries); foreach (var row in inputRows) { try { var rowData = row.Split(';'); var auth = char.ToUpper(rowData[0][0]) + rowData[0].Substring(1); var login = rowData[1]; var pass = rowData[2]; var proxy = rowData.Length > 3 ? rowData[3] : ""; var proxyLogin = rowData.Length > 4 ? rowData[4] : ""; var proxyPass = rowData.Length > 5 ? rowData[5] : ""; var desiredName = rowData.Length > 6 ? rowData[6] : ""; var path = login; var lat = rowData.Length > 7 ? rowData[7] : ""; var lon = rowData.Length > 8 ? rowData[8] : ""; var created = false; do { if (!Directory.Exists(SubPath + "\\" + path)) { CreateBotFromClone(path, login, auth, pass, proxy, proxyLogin, proxyPass, desiredName, lat, lon); created = true; } else { path += DeviceSettings.RandomString(4); } } while (!created); } catch (Exception) { //ignore } } batch_botText.Text = Empty; }
private void CreateBotFromClone(string path, string login, string auth, string pass, string proxy, string proxyLogin, string proxyPass, string desiredName) { var dir = Directory.CreateDirectory(SubPath + "\\" + path); var settings = GlobalSettings.Load(dir.FullName) ?? GlobalSettings.Load(dir.FullName); if (Bot != null) { settings = Bot.GlobalSettings.Clone(); var profilePath = dir.FullName; var profileConfigPath = Path.Combine(profilePath, "config"); settings.ProfilePath = profilePath; settings.ProfileConfigPath = profileConfigPath; settings.GeneralConfigPath = Path.Combine(Directory.GetCurrentDirectory(), "config"); } //set new settings Enum.TryParse(auth, out settings.Auth.AuthType); if (settings.Auth.AuthType == AuthType.Google) { settings.Auth.GoogleUsername = login; settings.Auth.GooglePassword = pass; } else { settings.Auth.PtcUsername = login; settings.Auth.PtcPassword = pass; } if (proxy != "") { settings.Auth.UseProxy = true; settings.Auth.ProxyUri = proxy; settings.Auth.ProxyLogin = proxyLogin; settings.Auth.ProxyPass = proxyPass; } if (desiredName != "") { settings.DesiredNickname = desiredName; settings.StartUpSettings.AutoCompleteTutorial = true; } settings.Device.DeviceId = DeviceSettings.RandomString(16, "0123456789abcdef"); settings.StoreData(dir.FullName); InitBot(settings, path); }
public void InitScreen2(Control surfaceFullScreen) { try { m_RenderingSurface2 = new Control(); m_RenderingSurface2 = surfaceFullScreen; DeviceSettings settingsFullScreen = new DeviceSettings() { Width = m_RenderingSurface2.ClientSize.Width, Height = m_RenderingSurface2.ClientSize.Height }; m_D2DContext.InitScreen2(m_RenderingSurface2.Handle, settingsFullScreen); } catch (Exception ex) { Logger.LogFile(ex.Message, "", "InitScreen2", ex.LineNumber(), "GraphicUtilDX"); } }
public sealed override void UpdateSettings() { DeviceStep nextStep = new NoOpStep(DeviceSettings.GetTickCount(DeviceSettings.CardReaderInitialization), initializationDescription); FirstInputDeviceStep = nextStep; nextStep.NextStep = new OpenStreamStep(); nextStep = nextStep.NextStep; nextStep.NextStep = new TextReadStep(recordWordCount); nextStep = nextStep.NextStep; nextStep.NextStep = new CloseStreamStep(); nextStep = nextStep.NextStep; nextStep.NextStep = new WriteToMemoryStep(false, recordWordCount) { NextStep = null }; FirstOutputDeviceStep = null; FirstIocDeviceStep = null; }
public sealed override void UpdateSettings() { var tickCount = DeviceSettings.GetTickCount(DeviceSettings.DiskInitialization); DeviceStep nextStep = new NoOpStep(tickCount, initializationDescription); FirstInputDeviceStep = nextStep; nextStep.NextStep = new OpenStreamStep(); nextStep = nextStep.NextStep; nextStep.NextStep = new SeekStep(); nextStep = nextStep.NextStep; nextStep.NextStep = new BinaryReadStep(WordsPerSector); nextStep = nextStep.NextStep; nextStep.NextStep = new CloseStreamStep(); nextStep = nextStep.NextStep; nextStep.NextStep = new WriteToMemoryStep(true, WordsPerSector) { NextStep = null }; nextStep = new NoOpStep(tickCount, initializationDescription); FirstOutputDeviceStep = nextStep; nextStep.NextStep = new ReadFromMemoryStep(true, WordsPerSector); nextStep = nextStep.NextStep; nextStep.NextStep = new OpenStreamStep(); nextStep = nextStep.NextStep; nextStep.NextStep = new SeekStep(); nextStep = nextStep.NextStep; nextStep.NextStep = new BinaryWriteStep(WordsPerSector); nextStep = nextStep.NextStep; nextStep.NextStep = new CloseStreamStep { NextStep = null }; nextStep = new NoOpStep(tickCount, initializationDescription); FirstIocDeviceStep = nextStep; nextStep.NextStep = new SeekStep { NextStep = null }; }
public void ModifyDeviceSettings(DeviceSettings settings, Microsoft.DirectX.Direct3D.Caps caps) { // If device doesn't support HW T&L or doesn't support 1.1 vertex shaders in HW // then switch to SWVP. if ((!caps.DeviceCaps.SupportsHardwareTransformAndLight) || (caps.VertexShaderVersion < new Version(1, 1))) { settings.BehaviorFlags = CreateFlags.SoftwareVertexProcessing; } else { settings.BehaviorFlags = CreateFlags.HardwareVertexProcessing; } // This application is designed to work on a pure device by not using // any get methods, so create a pure device if supported and using HWVP. if ((caps.DeviceCaps.SupportsPureDevice) && ((settings.BehaviorFlags & CreateFlags.HardwareVertexProcessing) != 0)) { settings.BehaviorFlags |= CreateFlags.PureDevice; } // Debugging vertex shaders requires either REF or software vertex processing // and debugging pixel shaders requires REF. #if (DEBUG_VS) if (settings.DeviceType != DeviceType.Reference) { settings.BehaviorFlags &= ~CreateFlags.HardwareVertexProcessing; settings.BehaviorFlags |= CreateFlags.SoftwareVertexProcessing; } #endif #if (DEBUG_PS) settings.DeviceType = DeviceType.Reference; #endif // For the first device created if its a REF device, optionally display a warning dialog box if (settings.DeviceType == DeviceType.Reference) { Utility.DisplaySwitchingToRefWarning(sampleFramework, "ProgressiveMesh"); } }
void SetSize(Device device) { TextAsset profile = Resources.Load <TextAsset>("Profiles/" + device.SettingsFile.Replace(".txt", "")); if (profile == null) { currentSetting = new DeviceSettings(); } else { currentSetting = JsonUtility.FromJson <DeviceSettings>(profile.text); } float top = 1.0f - currentSetting.UITopOffset; float left = 1.0f - currentSetting.UILeftOffset; float bottom = 1.0f - currentSetting.UIBottomOffset; float right = 1.0f - currentSetting.UIRightOffset; SizerPanel.anchoredPosition = new Vector2(CanvasRect.sizeDelta.x * left, -CanvasRect.sizeDelta.y * top); SizerPanel.sizeDelta = new Vector2(CanvasRect.sizeDelta.x - right * CanvasRect.sizeDelta.x - SizerPanel.anchoredPosition.x, CanvasRect.sizeDelta.y - bottom * CanvasRect.sizeDelta.y - Mathf.Abs(SizerPanel.anchoredPosition.y)); }
private void RetrieveSettings(DeviceSettings lstDS) { ProccessStatusReq psr = new ProccessStatusReq("admin", "!QAZ2wsx", txtIPAddress.Text); try { foreach (EndPoint ds in lstDS) { var epLog = psr.GetEndPointLog(ds.EndPointName, ds.ResourceURI); if (epLog != null) { ProcessParentData(psr, epLog, ds.ListParents); ds.HasValues = true; } } } catch (Exception ex) { MessageBox.Show(ex.Message, "Device Communication", MessageBoxButtons.OK, MessageBoxIcon.Warning); } }
public async Task <ActionResult> Dashboard([Bind(Include = "DeviceId,VarianceThreshold,DistanceMapThreshold,RGThreshold,RestrictedFillingThreshold,DilateValue,CapturePeriod")] DeviceSettings deviceSettings) { // Check Device ID against a whitelist of values to prevent XSS if (!IsmIoTSettings.RegexHelper.Text.IsMatch(deviceSettings.DeviceId)) { return(HttpNotFound()); } // If device doesn't exist, redirect to index // The rest of the user input is sanitized by parsing the value to numbers if (await registryManager.GetDeviceAsync(deviceSettings.DeviceId) == null) { return(RedirectToAction("Index")); } // C2D Message die dem Device einen durch die Controls veränderten DeviceState mitteilt await C2DSetDeviceStateAsync(deviceSettings.DeviceId, deviceSettings); //ModelState.Clear(); return(View(deviceSettings)); }
// GET: IsmDevices/Dashboard/<DeviceId> public async Task <ActionResult> Dashboard(string deviceId) { // Check Device ID against a whitelist of values to prevent XSS if (!IsmIoTSettings.RegexHelper.Text.IsMatch(deviceId)) { return(HttpNotFound()); } // If device doesn't exist, redirect to index if (await registryManager.GetDeviceAsync(deviceId) == null) { return(RedirectToAction("Index")); } // Load page DeviceSettings deviceSettings = new DeviceSettings(); deviceSettings.DeviceId = deviceId; //await C2DGetDeviceStateAsync(DeviceId); return(View(deviceSettings)); }
public ISNMPDeviceSettingDTO EditSNMPSetting(string oldID, string ID, string initialIPAndMask, string finalIPAndMask, string SNMPUser) { ISNMPDeviceSettingDTO setting; //Validation if (DeviceSettings == null || !DeviceSettings.ContainsKey(oldID)) { return(null); } //Changing values of reference does not interfere on process targets. They keep the track of objects setting = DeviceSettings[oldID]; setting.EditDeviceSetting(ID, initialIPAndMask, finalIPAndMask, SNMPUser); if (oldID != ID) { DeviceSettings.Remove(oldID); DeviceSettings.Add(ID, setting); } return(setting); }
/// <summary> /// Initializes Direct3D using passed in settings. /// </summary> private void InitializeDirect3D( bool windowed, Control renderTarget, int desiredWidth, int desiredHeight ) { this.windowed = windowed; this.renderTarget = renderTarget; this.displayMode = Manager.Adapters[ 0 ].CurrentDisplayMode; //if ( !windowed ) //{ displayMode.Width = desiredWidth; displayMode.Height = desiredHeight; //} d3dEnum.EnumerateAdapters(); // Create the device settings windowedSettings = FindBestWindowedSettings(); fullscreenSettings = FindBestFullscreenSettings(); currentSettings = windowed ? windowedSettings : fullscreenSettings; try { device = new Device( ( int )currentSettings.AdapterOrdinal, currentSettings.DeviceType, renderTarget, currentSettings.BehaviorFlags, currentSettings.PresentParameters ); } catch ( DirectXException ) { throw new DirectXException( "Unable to create the Direct3D device." ); } // Cancel automatic device reset on resize device.DeviceResizing += new System.ComponentModel.CancelEventHandler( CancelResize ); device.DeviceLost += new EventHandler( OnDeviceLost ); device.DeviceReset += new EventHandler( OnDeviceReset ); device.Disposing += new EventHandler( OnDeviceDisposing ); // What vertex and pixel shader versions are supported? Caps caps = Manager.GetDeviceCaps( ( int )currentSettings.AdapterOrdinal, currentSettings.DeviceType ); canDoPS11 = caps.PixelShaderVersion >= new Version( 1, 1 ); canDoPS20 = caps.PixelShaderVersion >= new Version( 2, 0 ); canDoPS30 = caps.PixelShaderVersion >= new Version( 3, 0 ); canDoVS11 = caps.VertexShaderVersion >= new Version( 1, 1 ); canDoVS20 = caps.VertexShaderVersion >= new Version( 2, 0 ); canDoVS30 = caps.VertexShaderVersion >= new Version( 3, 0 ); BuildProjectionMatrix( new Size( desiredWidth, desiredHeight ) ); }
/// <summary> /// Changes the device with the new settings. /// </summary> public void ChangeDevice( DeviceSettings newSettings ) { windowed = newSettings.PresentParameters.Windowed; if ( newSettings.PresentParameters.Windowed ) windowedSettings = ( DeviceSettings )newSettings.Clone(); else fullscreenSettings = ( DeviceSettings )newSettings.Clone(); if ( device != null ) { device.Dispose(); device = null; } try { device = new Device( ( int )newSettings.AdapterOrdinal, newSettings.DeviceType, renderTarget, newSettings.BehaviorFlags, newSettings.PresentParameters ); // Cancel automatic device reset on resize device.DeviceResizing += new System.ComponentModel.CancelEventHandler( CancelResize ); device.DeviceLost += new EventHandler( OnDeviceLost ); device.DeviceReset += new EventHandler( OnDeviceReset ); device.Disposing += new EventHandler( OnDeviceDisposing ); OnDeviceReset( this, null ); } catch ( DirectXException ) { throw new DirectXException( "Unable to recreate the Direct3D device while changing settings" ); } currentSettings = windowed ? windowedSettings : fullscreenSettings; }
/// <summary> /// Finds the best windowed Device settings supported by the system. /// </summary> /// <returns> /// A DeviceSettings class full with the best supported windowed settings. /// </returns> private DeviceSettings FindBestWindowedSettings() { DeviceSettingsEnum bestSettings = null; bool foundBest = false; // Loop through each adapter foreach ( AdapterEnum a in d3dEnum.Adapters ) { // Loop through each device foreach ( DeviceEnum d in a.DeviceEnumList ) { // Loop through each device settings configuration foreach ( DeviceSettingsEnum s in d.SettingsList ) { // Must be windowed mode and the AdapterFormat must match current DisplayMode Format if ( !s.Windowed || ( s.AdapterFormat != displayMode.Format ) ) { continue; } // The best DeviceSettingsEnum is a DeviceType.Hardware Device // where its BackBufferFormat is the same as the AdapterFormat if ( ( bestSettings == null ) || ( ( s.DeviceType == DeviceType.Hardware ) && ( s.AdapterFormat == s.BackBufferFormat ) ) || ( ( bestSettings.DeviceType != DeviceType.Hardware ) && ( s.DeviceType == DeviceType.Hardware ) ) ) { if ( !foundBest ) { bestSettings = s; } if ( ( s.DeviceType == DeviceType.Hardware ) && ( s.AdapterFormat == s.BackBufferFormat ) ) { foundBest = true; } } } } } if ( bestSettings == null ) { throw new DirectXException( "Unable to find any supported window mode settings." ); } // Store the best settings DeviceSettings windowedSettings = new DeviceSettings(); windowedSettings.AdapterFormat = bestSettings.AdapterFormat; windowedSettings.AdapterOrdinal = bestSettings.AdapterOrdinal; windowedSettings.BehaviorFlags = ( CreateFlags )bestSettings.VertexProcessingTypeList[ 0 ]; windowedSettings.Caps = bestSettings.DeviceInformation.Caps; windowedSettings.DeviceType = bestSettings.DeviceType; windowedSettings.PresentParameters = new PresentParameters(); windowedSettings.PresentParameters.AutoDepthStencilFormat = ( DepthFormat )bestSettings.DepthStencilFormatList[ 0 ]; windowedSettings.PresentParameters.BackBufferCount = 1; windowedSettings.PresentParameters.BackBufferFormat = bestSettings.AdapterFormat; windowedSettings.PresentParameters.BackBufferHeight = 0; windowedSettings.PresentParameters.BackBufferWidth = 0; windowedSettings.PresentParameters.DeviceWindow = renderTarget; windowedSettings.PresentParameters.EnableAutoDepthStencil = true; windowedSettings.PresentParameters.FullScreenRefreshRateInHz = 0; windowedSettings.PresentParameters.MultiSample = ( MultiSampleType )bestSettings.MultiSampleTypeList[ 0 ]; windowedSettings.PresentParameters.MultiSampleQuality = 0; windowedSettings.PresentParameters.PresentationInterval = ( PresentInterval )bestSettings.PresentIntervalList[ 0 ]; windowedSettings.PresentParameters.PresentFlag = PresentFlag.DiscardDepthStencil; windowedSettings.PresentParameters.SwapEffect = SwapEffect.Discard; windowedSettings.PresentParameters.Windowed = true; return windowedSettings; }
internal DeviceWorker(DeviceSettings deviceSettings) { _deviceSettings = deviceSettings; lock(DeviceLock) _thread.Enqueue(Initialize); }
private void CreateDevice(Direct3D d3D, DeviceSettings deviceSettings) { Device device; if(!TryCreateHardwareDevice(d3D, deviceSettings, out device) && !TryCreateSoftwareDevice(d3D, deviceSettings, out device)) CreateReferenceDevice(d3D, deviceSettings, out device); Device = device; }
private static bool TryCreateDevice(Direct3D d3D, DeviceSettings deviceSettings, DeviceType deviceType, CreateFlags vertexProcessingFlag, out Device device) { Format adapterformat = d3D.Adapters[0].CurrentDisplayMode.Format; //для теней обязательно нужен stencil buffer. Ищем формат PresentParameters presentParameters = deviceSettings.PresentParameters; foreach(Format stencilformat in new[] {Format.D24S8, Format.D24SingleS8, Format.D24X4S4, Format.D15S1}) { if(d3D.CheckDeviceFormat(0, deviceType, adapterformat, Usage.DepthStencil, ResourceType.Surface, stencilformat) && d3D.CheckDepthStencilMatch(0, deviceType, adapterformat, adapterformat, stencilformat)) { presentParameters.EnableAutoDepthStencil = true; presentParameters.AutoDepthStencilFormat = stencilformat; break; } } //Выбираем тип multisampling var multiSamplingTypesToCheck = new Dictionary<MultisampleType, int>(); if(deviceSettings.AutoDetermineMultisampleType) multiSamplingTypesToCheck = new[] {MultisampleType.FourSamples, MultisampleType.TwoSamples, MultisampleType.None}.ToDictionary(x => x, x => (int)x); else { MultisampleType multType = deviceSettings.MultisampleType; multiSamplingTypesToCheck.Add(multType, (int)multType); } foreach(var i in multiSamplingTypesToCheck) { presentParameters.Multisample = i.Key; presentParameters.MultisampleQuality = i.Value; try { device = new Device(d3D, 0, deviceType, presentParameters.DeviceWindowHandle, CreateFlags.Multithreaded | vertexProcessingFlag, presentParameters); return true; } catch(Direct3D9Exception) { } } device = null; return false; }
private static void CreateReferenceDevice(Direct3D d3D, DeviceSettings deviceSettings, out Device device) { if(!TryCreateDevice(d3D, deviceSettings, DeviceType.Reference, CreateFlags.SoftwareVertexProcessing, out device)) throw new Exception("Unable to create any direct3d device"); }
private static bool TryCreateSoftwareDevice(Direct3D d3D, DeviceSettings deviceSettings, out Device device) { device = null; return TryRegisterSoftwareRenderer(d3D) && TryCreateDevice(d3D, deviceSettings, DeviceType.Software, CreateFlags.SoftwareVertexProcessing, out device); }
private static bool TryCreateHardwareDevice(Direct3D d3D, DeviceSettings deviceSettings, out Device device) { return TryCreateDevice(d3D, deviceSettings, DeviceType.Hardware, CreateFlags.HardwareVertexProcessing, out device); }
private void LoadProtocolsAndDevices(PVSettings.SettingsBase fileSettings) { foreach (XmlNode e in fileSettings.settings.ChildNodes) { if (e.NodeType == XmlNodeType.Element && e.Name == "protocol") { ProtocolSettings protocol = new ProtocolSettings(this, (XmlElement)e); _ProtocolList.Add(protocol); } else if (e.NodeType == XmlNodeType.Element && e.Name == "device") { DeviceSettings device = new DeviceSettings(this, (XmlElement)e); foreach (DeviceSettings.DeviceName name in device.Names) { DeviceListItem item = new DeviceListItem(); item.Id = name.Id; item.Description = name.Name; item.DeviceSettings = device; _DeviceList.Add(item); foreach (DeviceSettings.GroupName groupName in item.DeviceSettings.DeviceGroups) { string protocol = item.DeviceSettings.Protocol; DeviceGroup deviceGroup = FindOrCreateDeviceGroup(groupName.Id, groupName.Name, protocol); if (!deviceGroup.DeviceList.Contains(item)) deviceGroup.DeviceList.Add(item); deviceGroup = FindOrCreateDeviceGroup(protocol, "Protocol: " + protocol, protocol, true); if (!deviceGroup.DeviceList.Contains(item)) deviceGroup.DeviceList.Add(item); } } } } }
/// <inheritdoc /> public SimpleHttpResponseMessage ReceiveSystemSettingsFromUserInterface(Stream postData) { string romId, friendlyName, username, password; int temperatureThreshold, counter; NameValueCollection postKeyValuePairs; SimpleHttpResponseMessage result; // assume that the save will be succesful, for now result = new SimpleHttpResponseMessage(); result.Message = "success"; // parse the application/x-www-form-urlencoded POST data into a collection postKeyValuePairs = ConvertPostStreamIntoNameValueCollection(postData); username = GetValueFromNameValueCollectionAndThenRemoveItToo(postKeyValuePairs, "username"); password = GetValueFromNameValueCollectionAndThenRemoveItToo(postKeyValuePairs, "password"); if (!UsernameAndPasswordAreCorrect(username, password)) { result.Message = "unauthorized"; return result; } // save the system wide settings, of which there are two SystemSettings systemSettings = new SystemSettings(); systemSettings.DataStoreDurationInDays = Convert.ToInt32(GetValueFromNameValueCollectionAndThenRemoveItToo(postKeyValuePairs, "data-store-duration-in-days")); systemSettings.HoursThatMustPassBetweenSendingDeviceSpecificWarningEmails = Convert.ToInt32(GetValueFromNameValueCollectionAndThenRemoveItToo(postKeyValuePairs, "max-email-freq-in-hours")); systemSettings.WarningEmailRecipientsInCsv = GetValueFromNameValueCollectionAndThenRemoveItToo(postKeyValuePairs, "warning-email-recipients-csv"); // instantiate empty variables in preparation for saving device specific settings romId = String.Empty; friendlyName = String.Empty; temperatureThreshold = Int32.MaxValue; // save the device specific settings, of which there are two for each device // a romId is the key for each device counter = 0; foreach (string key in postKeyValuePairs.AllKeys) { if (key.ToLowerInvariant().Contains("rom-id")) { counter = 0; romId = postKeyValuePairs[key]; } else if (key.ToLowerInvariant().Contains("friendly-name")) { ++counter; friendlyName = postKeyValuePairs[key]; } else if (key.ToLowerInvariant().Contains("temp-threshold")) { ++counter; temperatureThreshold = Convert.ToInt32(postKeyValuePairs[key]); } if (counter > 0 && counter % DeviceSettings.SYSTEM_SETTINGS_DEVICE_DATA_COUNT == 0) { DeviceSettings deviceSettings = new DeviceSettings() { FriendlyName = friendlyName, TemperatureThreshold = temperatureThreshold }; if (systemSettings.DeviceSettingsDictionary.ContainsKey(romId)) { systemSettings.DeviceSettingsDictionary[romId] = deviceSettings; } else { systemSettings.DeviceSettingsDictionary.Add(romId, new DeviceSettings() { FriendlyName = friendlyName, TemperatureThreshold = temperatureThreshold }); } } } systemSettings.Save(); return result; }