protected override async void OnNavigatedTo( NavigationEventArgs e ) { base.OnNavigatedTo( e ); this.operationMode = OperationMode.Preview; this.speaker = new Speaker(); if( GpioDeviceBase.IsAvailable ) { this.led = new Led( 6 ); this.led.TurnOn(); this.pushButton = new PushButton( 16 ); this.pushButton.Pushed += this.OnPushButtonPushed; this.pnlButtons.Visibility = Visibility.Collapsed; } this.camera = new Camera(); await this.camera.InitializeAsync(); this.previewElement.Source = this.camera.CaptureManager; await this.camera.CaptureManager.StartPreviewAsync(); }
/// <summary> /// Initializes a new instance of the FaceTracker class from a reference of the Kinect device. /// <param name="sensor">Reference to kinect sensor instance</param> /// </summary> public FaceTracker(KinectSensor sensor) { if (sensor == null) { throw new ArgumentNullException("sensor"); } if (!sensor.ColorStream.IsEnabled) { throw new InvalidOperationException("Color stream is not enabled yet."); } if (!sensor.DepthStream.IsEnabled) { throw new InvalidOperationException("Depth stream is not enabled yet."); } this.operationMode = OperationMode.Kinect; this.coordinateMapper = sensor.CoordinateMapper; this.initializationColorImageFormat = sensor.ColorStream.Format; this.initializationDepthImageFormat = sensor.DepthStream.Format; var newColorCameraConfig = new CameraConfig( (uint)sensor.ColorStream.FrameWidth, (uint)sensor.ColorStream.FrameHeight, sensor.ColorStream.NominalFocalLengthInPixels, FaceTrackingImageFormat.FTIMAGEFORMAT_UINT8_B8G8R8X8); var newDepthCameraConfig = new CameraConfig( (uint)sensor.DepthStream.FrameWidth, (uint)sensor.DepthStream.FrameHeight, sensor.DepthStream.NominalFocalLengthInPixels, FaceTrackingImageFormat.FTIMAGEFORMAT_UINT16_D13P3); this.Initialize(newColorCameraConfig, newDepthCameraConfig, IntPtr.Zero, IntPtr.Zero, this.DepthToColorCallback); }
/// <summary> /// 插入一个节点 /// </summary> /// <param name="locationType">这里locationType.LocationDepth表示想要插入的位置</param> /// <param name="mode">插入的方式,有初始化、前插、后插三种</param> /// <returns></returns> public static bool Insert(Locationtype locationType, OperationMode mode) { try { ISQLExecutor executor = ConfigurationHelper.Instance.CreateNewSQLExecutor() as ISQLExecutor; bool isPosExist = executor.Exist(typeof(Locationtype), "LocationDepth=@LocationDepth", new List<object>() { locationType.LocationDepth }); if (executor == null) { return false; } int effectrow = 0; switch(mode) { case OperationMode.Initial: if (isPosExist) { return false; } // 初始化,深度肯定为0 locationType.LocationDepth = 0; effectrow = executor.Insert(typeof(Locationtype), new List<object>() { locationType }); break; case OperationMode.InsertAfter: if (!isPosExist) { return false; } executor.ExecuteNonQuery(ConfigurationHelper.Instance.SqlDictionary["ResetAllBeforeInsert"], new List<object>() { locationType.LocationDepth }); locationType.LocationDepth += 1; effectrow = executor.Insert(typeof(Locationtype), new List<object>() { locationType }); break; case OperationMode.InsertBefore: if (!isPosExist) { return false; } executor.ExecuteNonQuery(ConfigurationHelper.Instance.SqlDictionary["ResetAllBeforeInsert"], new List<object>() { locationType.LocationDepth - 1 }); effectrow = executor.Insert(typeof(Locationtype), new List<object>() { locationType }); break; default: break; } if (effectrow > 0) { return true; } } catch { return false; } return false; }
public WorldSector(int index_x, int index_y, int lower_boundary_x, int upper_boundary_x, int lower_boundary_y, int upper_boundary_y) { this.index_x = index_x; this.index_y = index_y; this.lower_boundary_x = lower_boundary_x; this.upper_boundary_x = upper_boundary_x; this.lower_boundary_y = lower_boundary_y; this.upper_boundary_y = upper_boundary_y; mode = OperationMode.OUT_OF_CHARACTER_RANGE; Contained_Objects = new GObject_Sector_RefList (new Vector2(index_x, index_y)); }
private Expression VisitStringInclusionMethod(MethodCallExpression node, OperationMode operationMode) { OperationMode oldState = _operationMode; _operationMode = operationMode; this.Visit(node.Object); this.CurrentOperation.Append("("); this.Visit(node.Arguments[0]); this.CurrentOperation.Append(")"); _operationMode = oldState; return node; }
public void PerformOperationOnList(OperationMode mode) { int position; bool isFound; switch (mode) { case OperationMode.Input: InputList(); break; case OperationMode.Insert: Insert(); break; case OperationMode.Search: Console.Write("Please enter an item to search: "); int itemToSearch = int.Parse(Console.ReadLine()); isFound = Search(itemToSearch, out position); if (isFound) { Console.WriteLine("Item found at {0} position", position); } else { Console.WriteLine("Item can not be found"); } break; case OperationMode.Delete: Delete(); break; case OperationMode.Display: Display(); break; case OperationMode.Quit: break; default: Console.WriteLine("Please enter a valid option"); break; } }
public override void SelectedOnGUI() { mode = OperationMode.Normal; if(AllowToolUtility.ControlIsHeld) mode = OperationMode.Constrained; if(AllowToolUtility.AltIsHeld) mode = OperationMode.AllOfDef; addToSelection = AllowToolUtility.ShiftIsHeld; if (mode == OperationMode.Constrained) { if (constraintsNeedReindexing) UpdateSelectionConstraints(); var label = "MassSelect_nowSelecting".Translate(cachedConstraintReadout); DrawMouseAttachedLabel(label); } else if (mode == OperationMode.AllOfDef) { if (Event.current.type == EventType.Repaint) { var target = TryGetItemOrPawnUnderCursor(); string label = target == null ? "MassSelect_needTarget".Translate() : "MassSelect_targetHover".Translate(target.def.label.CapitalizeFirst()); DrawMouseAttachedLabel(label); } } }
protected void readXml(string fileName) { StreamReader sr = new StreamReader(fileName); XmlDocument doc = new XmlDocument(); doc.LoadXml(sr.ReadToEnd()); sr.Close(); XmlNode node = null; foreach (XmlNode n in doc.ChildNodes) { if (n.Name == "instances") { _dataSetName = n.Attributes[0].Value; _dataSourceName = n.Attributes[1].Value; if (n.Attributes[2].Value == "text") _media = MediaType.Text; else if (n.Attributes[2].Value == "image") _media = MediaType.Image; else if (n.Attributes[2].Value == "video") _media = MediaType.Video; else if (n.Attributes[2].Value == "audio") _media = MediaType.Audio; if (n.Attributes[3].Value == "learn") _opMode = OperationMode.Learn; else if (n.Attributes[3].Value == "validate") _opMode = OperationMode.Validate; else if (n.Attributes[3].Value == "classify") _opMode = OperationMode.Classify; if (n.Attributes[4].Value == "batch") _procMode = ProcessMode.Batch; else if (n.Attributes[4].Value == "online") _procMode = ProcessMode.Batch; node = n; break; } } //parse the IOs foreach (XmlNode n in node.ChildNodes) { if (n.Name == "input") { _sc.InputConditioners.Add(new ScaleAndOffset( double.Parse(n.Attributes[1].Value), double.Parse(n.Attributes[2].Value))); } else if (n.Name == "output") { _sc.OutputConditioners.Add(new ScaleAndOffset( double.Parse(n.Attributes[1].Value), double.Parse(n.Attributes[2].Value))); } } }
/// <summary> /// Encrypts bytes with the specified key and IV. /// </summary> public static Byte[] Encrypt(Byte[] key, Byte[] bytes, OperationMode mode, Byte[] iv) { Check(key, bytes); RijndaelManaged aes = new RijndaelManaged(); if (iv != null) aes.IV = iv; aes.Mode = (CipherMode)mode; aes.Padding = PaddingMode.None; if (key.Length == 24) aes.KeySize = 192; else if (key.Length == 32) aes.KeySize = 256; else aes.KeySize = 128; // Defaults to 128 aes.BlockSize = 128; aes.Key = key; ICryptoTransform ict = aes.CreateEncryptor(); MemoryStream mStream = new MemoryStream(); CryptoStream cStream = new CryptoStream(mStream, ict, CryptoStreamMode.Write); cStream.Write(bytes, 0, bytes.Length); cStream.FlushFinalBlock(); mStream.Close(); cStream.Close(); return mStream.ToArray(); }
public void Configure(IWatchDirectory watchDir) { _watchPath = watchDir.Path; _includeSubDirectories = watchDir.IncludeSubDirectories; _mode = watchDir.Mode; var strategy = watchDir.SortStrategy; if (string.IsNullOrEmpty(strategy)) { _sortStrategy = _entityLocator.ProvideDefaultSortStrategy(); } else { strategy = strategy.ToLower(); _sortStrategy = _entityLocator.ProvideSortStrategy(strategy); } foreach (string ext in watchDir.FileExtensions.Split(',')) { _acceptableExtensions.Add(string.Format(".{0}", ext)); } }
/// <summary> /// Start new fare scan and return the monitor responsible for the new requests /// </summary> /// <param name="mode"> /// The mode. /// </param> /// <returns> /// The <see cref="FareRequestMonitor"/>. /// </returns> internal FareRequestMonitor Monitor(OperationMode mode) { FareRequestMonitor newMon = null; try { // Validate the location of the journey if (this.View.Departure.Equals(this.View.Destination)) { this.View.Show( "Departure location and destination cannot be the same:" + Environment.NewLine + this.View.Departure, "Invalid Route", MessageBoxIcon.Exclamation); return null; } // Get list of new requests for the monitor var newRequests = this.GetRequests(); if (newRequests.Count > 0) { newMon = this.CreateMonitor(newRequests, mode); if (mode != OperationMode.LiveMonitor) { this._monitors.Clear(newMon.GetType()); } AppContext.Logger.InfoFormat("{0}: Starting monitor for {1} new requests", this.GetType().Name, newRequests.Count); this._monitors.Start(newMon); } else { string period = this.View.MinDuration == this.View.MaxDuration ? this.View.MinDuration.ToString(CultureInfo.InvariantCulture) : this.View.MinDuration.ToString(CultureInfo.InvariantCulture) + " and " + this.View.MaxDuration.ToString(CultureInfo.InvariantCulture); string message = string.Format( @"There is no travel date which satisfies the filter condition for the stay duration between {0} days (You selected travel period {1})! Double-check the filter conditions and make sure that not all travel dates are in the past", period, StringUtil.GetPeriodString(this.View.DepartureDate, this.View.ReturnDate)); AppContext.Logger.Debug(message); AppContext.ProgressCallback.Inform(null, message, "Invalid parameters", NotificationType.Exclamation); } } catch (Exception ex) { AppContext.ProgressCallback.Inform(this.View, "Failed to start monitors: " + ex.Message, "Check Fares", NotificationType.Error); AppContext.Logger.Error("Failed to start monitors: " + ex); } finally { this.View.SetScanner(true); } return newMon; }
/// <summary> /// Generates the CryptoTransform element used to encrypt/decrypt the bulk data /// </summary> /// <param name="mode">The operation mode</param> /// <returns>An ICryptoTransform instance</returns> public ICryptoTransform CreateCryptoStream(OperationMode mode) { if (mode == OperationMode.Encrypt) return m_crypt.CreateEncryptor(m_aesKey2, m_iv2); else return m_crypt.CreateDecryptor(m_aesKey2, m_iv2); }
/// <summary> /// Constructs a new AESCrypt instance, operating on the supplied stream /// </summary> /// <param name="password">The password used for encryption or decryption</param> /// <param name="stream">The stream to operate on, must be writeable for encryption, and readable for decryption</param> /// <param name="mode">The mode of operation, either OperationMode.Encrypt or OperationMode.Decrypt</param> public SharpAESCrypt(string password, Stream stream, OperationMode mode) { //Basic input checks if (stream == null) throw new ArgumentNullException("stream"); if (password == null) throw new ArgumentNullException("password"); if (mode != OperationMode.Encrypt && mode != OperationMode.Decrypt) throw new ArgumentException(Strings.InvalidOperationMode, "mode"); if (mode == OperationMode.Encrypt && !stream.CanWrite) throw new ArgumentException(Strings.StreamMustBeWriteAble, "stream"); if (mode == OperationMode.Decrypt && !stream.CanRead) throw new ArgumentException(Strings.StreamMustBeReadAble, "stream"); m_mode = mode; m_stream = stream; m_extensions = new List<KeyValuePair<string, byte[]>>(); if (mode == OperationMode.Encrypt) { this.Version = DefaultFileVersion; m_helper = new SetupHelper(mode, password, null); //Setup default extensions if (Extension_InsertCreateByIdentifier) m_extensions.Add(new KeyValuePair<string, byte[]>("CREATED-BY", System.Text.Encoding.UTF8.GetBytes(Extension_CreatedByIdentifier))); if (Extension_InsertTimeStamp) { m_extensions.Add(new KeyValuePair<string, byte[]>("CREATED-DATE", System.Text.Encoding.UTF8.GetBytes(DateTime.Now.ToString("yyyy-MM-dd")))); m_extensions.Add(new KeyValuePair<string, byte[]>("CREATED-TIME", System.Text.Encoding.UTF8.GetBytes(DateTime.Now.ToUniversalTime().ToString("hh-mm-ss")))); } if (Extension_InsertPlaceholder) m_extensions.Add(new KeyValuePair<string, byte[]>("", new byte[127])); //Suggested extension space //We defer creation of the cryptostream until it is needed, // so the caller can change version, extensions, etc. // before we write the header m_crypto = null; } else { //Read and validate ReadEncryptionHeader(password); m_hmac = m_helper.GetHMAC(); //Insert the HMAC before the decryption so the HMAC is calculated for the ciphertext m_crypto = new CryptoStream(new CryptoStream(new StreamHider(m_stream, m_version == 0 ? HASH_SIZE : (HASH_SIZE + 1)), m_hmac, CryptoStreamMode.Read), m_helper.CreateCryptoStream(m_mode), CryptoStreamMode.Read); } }
/// <summary> /// Gets the transportation reports. /// </summary> /// <param name="mode">The mode.</param> /// <param name="fromDate">From date.</param> /// <param name="toDate">To date.</param> /// <returns></returns> public List<TransporationReport> GetTransportationReports(OperationMode mode, DateTime? fromDate, DateTime? toDate) { int ledgerId = (mode == OperationMode.Dispatch) ? Ledger.Constants.GOODS_DISPATCHED : Ledger.Constants.GOODS_ON_HAND_UNCOMMITED; var list = _unitOfWork.TransactionRepository.Get(item => (item.LedgerID == ledgerId && (item.QuantityInMT > 0 || item.QuantityInUnit > 0)) && (item.TransactionGroup.DispatchDetails.Any() || item.TransactionGroup.ReceiveDetails.Any()) && (!item.TransactionGroup.InternalMovements.Any() || !item.TransactionGroup.Adjustments.Any()) ); if (fromDate.HasValue) { list = list.Where(p => p.TransactionDate >= fromDate.Value); } if (toDate.HasValue) { list = list.Where(p => p.TransactionDate <= toDate.Value); } return (from t in list group t by new { t.Commodity, t.Program } into tgroup select new TransporationReport() { Commodity = tgroup.Key.Commodity.Name, Program = tgroup.Key.Program.Name, NoOfTrucks = tgroup.Count(), QuantityInMT = tgroup.Sum(p => p.QuantityInMT), QuantityInUnit = tgroup.Sum(p => p.QuantityInUnit) }).ToList(); }
// ReSharper disable once UnusedMember.Local private static int Main(string mainCommand, string sourcePath = ".\\", OperationMode operationMode = OperationMode.install, string fileMask = "*.dll", string winVersion = "v10.0A", string netVersion = "4.7.1", string frameworkVersion = "v4.0.30319", string templateAppConfig = "", string logFolder = "GACNat.log", bool useX64Tooling = true) { try { string[] sourceFiles; IEnumerable <string> sourceAssemblies; List <string> failedFilesList = null; List <string> exceptionsLogList; var exceptionsLog = Path.Combine(sourcePath, logFolder, "Exceptions.log"); int fileCount; switch (mainCommand) { case "retry": if (!File.Exists(exceptionsLog)) { return(0); } operationMode = OperationMode.install; sourceFiles = File.ReadLines(exceptionsLog).ToArray(); exceptionsLogList = new List <string>(); fileCount = sourceFiles.Length; sourceAssemblies = sourceFiles; mainCommand = "gn"; break; case "g": case "gn": case "n": sourceFiles = Directory.EnumerateFiles(sourcePath, fileMask).ToArray(); exceptionsLogList = File.Exists(exceptionsLog) ? File.ReadLines(exceptionsLog).ToList() : new List <string>(); fileCount = sourceFiles.Length; sourceAssemblies = sourceFiles; break; default: DisplayHelp(); throw new Abort(); } switch (operationMode) { case OperationMode.install: { if (mainCommand.Contains("g")) { failedFilesList = new GACProcessor(exceptionsLogList, logFolder, useX64Tooling).GACInstall(sourceAssemblies, winVersion, netVersion); exceptionsLogList = failedFilesList; } if (mainCommand.Contains("n")) { failedFilesList = new NGENProcessor(exceptionsLogList, logFolder, useX64Tooling).NGENInstall(sourceAssemblies, frameworkVersion, templateAppConfig); } break; } case OperationMode.uninstall: { if (mainCommand.Contains("n")) { new NGENProcessor(exceptionsLogList, logFolder, useX64Tooling).NGENUninstall(sourceAssemblies, frameworkVersion); } if (mainCommand.Contains("g")) { new GACProcessor(exceptionsLogList, logFolder, useX64Tooling).GACUninstall(sourceAssemblies, winVersion, netVersion); } break; } case OperationMode.reinstall: { if (mainCommand.Contains("g")) { new GACProcessor(exceptionsLogList, logFolder, useX64Tooling).GACUninstall(sourceAssemblies, winVersion, netVersion); failedFilesList = new GACProcessor(exceptionsLogList, logFolder, useX64Tooling).GACInstall(sourceAssemblies, winVersion, netVersion); exceptionsLogList = failedFilesList; } if (mainCommand.Contains("n")) { new GACProcessor(exceptionsLogList, logFolder, useX64Tooling).GACUninstall(sourceAssemblies, winVersion, netVersion); failedFilesList = new NGENProcessor(exceptionsLogList, logFolder, useX64Tooling).NGENInstall(sourceAssemblies, frameworkVersion, templateAppConfig); } break; } default: throw new ArgumentOutOfRangeException(); } Directory.CreateDirectory(Path.Combine(sourcePath, logFolder + "\\")); if (failedFilesList != null) { if (failedFilesList.Count > 0) { File.WriteAllLines(exceptionsLog, failedFilesList); } else { File.Delete(exceptionsLog); } } CmdProcessorBase.Wl($"Completed gacnat process for {fileCount} input assemblies"); } catch (Exception e) { if (!(e is Abort)) { Console.WriteLine(e.Message); } // Console.ReadLine(); return(-1); } // Console.ReadLine(); return(0); }
private static string operationModeToString(OperationMode mode) { if(mode == Ice.OperationMode.Normal) { return "::Ice::Normal"; } if(mode == Ice.OperationMode.Nonmutating) { return "::Ice::Nonmutating"; } if(mode == Ice.OperationMode.Idempotent) { return "::Ice::Idempotent"; } return "???"; }
public frmCopyCIReference(UserInformation userInformation, Window mdiChild, DDCI_INFO activeentity, OperationMode operationMode) { InitializeComponent(); bll = new FeasibleReportAndCostSheet(userInformation); this.ActiveEntity = activeentity; Vm = new CopyCIReferenceViewModel(userInformation, activeentity, operationMode); this.DataContext = Vm; if (Vm.CloseAction == null && mdiChild.IsNotNullOrEmpty()) { Vm.CloseAction = new Action(() => mdiChild.Close()); } bll = new FeasibleReportAndCostSheet(userInformation); List <ProcessDesigner.Model.V_TABLE_DESCRIPTION> lstTableDescription = bll.GetTableColumnsSize("DDCI_INFO"); this.SetColumnLength <TextBox>(lstTableDescription); }
private void SetOperationMode(OperationMode operation) { WriteReg(Registers.OPR_MODE, (byte)operation); // It is necessary to wait 30 milliseconds Thread.Sleep(30); }
public override bool GetLock(IEnumerable <string> assets, OperationMode mode) { assets = assets.ToArray(); return(base.GetLock(assets, mode) && base.GetLock(GetMeta(assets), mode)); }
public override bool Delete(IEnumerable <string> assets, OperationMode mode) { return(base.Delete(AddMeta(assets), mode)); }
public MsgPumpData(PumpStatus statusPump, OperationMode operationMode) { this.StatusPump = statusPump; this.OperationMode = operationMode; }
public static string FailedOperationMessage(OperationMode operationname, string errormessage) { return(LC.L(@"The operation {0} has failed with error: {1}", operationname, errormessage)); }
public static bool GetLock(string assetpath, OperationMode operationMode = OperationMode.Normal) { var status = VCCommands.Instance.GetAssetStatus(assetpath); if (operationMode == OperationMode.Normal || EditorUtility.DisplayDialog("Force " + Terminology.getlock, "Are you sure you will steal the file from: [" + status.owner + "]", "Yes", "Cancel")) { return VCCommands.Instance.GetLock(new[] { assetpath }, operationMode); } return false; }
private static List<CommonResource> GetCommonResources(Vessel vessel, Part part, OperationMode opMode, ModuleMaintenanceTransferEnabler module = null) { var resList = new List<CommonResource>(); switch (opMode) { case OperationMode.Kerbal: { resList = (from resource in part.Resources.OfType<PartResource>() let kerbalResList = GetAllPartResourcesOfVessel(vessel).Where(kerbalResource => kerbalResource.resourceName == resource.resourceName).ToList() where kerbalResList.Count > 0 select new CommonResource(resource, kerbalResList)).ToList(); } break; case OperationMode.Maintenance: { if (module != null) { if (module.ConnectedPartsOnly) { var parts = new HashSet<Part> {module.part}; if (module.part.parent != null) { parts.Add(module.part.parent); } foreach (var child in module.part.children) { parts.Add(child); } foreach (var attachNode in module.part.attachNodes.Where(an => an.attachedPart != null)) { parts.Add(attachNode.attachedPart); } resList = (from resource in part.Resources.OfType<PartResource>() let localResList = GetAllPartResourcesOfParts(parts).Where(r => r.resourceName == resource.resourceName).ToList() where localResList.Count > 0 select new CommonResource(resource, localResList)).ToList(); } else { resList = (from resource in part.Resources.OfType<PartResource>() let localResList = GetAllPartResourcesOfVessel(vessel).Where(r => r.resourceName == resource.resourceName).ToList() where localResList.Count > 0 select new CommonResource(resource, localResList)).ToList(); } } } break; } return resList; }
private void dlgEditData_Load(object sender, EventArgs e) { try { //connect to database using (SqlConnection conn = new SqlConnection(frmMain.connectionString)) { conn.Open(); /* * //get primary keys and foreign keys * List<String> primaryKeys, foreignKeys; * * //get primary key and foreign keys * primaryKeys = new List<string>(); * foreignKeys = new List<string>(); * * //obtain primary keys and foreign keys of relation * using (SqlCommand command = new SqlCommand(String.Format("select CONSTRAINT_TYPE, COLUMN_NAME from INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc join INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE cc on tc.CONSTRAINT_NAME = cc.CONSTRAINT_NAME and tc.TABLE_NAME = cc.TABLE_NAME where (CONSTRAINT_TYPE = 'PRIMARY KEY' or CONSTRAINT_TYPE = 'FOREIGN KEY') and cc.TABLE_NAME = {0}", relName), conn)) * { * using (SqlDataReader reader = command.ExecuteReader()) * { * //populate the primary keys and foreign keys * while(reader.Read()) * { * if(reader.GetString(0) == "PRIMARY KEY") * { * primaryKeys.Add(reader.GetString(1)); * } else * { * foreignKeys.Add(reader.GetString(1)); * } * } * } * } */ //we already know the keys in each relation so we can directly specify it #region "UI Processing" //check operation mode if (key1 == null) { //if key1 is null, then it is data insertion mode opMode = OperationMode.Insert; this.Text = "Insert into " + this.Text; //check relation name, it determines number of key fields to be active if (relationName == "Student") { //hide the key2 and key3 field lblKey2.Visible = lblKey3.Visible = cboKey2.Visible = cboKey2.Enabled = cboKey3.Visible = cboKey3.Enabled = false; //also the Student relation has 3 non-primary key fields so hide the last 2 fields lblField4.Visible = lblField5.Visible = txtField4.Visible = txtField5.Visible = false; //the first key is the new key, disable the dropdown button cboKey1.DropDownStyle = ComboBoxStyle.Simple; //set the attribute labels lblKey1.Text = "NIM :"; lblField1.Text = "Name :"; lblField2.Text = "Program :"; lblField3.Text = "Enroll Year :"; } //TODO: Implement for other relations!!! else if (relationName == "SemesterData") { //only 2 keys required lblKey3.Visible = cboKey3.Visible = cboKey3.Enabled = false; //used to insert new semester cboKey2.DropDownStyle = ComboBoxStyle.Simple; //only 1 field required lblField2.Visible = lblField3.Visible = lblField4.Visible = lblField5.Visible = false; txtField2.Visible = txtField3.Visible = txtField4.Visible = txtField5.Visible = false; txtField2.Enabled = txtField3.Enabled = txtField4.Enabled = txtField5.Enabled = false; //get available Students using (SqlCommand cmdGetStudent = new SqlCommand("SELECT NIM, Name FROM Student ORDER BY NIM ASC", conn)) { using (SqlDataReader reader = cmdGetStudent.ExecuteReader()) { if (reader.Read()) { cboKey1.Items.Add(reader["NIM"] + " - " + reader["Name"]); while (reader.Read()) { cboKey1.Items.Add(reader["NIM"] + " - " + reader["Name"]); } } else { MessageBox.Show("No Students available", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } } } //make it drop down only and set first item as default //cboKey1.DropDownStyle = ComboBoxStyle.DropDownList; cboKey1.SelectedIndex = 0; //set the labels lblKey1.Text = "NIM :"; lblKey2.Text = "Semester :"; lblField1.Text = "Semester Year :"; } else if (relationName == "Courses") { //all fields used, change all combo box to Text Box mode cboKey1.DropDownStyle = cboKey2.DropDownStyle = cboKey3.DropDownStyle = ComboBoxStyle.Simple; //set the labels lblKey1.Text = "Course Code :"; lblKey2.Text = "Course Name :"; lblKey3.Text = "Theory Credit :"; lblField1.Text = "Practicum Credit :"; lblField2.Text = "TM Weight :"; lblField3.Text = "UTS Weight :"; lblField4.Text = "Practicum Weight :"; lblField5.Text = "UAS Weight :"; } else if (relationName == "Scores") { //set the labels lblKey1.Text = "NIM :"; lblKey2.Text = "Semester :"; lblKey3.Text = "Course Code :"; lblField1.Text = "Class :"; lblField2.Text = "TM :"; lblField3.Text = "UTS :"; lblField4.Text = "UAS :"; lblField5.Text = "UAP :"; //key 2 and key 3 field will be disabled by default until the a student is selected //get available Students using (SqlCommand cmdGetStudent = new SqlCommand("SELECT NIM, Name FROM Student ORDER BY NIM ASC", conn)) { using (SqlDataReader reader = cmdGetStudent.ExecuteReader()) { if (reader.Read()) { cboKey1.Items.Add(reader["NIM"] + " - " + reader["Name"]); while (reader.Read()) { cboKey1.Items.Add(reader["NIM"] + " - " + reader["Name"]); } } else { MessageBox.Show("No Students available", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning); this.Close(); } } } //disable combo box 2 because combo box 1 currently selected to nothing cboKey2.Enabled = false; //read available courses using (SqlCommand command = new SqlCommand("SELECT CourseCode, CourseName FROM Courses", conn)) { SqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { cboKey3.Items.Add(reader.GetString(0) + " - " + reader.GetString(1)); while (reader.Read()) { cboKey3.Items.Add(reader.GetString(0) + " - " + reader.GetString(1)); } } else { //no courses available, cancel insertion MessageBox.Show("No courses available!", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning); this.Close(); } } } } //TODO: Implement for other relations!!!! #endregion } } catch (SqlException sqlEx) { if (sqlEx.Number == -1) { CommonFunctions.InvokeErrorMsg("Failed establishing connection to database. Check if you are granted permission to database or SQL Server Service is running", Application.ProductName); this.Close(); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Arsip Nilai", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private void LoadFrom(SimpleConfig config) { try { configfilepath = config.config_loc; try { string x = config.appSettings[IgnoreListKey]; if (!String.IsNullOrEmpty(x)) ignoreList.AddRange(x.Trim().Split('|')); } catch { } try { _logLevel = (LogLevel)Enum.Parse(typeof(LogLevel), config.appSettings[LogLevelKey]); } catch { _logLevel = LogLevel.WARN; } try { string x = config.appSettings[AuthModePasswordKey]; if (!String.IsNullOrEmpty(x)) password = x; } catch { } try { string x = config.appSettings[AuthModeUsernameKey]; if (!String.IsNullOrEmpty(x)) username = x; } catch { } try { string x = config.appSettings[AuthModePKIInfoKey]; if (!String.IsNullOrEmpty(x)) pkiinfo = x; } catch { } try { string x = config.appSettings[DCSUrlKey]; if (!String.IsNullOrEmpty(x)) dcsurl.AddRange(x.Trim().Split('|')); } catch { } try { string x = config.appSettings[SSUrlKey]; if (!String.IsNullOrEmpty(x)) ssurl.AddRange(x.Trim().Split('|')); } catch { } try { string x = config.appSettings[PCSUrlKey]; if (!String.IsNullOrEmpty(x)) pcsurl.AddRange(x.Trim().Split('|')); } catch { } try { DCSalgo = (Algorithm)Enum.Parse(typeof(Algorithm), config.appSettings[UddiFindTypekey]); } catch { } try { DCSalgo = (Algorithm)Enum.Parse(typeof(Algorithm), config.appSettings[DCSlagokey]); } catch { } try { PCSalgo = (Algorithm)Enum.Parse(typeof(Algorithm), config.appSettings[PCSlagokey]); } catch { } try { authMode = (AuthMode)Enum.Parse(typeof(AuthMode), config.appSettings[AuthModeKey]); } catch { } try { DeadMessageDuration = (long)long.Parse(config.appSettings[DeadMsgkey]); } catch { } try { DependencyInjectionEnabled = (bool)bool.Parse(config.appSettings[DepInjkey]); } catch { } try { UddiEnabled = (bool)bool.Parse(config.appSettings[UddiEnabledKey]); } catch { } try { DNSEnabled = (bool)bool.Parse(config.appSettings[DNSEnabledKey]); } catch { } try { ServiceUnavailableBehavior = (UnavailableBehavior)Enum.Parse(typeof(UnavailableBehavior), config.appSettings[AgentBevKey]); } catch { } try { DCSretrycount = Int32.Parse(config.appSettings[DCSlretrykey]); } catch { } try { PCSretrycount = Int32.Parse(config.appSettings[PCSlretrykey]); } catch { } try { DiscoveryInterval = Int32.Parse(config.appSettings[discoveryInterval]); } catch { } try { UddiInquiryUrl = (config.appSettings[UddiURLKey]); } catch { } try { UddiSecurityUrl = (config.appSettings[UddiSecUrlKey]); } catch { } try { UddiAuthRequired = bool.Parse(config.appSettings[UddiAuthKey]); } catch { } try { UddiUsername = (config.appSettings[UddiUsernameKey]); } catch { } try { UddiEncryptedPassword = (config.appSettings[UddipwdKey]); } catch { } try { UddiDCSLookup = (config.appSettings[UddiDCSkey]); } catch { } try { UddiPCSLookup = (config.appSettings[UddiPCSkey]); } catch { } try { _uddifindType = (UddiFindType)Enum.Parse(typeof(UddiFindType), (config.appSettings[UddiFindTypekey])); } catch { } try { operatingmode = (OperationMode)Enum.Parse(typeof(OperationMode), (config.appSettings[operatingModeKey])); } catch { } try { PersistLocation = (config.appSettings[PersistKey]); } catch { } } catch (Exception) { } }
public async Task SetOperationMode(OperationMode newMode) { WriteByte((byte)BNO055Register.BNO055_OPR_MODE_ADDR, (byte)newMode); await Task.Delay(30); }
public static string StartingOperationMessage(OperationMode operationname) { return LC.L(@"The operation {0} has started", operationname); }
public static string StartingOperationMessage(OperationMode operationname) { return(LC.L(@"The operation {0} has started", operationname)); }
/// <summary> /// Gets the grouped transportation reports. /// </summary> /// <param name="mode">The mode.</param> /// <param name="fromDate">From date.</param> /// <param name="toDate">To date.</param> /// <returns></returns> public List<GroupedTransportation> GetGroupedTransportationReports(OperationMode mode, DateTime? fromDate, DateTime? toDate) { var list = (from tr in GetTransportationReports(mode, fromDate, toDate) group tr by tr.Program into trg select new GroupedTransportation() { Program = trg.Key, Transportations = trg.ToList() }); return list.ToList(); ; }
public static string CompletedOperationMessage(OperationMode operationname) { return(LC.L(@"The operation {0} has completed", operationname)); }
public bool GetLock(IEnumerable <string> assets, OperationMode mode = OperationMode.Normal) { return(HandleExceptions(() => PerformOperation(OperationType.GetLock, assets, _assets => vcc.GetLock(_assets, mode)))); }
/// <summary> /// Draws the EditorWindow's GUI. /// </summary> public void OnGUI() { _scrollPos = GUILayout.BeginScrollView(_scrollPos); GUILayout.BeginVertical(); #region - Operation mode - GUILayout.Label("Operation mode"); GUIContent[] modes = new GUIContent[] { new GUIContent("Fly", "Where do you want to fly today?"), new GUIContent("Orbit", "Round, round, round we go"), new GUIContent("Telekinesis", "Watch where you're levitating that piano!"), new GUIContent("Grab Move", "Excuse me, yes. HDS coming through. I've got a package people") }; _operationMode = (OperationMode)GUILayout.SelectionGrid((int)_operationMode, modes, 4); #endregion - Operation mode - #region - Coordinate system - // Enable the coordsys only in Telekinesis mode. GUI.enabled = _operationMode == OperationMode.Telekinesis; GUILayout.Label("Coordinate system"); string[] coordSystems = new string[] { "Camera", "World", "Parent", "Local" }; _coordSys = (CoordinateSystem)GUILayout.SelectionGrid((int)_coordSys, coordSystems, 4); #endregion - Coordinate system - #region - Snapping - // Disable the constraint controls in Fly and Orbit mode. GUI.enabled = _operationMode != OperationMode.Fly && _operationMode != OperationMode.Orbit; GUILayout.Space(10); GUILayout.Label("Snap"); GUILayout.Space(4); GUILayout.BeginHorizontal(); _snapTranslation = GUILayout.Toggle(_snapTranslation, "Grid snap"); _snapDistance = EditorGUILayout.FloatField(_snapDistance); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); _snapRotation = GUILayout.Toggle(_snapRotation, "Angle snap"); _snapAngle = EditorGUILayout.IntField(_snapAngle); GUILayout.EndHorizontal(); // Re-enable gui. GUI.enabled = true; #endregion - Snapping - #region - Locking and sensitivity - GUILayout.Space(10); GUILayout.Label("Lock"); GUILayout.Space(4); EditorGUI.BeginChangeCheck(); _lockHorizon = GUILayout.Toggle(_lockHorizon, "Horizon"); if (EditorGUI.EndChangeCheck() && _lockHorizon) { StraightenHorizon(); } SpaceNavigator.Instance.OnGUI(); #endregion - Locking and sensitivity - #region - Axes inversion per mode - GUILayout.Space(10); GUILayout.Label("Invert axes in " + _operationMode.ToString() + " mode"); GUILayout.Space(4); bool tx, ty, tz, rx, ry, rz; switch (_operationMode) { case OperationMode.Fly: tx = _flyInvertTranslation.x < 0; ty = _flyInvertTranslation.y < 0; tz = _flyInvertTranslation.z < 0; rx = _flyInvertRotation.x < 0; ry = _flyInvertRotation.y < 0; rz = _flyInvertRotation.z < 0; break; case OperationMode.Orbit: tx = _orbitInvertTranslation.x < 0; ty = _orbitInvertTranslation.y < 0; tz = _orbitInvertTranslation.z < 0; rx = _orbitInvertRotation.x < 0; ry = _orbitInvertRotation.y < 0; rz = _orbitInvertRotation.z < 0; break; case OperationMode.Telekinesis: tx = _telekinesisInvertTranslation.x < 0; ty = _telekinesisInvertTranslation.y < 0; tz = _telekinesisInvertTranslation.z < 0; rx = _telekinesisInvertRotation.x < 0; ry = _telekinesisInvertRotation.y < 0; rz = _telekinesisInvertRotation.z < 0; break; case OperationMode.GrabMove: tx = _grabMoveInvertTranslation.x < 0; ty = _grabMoveInvertTranslation.y < 0; tz = _grabMoveInvertTranslation.z < 0; rx = _grabMoveInvertRotation.x < 0; ry = _grabMoveInvertRotation.y < 0; rz = _grabMoveInvertRotation.z < 0; break; default: throw new ArgumentOutOfRangeException(); } GUILayout.BeginHorizontal(); GUILayout.Label("Translation", GUILayout.Width(100)); EditorGUI.BeginChangeCheck(); tx = GUILayout.Toggle(tx, "X"); ty = GUILayout.Toggle(ty, "Y"); tz = GUILayout.Toggle(tz, "Z"); if (EditorGUI.EndChangeCheck()) { switch (_operationMode) { case OperationMode.Fly: _flyInvertTranslation = new Vector3(tx ? -1 : 1, ty ? -1 : 1, tz ? -1 : 1); break; case OperationMode.Orbit: _orbitInvertTranslation = new Vector3(tx ? -1 : 1, ty ? -1 : 1, tz ? -1 : 1); break; case OperationMode.Telekinesis: _telekinesisInvertTranslation = new Vector3(tx ? -1 : 1, ty ? -1 : 1, tz ? -1 : 1); break; case OperationMode.GrabMove: _grabMoveInvertTranslation = new Vector3(tx ? -1 : 1, ty ? -1 : 1, tz ? -1 : 1); break; default: throw new ArgumentOutOfRangeException(); } } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label("Rotation", GUILayout.Width(100)); EditorGUI.BeginChangeCheck(); rx = GUILayout.Toggle(rx, "X"); ry = GUILayout.Toggle(ry, "Y"); rz = GUILayout.Toggle(rz, "Z"); if (EditorGUI.EndChangeCheck()) { switch (_operationMode) { case OperationMode.Fly: _flyInvertRotation = new Vector3(rx ? -1 : 1, ry ? -1 : 1, rz ? -1 : 1); break; case OperationMode.Orbit: _orbitInvertRotation = new Vector3(rx ? -1 : 1, ry ? -1 : 1, rz ? -1 : 1); break; case OperationMode.Telekinesis: _telekinesisInvertRotation = new Vector3(rx ? -1 : 1, ry ? -1 : 1, rz ? -1 : 1); break; case OperationMode.GrabMove: _grabMoveInvertRotation = new Vector3(rx ? -1 : 1, ry ? -1 : 1, rz ? -1 : 1); break; default: throw new ArgumentOutOfRangeException(); } } GUILayout.EndHorizontal(); #endregion - Axes inversion per mode - GUILayout.EndVertical(); GUILayout.EndScrollView(); }
/// <summary> /// Initialize the setup /// </summary> /// <param name="mode">The mode to prepare for</param> /// <param name="password">The password used to encrypt or decrypt</param> /// <param name="iv">The IV used, set to null if encrypting</param> public SetupHelper(OperationMode mode, string password, byte[] iv) { m_crypt = SymmetricAlgorithm.Create(CRYPT_ALGORITHM); //Not sure how to insert this with the CRYPT_ALGORITHM string m_crypt.Padding = PaddingMode.None; m_crypt.Mode = CipherMode.CBC; m_hash = HashAlgorithm.Create(HASH_ALGORITHM); m_rand = RandomNumberGenerator.Create(/*RAND_ALGORITHM*/); m_hmac = HMAC.Create(HMAC_ALGORITHM); if (mode == OperationMode.Encrypt) { m_iv1 = GenerateIv1(); m_aesKey1 = GenerateAESKey1(EncodePassword(password)); m_iv2 = GenerateIv2(); m_aesKey2 = GenerateAESKey2(); } else { m_iv1 = iv; m_aesKey1 = GenerateAESKey1(EncodePassword(password)); } }
/// <summary> /// Generates the notifications for media. /// </summary> /// <param name="media">The media.</param> /// <param name="userID">The user ID.</param> /// <param name="projectId">The project id.</param> /// <param name="operationMode">The operation mode.</param> /// <param name="newName">The new name.</param> /// <param name="newURL">The new URL.</param> public void GenerateNotificationsForMedia(DocumentMedia media, int userID, int projectId, OperationMode operationMode, string newName = "", string newURL = "") { string hyperlinkExtension = "Hyperlink"; PersonalBL personalBL = new PersonalBL(DataContext); User user = personalBL.GetUser(userID); string userName = string.Concat(user.FirstName + " " + user.LastName).Trim(); StageBitz.Data.Notification nf = new StageBitz.Data.Notification(); nf.CreatedByUserId = nf.LastUpdatedByUserId = userID; nf.CreatedDate = nf.LastUpdatedDate = Utils.Now; nf.RelatedId = media.RelatedId; nf.ProjectId = projectId; string message = string.Empty; string fileName = string.Empty; if (media.FileExtension.ToUpper() != hyperlinkExtension.ToUpper()) { if (operationMode == OperationMode.Edit) { fileName = string.Format("file '{0}'", string.Concat(newName, ".", media.FileExtension != null ? media.FileExtension : string.Empty)); } else { fileName = string.Format("file '{0}'", string.Concat(media.Name, ".", media.FileExtension != null ? media.FileExtension : string.Empty)); } } else { if (operationMode == OperationMode.Edit) { fileName = this.GetContentForEditHyperlink(media, newName, newURL); } else { fileName = string.Format("Hyperlink '{0}'", (media.Name != null && media.Name != string.Empty) ? media.Name : media.Description); } } switch (operationMode) { case OperationMode.Add: message = "{0} added the {1}."; nf.OperationTypeCodeId = Utils.GetCodeIdByCodeValue("OperationType", "ADD"); break; case OperationMode.Edit: message = "{0} edited the {1}."; nf.OperationTypeCodeId = Utils.GetCodeIdByCodeValue("OperationType", "EDIT"); break; case OperationMode.Delete: message = "{0} deleted the {1}."; nf.OperationTypeCodeId = Utils.GetCodeIdByCodeValue("OperationType", "DELETE"); break; } // Set module type/ops type based on the related table. switch (media.RelatedTableName) { case "Project": nf.ModuleTypeCodeId = Utils.GetCodeIdByCodeValue("ModuleType", "PROJECT"); break; case "ItemBrief": nf.ModuleTypeCodeId = Utils.GetCodeIdByCodeValue("ModuleType", "ITEMBRIEFMEDIA"); break; } nf.Message = string.Format(message, userName, fileName); this.AddNotification(nf); }
private void OnEnableModeChanged(OperationMode oldValue, OperationMode newValue, LimitTimer timer) { switch(newValue) { case OperationMode.Disabled: timer.Enabled = false; break; case OperationMode.Continuous: case OperationMode.ContinuousReload: timer.Mode = WorkMode.Periodic; timer.Enabled = true; timer.EventEnabled = true; break; case OperationMode.Once: timer.Mode = WorkMode.OneShot; timer.Enabled = true; timer.EventEnabled = true; break; } }
/// <summary> Sets the operation mode of the BNO055. Only use if you know what you're doing! </summary> /// <param name="Mode"> The target mode that the BNO-55 will be set to. </param> public void SetMode(OperationMode Mode) { this.Mode = Mode; Write8((byte)Register.BNO055_OPR_MODE_ADDR, (byte)(((byte)Mode) & 0xFF)); Thread.Sleep(30); }
/// <summary> /// Create new monitor for requests depending on the operation mode /// </summary> /// <param name="requests"> /// The requests. /// </param> /// <param name="operationMode"> /// The operation Mode. /// </param> /// <returns> /// The <see cref="FareRequestMonitor"/>. /// </returns> internal FareRequestMonitor CreateMonitor(List<FareMonitorRequest> requests, OperationMode operationMode) { if (requests == null || requests.Count < 1) { return null; } FareRequestMonitor newMon = null; FareMonitorEvents monitorEvents = null; if (operationMode == OperationMode.LiveMonitor) { newMon = new LiveFareMonitor(this._liveFareStorage, new TaskbarFlightNotifier(), WebFareBrowserControlFactory.Instance); monitorEvents = this.Events[OperationMode.LiveMonitor]; } else { if (operationMode == OperationMode.ShowFare) { newMon = new FareRequestMonitor(WebFareBrowserControlFactory.Instance); monitorEvents = this.Events[OperationMode.ShowFare]; } else if (operationMode == OperationMode.GetFareAndSave) { newMon = new FareExportMonitor( AppContext.MonitorEnvironment.ArchiveManager, WebFareBrowserControlFactory.Instance, this.View.AutoSync); monitorEvents = this.Events[OperationMode.GetFareAndSave]; } else { throw new ApplicationException("Unsupported opearation mode: " + operationMode); } } monitorEvents.Attach(newMon); newMon.Enqueue(requests); return newMon; }
public bool Delete(IEnumerable <string> assets, OperationMode mode) { return(CreateAssetOperation("delete" + (mode == OperationMode.Force ? " --force" : ""), assets)); }
public static bool GetLock(Object obj, OperationMode operationMode = OperationMode.Normal) { bool shouldGetLock = true; if (onHierarchyAllowGetLock != null) shouldGetLock = onHierarchyAllowGetLock(obj); if (shouldGetLock) { bool success = GetLock(obj.GetAssetPath(), operationMode); if (success && onHierarchyGetLock != null) onHierarchyGetLock(obj); return success; } return false; }
public virtual bool ice_invoke(string operation, OperationMode mode, byte[] inParams, out byte[] outParams, Dictionary<string, string> context) { throw new CollocationOptimizationException(); }
private static PartResource GetOrderedPartResource(IEnumerable<PartResource> localResources, Vessel activeVessel, bool rootFirst, bool transferOut, OperationMode opMode, ModuleMaintenanceTransferEnabler module) { const double treshold = 0.001d; var rootPart = (opMode == OperationMode.Kerbal) ? activeVessel.rootPart : module.part; if (transferOut) { var allWithAmount = localResources.Where(r => r.amount > treshold).ToList(); if (allWithAmount.Count > 1) { if (rootFirst) { foreach (var partResource in allWithAmount) { if (partResource.part == rootPart) { return partResource; } } } else { foreach (var partResource in allWithAmount) { if (partResource.part != rootPart) { return partResource; } } } } return allWithAmount.Count >= 1 ? allWithAmount[0] : null; } var allWithSpace = localResources.Where(r => (r.maxAmount - r.amount) > treshold).ToList(); if (allWithSpace.Count > 1) { if (rootFirst) { foreach (var partResource in allWithSpace) { if (partResource.part == rootPart) { return partResource; } } } else { foreach (var partResource in allWithSpace) { if (partResource.part != rootPart) { return partResource; } } } } return allWithSpace.Count >= 1 ? allWithSpace[0] : null; }
public bool GetLock(IEnumerable<string> assets, OperationMode mode) { dataCarrier.assets = assets.ToList(); return true; }
protected static void checkMode__(OperationMode expected, OperationMode received) { if(expected != received) { if(expected == OperationMode.Idempotent && received == OperationMode.Nonmutating) { // // Fine: typically an old client still using the // deprecated nonmutating keyword // } else { Ice.MarshalException ex = new Ice.MarshalException(); ex.reason = "unexpected operation mode. expected = " + operationModeToString(expected) + " received = " + operationModeToString(received); throw ex; } } }
void GoTo(OperationMode mode) { MethodInvoker action = new MethodInvoker(delegate() { CurrentOperationMode = mode; switch (mode) { case OperationMode.Portal: ArenaServerListView.Items.Clear(); RoomListView.Items.Clear(); LocationTabControl.SelectedTab = PortalTabPage; EnableRoomEditFormItems(false); break; case OperationMode.ArenaLobby: ArenaServerListView.Items.Clear(); RoomListView.Items.Clear(); LocationTabControl.SelectedTab = ArenaTabPage; RoomCreateEditButton.Text = "部屋を作成"; RoomCreateEditButton.Enabled = true; RoomCloseExitButton.Text = "部屋を閉じる"; RoomCloseExitButton.Enabled = false; RoomMasterNameTextBox.Text = LoginUserName; EnableRoomEditFormItems(true); break; case OperationMode.PlayRoomMaster: LocationTabControl.SelectedTab = PlayRoomTabPage; RoomCreateEditButton.Text = "部屋を修正"; RoomCreateEditButton.Enabled = true; RoomCloseExitButton.Text = "部屋を閉じる"; RoomCloseExitButton.Enabled = true; RoomMasterNameTextBox.Text = LoginUserName; EnableRoomEditFormItems(true); break; case OperationMode.PlayRoomParticipant: LocationTabControl.SelectedTab = PlayRoomTabPage; RoomCreateEditButton.Enabled = false; RoomCloseExitButton.Text = "退室する"; RoomCloseExitButton.Enabled = true; EnableRoomEditFormItems(false); break; case OperationMode.Offline: ArenaServerListView.Items.Clear(); RoomListView.Items.Clear(); playersTreeView.Nodes.Clear(); RoomCreateEditButton.Enabled = false; RoomCloseExitButton.Enabled = false; EnableRoomEditFormItems(false); ServerLoginButton.Text = SERVER_LOGIN; ServerLoginButton.Enabled = true; ServerAddressComboBox.Enabled = true; playersTreeView.Nodes.Clear(); ResetServerStatusBar(); LoginUserNameTextBox.Enabled = true; break; case OperationMode.ConnectingToServer: LoginUserNameTextBox.Enabled = false; MainTabControl.SelectedTab = chatTagPage; break; default: break; } }); if (InvokeRequired) Invoke(action); else action(); }
private void buttonOperation_Click(object sender, System.EventArgs e) { switch ( this.enOperationMode ) { case OperationMode.Or: this.enOperationMode = OperationMode.And; break; case OperationMode.And: this.enOperationMode = OperationMode.Xor; break; case OperationMode.Xor: this.enOperationMode = OperationMode.Or; break; default: break; } this.buttonOperation.Text = this.enOperationMode.ToString(); this.buttonRefresh_Click( sender, e ); }
public ShogiBoardViewModel(GameService gameService, IMessenger messenger, Func <GameSet> gameSetGetter) { Messenger = messenger; this.gameService = gameService; OperationMode = OperationMode.SelectMoveSource; this.gameService.Subscribe(this); StartCommand = new DelegateCommand( async() => { var gameSet = gameSetGetter(); FirstPlayerHands.Name = gameSet.Players[PlayerType.FirstPlayer].Name; SecondPlayerHands.Name = gameSet.Players[PlayerType.SecondPlayer].Name; OperationMode = OperationMode.AIThinking; cancelTokenSource = new CancellationTokenSource(); await Task.Run(() => { this.gameService.Start(gameSet, cancelTokenSource.Token); //this.gameService.Start(new NegaAlphaAI(9), new NegaAlphaAI(9), GameType.AnimalShogi, this); }); cancelTokenSource = null; // [MEMO:タスクが完了されるまでここは実行されない(AIThinkingのまま)] UpdateOperationModeOnTaskFinished(); }, () => { return(OperationMode != OperationMode.AIThinking); }); RestartCommand = new DelegateCommand( async() => { OperationMode = OperationMode.AIThinking; cancelTokenSource = new CancellationTokenSource(); await Task.Run(() => { this.gameService.Restart(cancelTokenSource.Token); }); cancelTokenSource = null; // [MEMO:タスクが完了されるまでここは実行されない(AIThinkingのまま)] UpdateOperationModeOnTaskFinished(); }, () => { return(OperationMode != OperationMode.AIThinking); }); MoveCommand = new DelegateCommand <object>( async(param) => { if (param == null) { return; } if (OperationMode == OperationMode.SelectMoveSource) { var selectedMoveSource = param as ISelectable; selectedMoveSource.IsSelected = true; OperationMode = OperationMode.SelectMoveDestination; UpdateCanMove(selectedMoveSource); } else if (OperationMode == OperationMode.SelectMoveDestination) { var cell = param as CellViewModel; if (cell != null && cell.CanMove) { MoveCommand move = null; if (cell.MoveCommands.Count() == 1) { move = cell.MoveCommands[0]; } else { var doTransform = Messenger.MessageYesNo("成りますか?"); move = cell.MoveCommands.FirstOrDefault(x => x.DoTransform == doTransform); } //game.Play(move); OperationMode = OperationMode.AIThinking; cancelTokenSource = new CancellationTokenSource(); await Task.Run(() => this.gameService.Play(move, cancelTokenSource.Token)); cancelTokenSource = null; // [MEMO:タスクが完了されるまでここは実行されない(AIThinkingのまま)] UpdateOperationModeOnTaskFinished(); } else { // [動けない位置の場合はキャンセルしすべて更新] OperationMode = OperationMode.SelectMoveSource; Update(); } } }, (param) => { if (param == null) { return(false); } if (OperationMode == OperationMode.SelectMoveSource) { var cell = param as CellViewModel; if (cell != null) { if (cell.Koma == null) { return(false); } return(this.gameService.GetGame().State.TurnPlayer == cell.Koma.Player.ToDomain()); } var hand = param as HandKomaViewModel; if (hand != null) { return(this.gameService.GetGame().State.TurnPlayer == hand.Player.ToDomain()); } } else if (OperationMode == OperationMode.SelectMoveDestination) { return(true); } // [OperationMode.GameEnd] // [OperationMode.AIThinking] // [OperationMode.Stopping] return(false); } ); StopCommand = new DelegateCommand( () => { cancelTokenSource?.Cancel(); // [MEMO:OperationModeを変更すると、この時点でタスクが裏で動いているのに、他の操作ができるようになってしまうが] // [ アプリケーションサービス層でロックしているので一応問題ない(タスクがキャンセルされるまで少し固まる可能性はあるが)] OperationMode = OperationMode.Stopping; }, () => { return(OperationMode == OperationMode.AIThinking || OperationMode == OperationMode.SelectMoveSource || OperationMode == OperationMode.GameEnd); }); ResumeCommand = new DelegateCommand( async() => { OperationMode = OperationMode.AIThinking; cancelTokenSource = new CancellationTokenSource(); await Task.Run(() => { this.gameService.Resume(cancelTokenSource.Token); }); cancelTokenSource = null; // [MEMO:タスクが完了されるまでここは実行されない(AIThinkingのまま)] UpdateOperationModeOnTaskFinished(); }, () => { return(OperationMode == OperationMode.Stopping); }); UndoCommand = new DelegateCommand( () => { this.gameService.Undo(Game.UndoType.Undo); Update(); UndoCommand?.RaiseCanExecuteChanged(); RedoCommand?.RaiseCanExecuteChanged(); }, () => { return(OperationMode == OperationMode.Stopping && this.gameService.GetGame().CanUndo(Game.UndoType.Undo)); }); RedoCommand = new DelegateCommand( () => { this.gameService.Undo(Game.UndoType.Redo); Update(); UndoCommand?.RaiseCanExecuteChanged(); RedoCommand?.RaiseCanExecuteChanged(); }, () => { return(OperationMode == OperationMode.Stopping && this.gameService.GetGame().CanUndo(Game.UndoType.Redo)); }); var ai = new NegaAlphaAI(6); var human = new Human(); FirstPlayerHands = new PlayerViewModel() { Player = Player.FirstPlayer, Name = human.Name }; SecondPlayerHands = new PlayerViewModel() { Player = Player.SecondPlayer, Name = ai.Name }; ForegroundPlayer = Player.FirstPlayer; // [MEMO:タスクで開始していない(コンストラクタなのできない)ので、必ず初手はHumanになるようにする] cancelTokenSource = new CancellationTokenSource(); this.gameService.Start(new GameSet(human, ai, GameType.AnimalShogi), cancelTokenSource.Token); cancelTokenSource = null; }