public void ShouldParseEnumFromString() { var converter = new EnumConverter(); var expected = FooEnum.All; var result = converter.ToEnum("All", FooEnum.None); Assert.Equal(expected, result); }
public void showInfo(string value) { Vehicleinfo vinfo = EnumConverter.VehicleinfoEnum(value); Dispatcher.Invoke((Action) delegate { if (vinfo == Vehicleinfo.None) { Dispatcher.Invoke(new Action(() => lbl_show_info.Content = ""), DispatcherPriority.Send); } if (vinfo == Vehicleinfo.SwitchDirection) { Dispatcher.Invoke(new Action(() => lbl_show_info.Content = CurrentLane.CurrentSwitchToDirection), DispatcherPriority.Send); } if (vinfo == Vehicleinfo.Direction) { Dispatcher.Invoke(new Action(() => lbl_show_info.Content = CurrentLane.LaneDirection), DispatcherPriority.Send); } if (vinfo == Vehicleinfo.VID) { txt_vid.Visibility = Visibility.Hidden; Dispatcher.Invoke(new Action(() => lbl_show_info.Content = VID), DispatcherPriority.Send); } else if (vinfo == Vehicleinfo.SpeedKMH) { Dispatcher.Invoke(new Action(() => lbl_show_info.Content = GetSpeedInKMH.ToString("0.00")), DispatcherPriority.Send); } else if (vinfo == Vehicleinfo.SpeedTimer) { Dispatcher.Invoke(new Action(() => lbl_show_info.Content = InstantaneousSpeed.ToString("0.00")), DispatcherPriority.Send); } else if (vinfo == Vehicleinfo.RID) { Dispatcher.Invoke(new Action(() => lbl_show_info.Content = CurrentLane.MyRoadSegment.RID), DispatcherPriority.Send); } else if (vinfo == Vehicleinfo.SJID) { Dispatcher.Invoke(new Action(() => lbl_show_info.Content = StartJunction.JID), DispatcherPriority.Send); } else if (vinfo == Vehicleinfo.DJID) { Dispatcher.Invoke(new Action(() => lbl_show_info.Content = EndJunction.JID), DispatcherPriority.Send); } else if (vinfo == Vehicleinfo.LaneIndex) { Dispatcher.Invoke(new Action(() => lbl_show_info.Content = CurrentLane.LaneIndex), DispatcherPriority.Send); } else if (vinfo == Vehicleinfo.InstanceLocation) { int X = Convert.ToInt32(InstanceLocation.X); int Y = Convert.ToInt32(InstanceLocation.Y); Dispatcher.Invoke(new Action(() => lbl_show_info.Content = X + "," + Y), DispatcherPriority.Send); } else if (vinfo == Vehicleinfo.RemianDistanceToHeadingJunction) { Dispatcher.Invoke(new Action(() => lbl_show_info.Content = RemianDistanceToHeadingJunction.ToString("0.00")), DispatcherPriority.Send); } else if (vinfo == Vehicleinfo.TravelledDistanceInMeter) { Dispatcher.Invoke(new Action(() => lbl_show_info.Content = TravelledDistanceInMeter.ToString("0.00")), DispatcherPriority.Send); } else if (vinfo == Vehicleinfo.ExceededDistanceInMeter) { Dispatcher.Invoke(new Action(() => lbl_show_info.Content = ExceededDistanceInMeter.ToString("0.00")), DispatcherPriority.Send); } else if (vinfo == Vehicleinfo.PacketsQueueLength) { Dispatcher.Invoke(new Action(() => lbl_show_info.Content = PacketQueue.Count), DispatcherPriority.Send); } else if (vinfo == Vehicleinfo.JunctionQueueIndex) { Dispatcher.Invoke(new Action(() => lbl_show_info.Content = IndexInQueue), DispatcherPriority.Send); } else if (vinfo == Vehicleinfo.RIDpluseLaneIndex) { Dispatcher.Invoke(new Action(() => lbl_show_info.Content = CurrentLane.MyRoadSegment.RID + "-" + CurrentLane.LaneIndex), DispatcherPriority.Send); } }); }
public void CanConvert_NullableTestEnum_ReturnsTrue() { EnumConverter <TestEnum> converter = new EnumConverter <TestEnum>(); Assert.IsFalse(converter.CanConvert(typeof(TestEnum?))); }
/** * Specifies that a break shall be placed at the current location in the run * content. * A break is a special character which is used to override the * normal line breaking that would be performed based on the normal layout * of the document's contents. * <p> * The behavior of this break character (the * location where text shall be restarted After this break) shall be * determined by its type values. * </p> * @see BreakType */ public void AddBreak(BreakType type) { CT_Br br = run.AddNewBr(); br.type = EnumConverter.ValueOf <ST_BrType, BreakType>(type); }
private void UpdateStatus(User source, User entity, USER_STATUS status) { entity.Status = status; this.Update(null, entity); var log = new DbLog(DateTime.Now, ACTION_TARGET.USER, ACTION.CHANGE_STATUS, CHANGE_FIELD.TITLE, source.Id, entity.Id, entity.Name, EnumConverter.Convert(status), null); _context.DbLogs.Add(log); _context.SaveChanges(); }
public LRS(Indicator indicator, int length, RegressionDistanceMode distanceMode) { this.indicator = new FreeQuant.Indicators.LRS(indicator.indicator, length); (this.indicator as FreeQuant.Indicators.LRS).DistanceMode = EnumConverter.Convert(distanceMode); }
public LRS(BarSeries series, int length, BarData option, Color color) { this.indicator = new FreeQuant.Indicators.LRS(series.series, length, EnumConverter.Convert(option), color); }
private async void PropertyControl_OnDataContextChanged(FrameworkElement sender, DataContextChangedEventArgs args) { if (args.NewValue == _currentSample) { return; } _currentSample = DataContext as Sample; RootPanel.Children.Clear(); if (_currentSample != null) { var propertyDesc = await _currentSample.GetPropertyDescriptorAsync(); if (propertyDesc == null) { return; } foreach (var option in propertyDesc.Options) { // Label var label = new TextBlock { Text = option.Name + ":", Foreground = new SolidColorBrush(Colors.Black) }; RootPanel.Children.Add(label); // Control Control controlToAdd; DependencyProperty dependencyProperty; IValueConverter converter = null; switch (option.Kind) { case PropertyKind.Slider: case PropertyKind.DoubleSlider: var slider = new Slider(); var sliderOption = option as SliderPropertyOptions; if (sliderOption != null) { slider.Minimum = sliderOption.MinValue; slider.Maximum = sliderOption.MaxValue; } if (option.Kind == PropertyKind.DoubleSlider) { slider.StepFrequency = 0.01; } controlToAdd = slider; dependencyProperty = RangeBase.ValueProperty; break; case PropertyKind.Enum: var enumType = option.DefaultValue.GetType(); var comboBox = new ComboBox { ItemsSource = Enum.GetNames(enumType), SelectedItem = option.DefaultValue.ToString() }; converter = new EnumConverter(enumType); controlToAdd = comboBox; dependencyProperty = Selector.SelectedItemProperty; break; case PropertyKind.Bool: var checkBox = new ToggleSwitch(); controlToAdd = checkBox; dependencyProperty = ToggleSwitch.IsOnProperty; break; case PropertyKind.Brush: var colorComboBox = new ComboBox(); var dataSource = typeof(Colors).GetTypeInfo().DeclaredProperties.Select(p => p.Name).ToList(); colorComboBox.ItemsSource = dataSource; colorComboBox.SelectedIndex = dataSource.IndexOf(option.DefaultValue.ToString()); converter = new SolidColorBrushConverter(); controlToAdd = colorComboBox; dependencyProperty = Selector.SelectedItemProperty; break; default: var textBox = new TextBox { Text = option.DefaultValue.ToString() }; controlToAdd = textBox; dependencyProperty = TextBox.TextProperty; break; } var binding = new Binding { Source = propertyDesc.Expando, Path = new PropertyPath(option.Name + ".Value"), Mode = BindingMode.TwoWay, Converter = converter }; controlToAdd.SetBinding(dependencyProperty, binding); controlToAdd.Margin = new Thickness(0, 5, 0, 20); RootPanel.Children.Add(controlToAdd); } } }
public static IEnumerable <Fermentable> GetAvailableFermentables(SQLiteConnection connection) { SQLiteCommand selectFermentablesCommand = connection.CreateCommand(); selectFermentablesCommand.CommandText = "SELECT name, yield, yieldByWeight, color, origin, notes, diastaticPower, type, maltCategory, gravityPoint FROM Fermentables"; using SQLiteDataReader reader = selectFermentablesCommand.ExecuteReader(); while (reader.Read()) { string name = reader.GetString(0); string yieldValue = reader[1].ToString(); float? yield = !yieldValue.IsNullOrEmpty() ? (float?)float.Parse(yieldValue) : null; string yieldByWeightValue = reader[2].ToString(); float? yieldByWeight = !yieldByWeightValue.IsNullOrEmpty() ? (float?)float.Parse(yieldByWeightValue) : null; float color = reader.GetFloat(3); string origin = reader.GetString(4); string notes = reader.GetString(5); string diastaticPowerValue = reader[6].ToString(); float? diastaticPower = !diastaticPowerValue.IsNullOrEmpty() ? (float?)float.Parse(diastaticPowerValue) : null; FermentableType type = EnumConverter.Parse <FermentableType>(reader.GetString(7)); string maltCategoryValue = reader[8].ToString(); MaltCategory? maltCategory = !maltCategoryValue.IsNullOrEmpty() ? (MaltCategory?)EnumConverter.Parse <MaltCategory>(maltCategoryValue) : null; int gravityPoint = reader.GetInt32(9); var characteristics = new FermentableCharacteristics(yield, color, diastaticPower) { YieldByWeight = yieldByWeight, Type = type, MaltCategory = maltCategory, GravityPoint = gravityPoint }; yield return(new Fermentable(name, characteristics, notes, origin)); } }
/// <summary> /// Отчет "Отчёт об успеваемости студента за {semester} семестр" /// </summary> /// <param name="root"></param> /// <returns></returns> public static Report GetStudentPerformance(Root root, Semester semester, Student student) { var caption = $"Отчёт об успеваемости студента за {semester} семестр"; var report = new Report { Caption = caption }; report.ReportColumns.Add(new ReportColumn("Предмет", 500), new ReportColumn("Оценка", 200)); // добавляем строки в отчет foreach (var item in root.Performances.Where(x => x.IdSemester == semester.IdSemester && x.IdStudent == student.IdStudent)) { report.ReportRows.Add(0, $"{Helper.MatterById(item.IdMatter)}", $"{EnumConverter.GetName(item.Grade)}"); } // определение обработчика печати страницы отчета report.PrintPage = (o, e, rect, offset) => { SizeF strSize = new SizeF(); var strPoint = offset; // Печать данных студента strPoint.X = rect.X + 50; var data = new[] { student.ToString(), Helper.GetStudyGroupById(student.IdStudyGroup).ToString() }; using (var headerfont = new Font("Arial", 12, FontStyle.Bold)) using (var sf = new StringFormat()) { sf.Alignment = StringAlignment.Near; sf.LineAlignment = StringAlignment.Center; for (var i = 0; i < data.Length; i++) { var width = i == 0 ? 500 : 200; strSize = e.Graphics.MeasureString(data[i], headerfont); var r = new Rectangle(Point.Ceiling(strPoint), new Size(width, (int)strSize.Height)); using (var rowfont = new Font("Arial", 12, FontStyle.Bold)) { e.Graphics.DrawString(i == 0 ? "Ф.И.О.:" : "Группа:", rowfont, Brushes.Black, r, sf); } r.Offset(70, 0); e.Graphics.DrawString(data[i], headerfont, Brushes.Red, r, sf); strPoint.X += width; } } strPoint.Y += strSize.Height + 10; // Печать заголовка таблицы strPoint.X = rect.X + 50; using (var headerfont = new Font("Arial", 12, FontStyle.Bold)) using (var sf = new StringFormat()) { sf.Alignment = StringAlignment.Near; sf.LineAlignment = StringAlignment.Center; foreach (var header in report.ReportColumns) { strSize = e.Graphics.MeasureString(header.Text, headerfont); var r = new Rectangle(Point.Ceiling(strPoint), new Size(header.Width, (int)strSize.Height)); e.Graphics.DrawString(header.Text, headerfont, Brushes.Black, r, sf); strPoint.X += header.Width; } } // Печать строк таблицы strPoint.Y += strSize.Height + 10; using (var rowfont = new Font("Arial", 12, FontStyle.Regular)) using (var sf = new StringFormat()) { sf.Alignment = StringAlignment.Near; sf.LineAlignment = StringAlignment.Center; foreach (var row in report.ReportRows) { strPoint.X = rect.X + 50; string value; // здесь будет значение for (var i = 0; i < report.ReportColumns.Count; i++) { value = row.Items[i]; var r = new Rectangle(Point.Ceiling(strPoint), new Size(report.ReportColumns[i].Width, (int)strSize.Height)); e.Graphics.DrawString(value, rowfont, Brushes.Black, r, sf); strPoint.X += report.ReportColumns[i].Width; } strPoint.Y += strSize.Height; } } }; return(report); }
//Adds a mod directly to target item (or bench item) if legal; updates costs if provided; modifies mod pool accordingly if provided public string ForceAddMod(PoEModData mod, ItemCraft target = null, IDictionary <string, int> costs = null, IDictionary <PoEModData, int> pool = null) { target = target ?? BenchItem; if (mod.generation_type == ModLogic.Prefix) { if (target.ModCountByType(ModLogic.Prefix) >= target.GetAffixLimit(true)) { return("Item cannot have another prefix"); } } else { if (target.ModCountByType(ModLogic.Suffix) >= target.GetAffixLimit(true)) { return("Item cannot have another suffix"); } } foreach (ModCraft livemod in target.LiveMods) { PoEModData modtemplate = CraftingDatabase.AllMods[livemod.SourceData]; if (modtemplate.group == mod.group) { return("Item already has a mod in this mod group"); } } if (mod.domain == "crafted") //if crafted check the specific cases of quality craft on item w/ quality mod, and conversion glove mod { if (target.LiveTags.Contains("local_item_quality")) { foreach (PoEModWeight w in mod.spawn_weights) { if (w.tag == "local_item_quality" && w.weight == 0) { return("Cannot craft quality on an item with another quality mod"); } } } if (target.LiveTags.Contains("has_physical_conversion_mod") && mod.adds_tags.Contains("has_physical_conversion_mod")) { return("Item already has a physical conversion mod"); } //This check turned out to the too restrictive. Many crafted mods have 0 spawn weight on item types they should be craftable on. //if (ModLogic.CalcGenWeight(mod, target.LiveTags) <= 0) // return "Invalid craft for current item and/or item mods"; } PoEBaseItemData itemtemplate = CraftingDatabase.AllBaseItems[target.SourceData]; //if it's an influenced mod, add the appropriate tag foreach (ItemInfluence inf in Enum.GetValues(typeof(ItemInfluence))) { if (EnumConverter.InfToNames(inf).Contains(mod.name)) { string inftag = itemtemplate.item_class_properties[EnumConverter.InfToTag((ItemInfluence)inf)]; if (inftag != null) { target.LiveTags.Add(inftag); } break; } } //if a mod pool is provided, updated it accordingly, otherwise just add the mod directly if (pool != null) { ModLogic.AddModAndTrim(target, pool, mod); } else { target.AddMod(mod); } ItemRarity newrarity = target.GetMinimumRarity(); if (newrarity > target.Rarity) { target.Rarity = newrarity; } if (costs != null && target == BenchItem) { foreach (string s in costs.Keys) { TallyCurrency(s, costs[s]); } } return(null); }
private bool DoAddMod(ItemRarity targetrarity, bool rename, int count, int qualityconsumed, ItemInfluence?inf = null) { string inftag = null; if (inf != null) { inftag = CraftingDatabase.AllBaseItems[BenchItem.SourceData].item_class_properties[EnumConverter.InfToTag(inf.Value)]; } ItemCraft dummy = BenchItem.Copy(); if (inftag != null) { dummy.LiveTags.Add(inftag); } dummy.Rarity = targetrarity; IDictionary <PoEModData, int> validatedpool = ModLogic.FindValidMods(dummy, BaseValidMods); if (inf != null) { validatedpool = ModLogic.FilterForInfluence(validatedpool, inf.Value); } if (validatedpool.Count == 0) { return(false); } DoCurrencyRolls((item) => { if (inftag != null) { item.LiveTags.Add(inftag); } item.Rarity = targetrarity; IDictionary <PoEModData, int> poolcopy = new Dictionary <PoEModData, int>(validatedpool); ModLogic.RollAddMod(item, poolcopy); if (item.QualityType != null) { item.BaseQuality -= qualityconsumed; } if (rename) { item.GenerateName(); } }, count); return(true); }
protected override uint ToBinary(TEnum value) { return(EnumConverter <TEnum> .ToUInt(value)); }
public ControlPanelUserQueryFilterVM() { this.ListStatus = EnumConverter.GetKeyValuePairs <ControlPanelUserStatus>(EnumConverter.EnumAppendItemType.All); this.PagingInfo = new PagingInfo(); }
internal static IEnumerable <FermentableIngredientDataModel> GetFermentableIngredientsForRecipe(int recipeId, SQLiteConnection connection) { using SQLiteCommand selectIngredientsCommand = connection.CreateCommand(); selectIngredientsCommand.CommandText = "SELECT FermentableIngredients.id, FermentableIngredients.amount, Fermentables.name, Fermentables.yield, Fermentables.yieldByWeight, Fermentables.color, Fermentables.origin, Fermentables.notes, Fermentables.diastaticPower, Fermentables.type, Fermentables.maltCategory, Fermentables.gravityPoint FROM FermentableIngredients " + "JOIN FermentablesInRecipe ON FermentablesInRecipe.fermentableIngredient = FermentableIngredients.id AND FermentablesInRecipe.recipe = @recipeId " + "JOIN Fermentables ON Fermentables.id = FermentableIngredients.fermentableInfo"; selectIngredientsCommand.Parameters.AddWithValue("recipeId", recipeId); using SQLiteDataReader reader = selectIngredientsCommand.ExecuteReader(); while (reader.Read()) { string yieldValue = reader[3].ToString(); float? yield = !yieldValue.IsNullOrEmpty() ? (float?)float.Parse(yieldValue) : null; string yieldByWeightValue = reader[4].ToString(); float? yieldByWeight = !yieldByWeightValue.IsNullOrEmpty() ? (float?)float.Parse(yieldByWeightValue) : null; string diastaticPowerValue = reader[8].ToString(); float? diastaticPower = !diastaticPowerValue.IsNullOrEmpty() ? (float?)float.Parse(diastaticPowerValue) : null; string maltCategoryValue = reader[10].ToString(); MaltCategory?maltCategory = !maltCategoryValue.IsNullOrEmpty() ? EnumConverter.Parse <MaltCategory>(maltCategoryValue) : null; var characteristics = new FermentableCharacteristics(yield, reader.GetFloat(5), diastaticPower) { GravityPoint = reader.GetInt32(11), Type = EnumConverter.Parse <FermentableType>(reader.GetString(9)), MaltCategory = maltCategory, YieldByWeight = yieldByWeight }; var fermentableInfo = new Fermentable(reader.GetString(2), characteristics, reader.GetString(7), reader.GetString(6)); yield return(new FermentableIngredientDataModel(fermentableInfo, reader.GetInt32(0)) { Amount = reader.GetFloat(1) }); } }
/// <summary> /// Returns a registered converter. /// </summary> /// <param name="type">The lookup type.</param> /// <returns>If there is no a converter for the type it will be null; otherwise the converter.</returns> public Func<object, object> GetConverter(Type type) { Func<object, object> converter; Converters.TryGetValue(type, out converter); if (converter == null) { var nullable = false; if(type.IsEnum == false) { type = Nullable.GetUnderlyingType(type); if (type == null || type.IsEnum == false) return null; nullable = true; } var enumConverter = new EnumConverter(this, type, nullable); RegisterConverter(type, enumConverter.Convert); return enumConverter.Convert; } return converter; }
/// <summary> /// 构造函数 /// </summary> public BrandVM() { BrandStatusList = EnumConverter.GetKeyValuePairs <ValidStatus>(EnumConverter.EnumAppendItemType.None); }
public LRS(Indicator indicator, int length, RegressionDistanceMode distanceMode, BarData option, Color color) { this.indicator = new FreeQuant.Indicators.LRS(indicator.indicator, length, EnumConverter.Convert(option), color); (this.indicator as FreeQuant.Indicators.LRS).DistanceMode = EnumConverter.Convert(distanceMode); }
/// <summary> /// Process the Set-IshFolder commandlet. /// </summary> /// <exception cref="TrisoftAutomationException"></exception> /// <exception cref="Exception"></exception> /// <remarks>Writes an <see cref="IshFolder"/> array to the pipeline</remarks> protected override void ProcessRecord() { try { // 1. Validating the input WriteDebug("Validating"); string xmlIshFolders = ""; long folderId = -5; string[] readAccess; string newFolderName; List <long> returnFolderIds = new List <long>(); if (IshFolder != null) { // 1a. read all info from the IshFolder/IshFields object IshFolder[] ishFolders = IshFolder; int current = 0; foreach (IshFolder ishFolder in ishFolders) { // read "folderRef" from the ishFolder object folderId = ishFolder.IshFolderRef; WriteDebug($"folderId[{folderId}] {++current}/{ishFolders.Length}"); string readAccessString = ishFolder.IshFields.GetFieldValue("READ-ACCESS", Enumerations.Level.None, Enumerations.ValueType.Value); readAccess = readAccessString.Split(new[] { IshSession.Seperator }, StringSplitOptions.RemoveEmptyEntries); newFolderName = ishFolder.IshFields.GetFieldValue("FNAME", Enumerations.Level.None, Enumerations.ValueType.Value); if (readAccess == null) { WriteDebug($"Renaming folderId[{folderId}]"); if (ShouldProcess(Convert.ToString(folderId))) { IshSession.Folder25.Rename(folderId, newFolderName); } } else { WriteDebug($"Updating folderId[{folderId}]"); if (ShouldProcess(Convert.ToString(folderId))) { IshSession.Folder25.Update(folderId, newFolderName, readAccess); } } returnFolderIds.Add(folderId); } } else if (FolderId != 0) { // 1b. Retrieve using FolderId WriteDebug($"folderId[{FolderId}]"); folderId = FolderId; readAccess = ReadAccess; newFolderName = _newFolderName; if (newFolderName == null && readAccess == null) { WriteDebug($"Renaming folderId[{folderId}]"); if (ShouldProcess(Convert.ToString(folderId))) { IshSession.Folder25.Rename(folderId, newFolderName); } } else { WriteDebug($"Updating folderId[{folderId}]"); if (ShouldProcess(Convert.ToString(folderId))) { IshSession.Folder25.Update(folderId, newFolderName, readAccess); } } returnFolderIds.Add(folderId); } else if (FolderPath != null) { // 1c. Retrieve using provided parameter FolderPath // Parse FolderPath input parameter: get basefolderName(1st element of an array) string folderPath = FolderPath; string[] folderPathElements = folderPath.Split( new string[] { IshSession.FolderPathSeparator }, StringSplitOptions.RemoveEmptyEntries); string baseFolderLabel = folderPathElements[0]; // remaining folder path elements string[] folderPathTrisoft = new string[folderPathElements.Length - 1]; Array.Copy(folderPathElements, 1, folderPathTrisoft, 0, folderPathElements.Length - 1); WriteDebug($"FolderPath[{folderPath}]"); string xmlIshFolder = IshSession.Folder25.GetMetadata( BaseFolderLabelToEnum(IshSession, baseFolderLabel), folderPathTrisoft, ""); IshFolders ishFolder = new IshFolders(xmlIshFolder, "ishfolder"); folderId = ishFolder.Folders[0].IshFolderRef; readAccess = ReadAccess; newFolderName = _newFolderName; if (newFolderName == "") { WriteWarning("Skipping rename to empty for folderId[" + folderId + "]"); } else if (readAccess == null) { WriteDebug($"Renaming folderId[{folderId}]"); if (ShouldProcess(Convert.ToString(folderId))) { IshSession.Folder25.Rename(folderId, newFolderName); } } else { WriteDebug($"Updating folderId[{folderId}]"); if (ShouldProcess(Convert.ToString(folderId))) { IshSession.Folder25.Update(folderId, newFolderName, readAccess); } } returnFolderIds.Add(folderId); } else { // 1d. Retrieve subfolder(s) from the specified root folder using BaseFolder string (enumeration) var baseFolder = EnumConverter.ToBaseFolder <Folder25ServiceReference.BaseFolder>(BaseFolder); xmlIshFolders = IshSession.Folder25.GetMetadata( baseFolder, new string[0], ""); IshFolders retrievedFolders = new IshFolders(xmlIshFolders, "ishfolder"); folderId = retrievedFolders.Folders[0].IshFolderRef; readAccess = ReadAccess; newFolderName = _newFolderName; if (newFolderName == "") { WriteWarning("Skipping rename to empty for folderId[" + folderId + "]"); } if (readAccess == null) { WriteDebug($"Renaming folderId[{folderId}]"); if (ShouldProcess(Convert.ToString(folderId))) { IshSession.Folder25.Rename(folderId, newFolderName); } } else { WriteDebug($"Updating folderId[{folderId}]"); if (ShouldProcess(Convert.ToString(folderId))) { IshSession.Folder25.Update(folderId, newFolderName, readAccess); } } returnFolderIds.Add(folderId); } // Retrieve updated folder from the database and write it out WriteDebug("Retrieving"); // Add the required fields (needed for pipe operations) IshFields requestedMetadata = IshSession.IshTypeFieldSetup.ToIshRequestedMetadataFields(IshSession.DefaultRequestedMetadata, ISHType, new IshFields(), Enumerations.ActionMode.Read); xmlIshFolders = IshSession.Folder25.RetrieveMetadataByIshFolderRefs(returnFolderIds.ToArray(), requestedMetadata.ToXml()); // 3b. Write it var returnIshObjects = new IshFolders(xmlIshFolders).FolderList; WriteVerbose("returned object count[" + returnIshObjects.Count + "]"); WriteObject(IshSession, ISHType, returnIshObjects.ConvertAll(x => (IshBaseObject)x), true); } catch (TrisoftAutomationException trisoftAutomationException) { ThrowTerminatingError(new ErrorRecord(trisoftAutomationException, base.GetType().Name, ErrorCategory.InvalidOperation, null)); } catch (Exception exception) { ThrowTerminatingError(new ErrorRecord(exception, base.GetType().Name, ErrorCategory.NotSpecified, null)); } }
public LRS(Indicator indicator, int length, BarData option, Color color) { this.indicator = new FreeQuant.Indicators.LRS(indicator.indicator, length, EnumConverter.Convert(option), color); }
/// <summary> /// Update property for entity. /// </summary> /// <param name="entity">Entity to update.</param> /// <param name="propertyMetadata">Property metadata.</param> /// <returns></returns> public async Task UpdateProperty(TEntity entity, IPropertyMetadata propertyMetadata) { if (propertyMetadata.EditRoles.Count() > 0 && !(propertyMetadata.AuthenticationRequiredMode == AuthenticationRequiredMode.All ? propertyMetadata.EditRoles.All(r => Controller.User.IsInRole(r)) : propertyMetadata.EditRoles.Any(r => Controller.User.IsInRole(r)))) { return; } if (propertyMetadata.IsFileUpload) { #region File Path Value if (!Controller.Request.Files.AllKeys.Contains(propertyMetadata.ClrName)) { return; } if (!(Controller is IFileController <TEntity>)) { if (propertyMetadata.ClrType != typeof(byte[])) { throw new NotSupportedException("Controller doesn't support upload file."); } if (Controller.Request.Files.AllKeys.Contains(propertyMetadata.ClrName)) { var file = Controller.Request.Files[propertyMetadata.ClrName]; MemoryStream stream = new MemoryStream(); await file.InputStream.CopyToAsync(stream); propertyMetadata.SetValue(entity, stream.ToArray()); stream.Close(); stream.Dispose(); } } else { await((IFileController <TEntity>)Controller).SaveFileToProperty(entity, propertyMetadata, Controller.Request.Files[propertyMetadata.ClrName]); } #endregion } else { if (!Controller.Request.Form.AllKeys.Contains(propertyMetadata.ClrName)) { return; } string value = Controller.Request.Form[propertyMetadata.ClrName]; TypeConverter converter = EntityValueConverter.GetConverter(propertyMetadata); if (converter == null) { if (propertyMetadata.ClrType.IsGenericType && propertyMetadata.ClrType.GetGenericTypeDefinition() == typeof(ICollection <>)) { converter = new Converter.CollectionConverter(); } else if (propertyMetadata.ClrType.IsEnum) { converter = new EnumConverter(propertyMetadata.ClrType); } else { converter = TypeDescriptor.GetConverter(propertyMetadata.ClrType); if (converter == null && propertyMetadata.Type != ComponentModel.DataAnnotations.CustomDataType.Password) { throw new NotSupportedException("Type of \"" + propertyMetadata.ClrName + "\" converter not found."); } } } if (propertyMetadata.Type == ComponentModel.DataAnnotations.CustomDataType.Password && entity is IPassword) { object v = propertyMetadata.GetValue(entity); if (v == null || value != v.ToString()) { ((IPassword)entity).SetPassword(value); } } else { EntityValueConverterContext context = new EntityValueConverterContext(EntityBuilder.DescriptorContext, propertyMetadata); object cvalue; try { cvalue = converter.ConvertFrom(context, null, value); } catch (Exception ex) { Controller.ViewBag.ErrorMessage = ex.Message; return; } if (converter.GetType() == typeof(Converter.CollectionConverter)) { object collection = propertyMetadata.GetValue(entity); ((dynamic)collection).Clear(); var addMethod = collection.GetType().GetMethod("Add"); object[] array = (object[])cvalue; for (int a = 0; a < array.Length; a++) { addMethod.Invoke(collection, new object[] { array[a] }); } } else { propertyMetadata.SetValue(entity, cvalue); } } } }
public LRS(BarSeries series, int length, RegressionDistanceMode distanceMode, BarData option) { this.indicator = new FreeQuant.Indicators.LRS(series.series, length, EnumConverter.Convert(option)); (this.indicator as FreeQuant.Indicators.LRS).DistanceMode = EnumConverter.Convert(distanceMode); }
/// <summary> /// Serializes the given object into a CodeDom object. /// </summary> public override object Serialize(IDesignerSerializationManager manager, object value) { CodeExpression expression = null; using (TraceScope("EnumCodeDomSerializer::" + nameof(Serialize))) { Trace("Type: {0}", (value is null ? "(null)" : value.GetType().Name)); if (value is Enum) { bool needCast = false; Enum[] values; TypeConverter converter = TypeDescriptor.GetConverter(value); if (converter != null && converter.CanConvertTo(typeof(Enum[]))) { values = (Enum[])converter.ConvertTo(value, typeof(Enum[])); needCast = (values.Length > 1); } else { values = new Enum[] { (Enum)value }; needCast = true; } // EnumConverter (and anything that is overridden to support enums) // should be providing us a conversion to Enum[] for flag styles. // If it doesn't, we will emit a warning and just do a cast from the enum value. CodeTypeReferenceExpression enumType = new CodeTypeReferenceExpression(value.GetType()); // If names is of length 1, then this is a simple field reference. Otherwise, // it is an or-d combination of expressions. // TraceIf(values.Length == 1, "Single field entity."); TraceIf(values.Length > 1, "Multi field entity."); // We now need to serialize the enum terms as fields. We new up an EnumConverter to do // that. We cannot use the type's own converter since it might have a different string // representation for its values. Hardcoding is okay in this case, since all we want is // the enum's field name. Simply doing ToString() will not give us any validation. TypeConverter enumConverter = new EnumConverter(value.GetType()); foreach (Enum term in values) { string termString = enumConverter?.ConvertToString(term); CodeExpression newExpression = !string.IsNullOrEmpty(termString) ? new CodeFieldReferenceExpression(enumType, termString) : null; if (newExpression != null) { if (expression is null) { expression = newExpression; } else { expression = new CodeBinaryOperatorExpression(expression, CodeBinaryOperatorType.BitwiseOr, newExpression); } } } // If we had to combine multiple names, wrap the result in an appropriate cast. // if (expression != null && needCast) { expression = new CodeCastExpression(value.GetType(), expression); } } else { Debug.Fail("Enum serializer called for non-enum object."); TraceError("Enum serializer called for non-enum object {0}", (value is null ? "(null)" : value.GetType().Name)); } } return(expression); }
/** * Specifies that the contents of this run.should be displayed along with an * underline appearing directly below the character heigh * * @return the Underline pattern Applyed to this run * @see UnderlinePatterns */ public UnderlinePatterns GetUnderline() { CT_RPr pr = run.rPr; return((pr != null && pr.IsSetU()) ? EnumConverter.ValueOf <UnderlinePatterns, ST_Underline>(pr.u.val) : UnderlinePatterns.None); }
private void BindComboBoxData() { //商户: this.Merchant.ItemsSource = EnumConverter.GetKeyValuePairs <CompanyCustomer>(EnumConverter.EnumAppendItemType.All); this.Merchant.SelectedIndex = 0; }
public void CanConvert_TestEnum_ReturnsTrue() { EnumConverter <TestEnum> converter = new EnumConverter <TestEnum>(); Assert.IsTrue(converter.CanConvert(typeof(TestEnum))); }
private void PropertyControl_OnDataContextChanged(FrameworkElement sender, DataContextChangedEventArgs args) { if (args.NewValue == _currentSample) { return; } _currentSample = DataContext as Sample; RootPanel.Children.Clear(); if (_currentSample != null) { var propertyDesc = _currentSample.PropertyDescriptor; if (propertyDesc == null) { return; } foreach (var option in propertyDesc.Options) { // Label var label = new TextBlock { Text = option.Label, FontSize = 15, FontWeight = FontWeights.Bold }; RootPanel.Children.Add(label); // Control Control controlToAdd; DependencyProperty dependencyProperty; IValueConverter converter = null; IDictionary <string, object> propertyDict = propertyDesc.Expando; switch (option.Kind) { case PropertyKind.Slider: case PropertyKind.DoubleSlider: var slider = new Slider(); var sliderOption = option as SliderPropertyOptions; if (sliderOption != null) { slider.Minimum = sliderOption.MinValue; slider.Maximum = sliderOption.MaxValue; slider.StepFrequency = sliderOption.Step; } if (option.Kind == PropertyKind.DoubleSlider) { slider.StepFrequency = 0.01; } if ((propertyDict[option.Name] as ValueHolder).Value is double value) { slider.Value = value; } controlToAdd = slider; dependencyProperty = RangeBase.ValueProperty; break; case PropertyKind.Enum: var enumType = option.DefaultValue.GetType(); var comboBox = new ComboBox { ItemsSource = Enum.GetNames(enumType), SelectedItem = (propertyDict[option.Name] as ValueHolder).Value.ToString() }; converter = new EnumConverter(enumType); controlToAdd = comboBox; dependencyProperty = Selector.SelectedItemProperty; break; case PropertyKind.Bool: var checkBox = new ToggleSwitch(); if ((propertyDict[option.Name] as ValueHolder).Value is bool isOn) { checkBox.IsOn = isOn; } controlToAdd = checkBox; dependencyProperty = ToggleSwitch.IsOnProperty; break; case PropertyKind.Brush: var colorComboBox = new ComboBox(); var dataSource = typeof(Colors).GetTypeInfo().DeclaredProperties.Select(p => p.Name).ToList(); colorComboBox.ItemsSource = dataSource; if ((propertyDict[option.Name] as ValueHolder).Value is SolidColorBrush brush && _colorNames.TryGetValue(brush.Color, out var color)) { colorComboBox.SelectedIndex = dataSource.IndexOf(color); } else { colorComboBox.SelectedIndex = dataSource.IndexOf(option.DefaultValue.ToString()); } converter = new SolidColorBrushConverter(); controlToAdd = colorComboBox; dependencyProperty = Selector.SelectedItemProperty; break;
public void CanConvert_CanWrite_ReturnsTrue() { EnumConverter <TestEnum> converter = new EnumConverter <TestEnum>(); Assert.IsTrue(converter.CanWrite); }
static void ProcessNavGraphicsMessage(Message m) // used for emulator { var ae = ScreenCleared; // This is the only usage? - no, for emulator if (ae != null && m.Data.Compare(MessageClearScreen.Data)) { ae(); //m.ReceiverDescription = "Clear screen"; return; } ae = ScreenRefreshed; // This is the only usage? - no, for emulator if (ae != null && m.Data.Compare(MessageRefreshScreen.Data)) { ae(); //m.ReceiverDescription = "Refresh screen"; OnScreenUpdated(); return; } var e = TextReceived; // This is the only usage? - no, for emulator if (e != null || ReplyToScreenUpdates) { if (m.Data.StartsWith(DataDrawIndexMk2) || m.Data.StartsWith(DataDrawIndexMk34)) { var a = new BordmonitorText(BordmonitorFields.Item, m.Data); if (e != null) { e(a); } //#if NETMF //m.ReceiverDescription = "BM fill items"; //#else //var s = "BM fill items"; //var items = a.ParseItems(); //foreach (var i in items) //{ // s += " | " + i.Index.ToHex() + "." + i.Text; //} //m.ReceiverDescription = s; //#endif OnScreenUpdated(true); } else if (m.Data.StartsWith(DataUpdateScreen)) { if (m.Data.StartsWith(DataShowHeader)) { var headerIndex = m.Data[DataShowHeader.Length]; var field = EnumConverter.GetBordmonitorFieldFromIndex(headerIndex); var a = new BordmonitorText(field, m.Data); if (e != null) { e(a); } //#if NETMF //m.ReceiverDescription = "BM show status"; //#else //m.ReceiverDescription = "BM show status: " + a.Text; //#endif } OnScreenUpdated(false); } else if (m.Data.StartsWith(DataShowTitle)) { var a = new BordmonitorText(BordmonitorFields.Title, m.Data); if (e != null) { e(a); } //#if NETMF //m.ReceiverDescription = "BM show title"; //#else //m.ReceiverDescription = "BM show title: " + a.Text; //#endif OnScreenUpdated(); } } }
public NavComAction(ILogger <NavComAction> logger, IImageLogic imageLogic, IFlightConnector flightConnector, EnumConverter enumConverter) { registration = new RegistrationParameters(Environment.GetCommandLineArgs()[1..]);
/// <summary> /// Process the Get-IshFolder commandlet. /// </summary> /// <exception cref="TrisoftAutomationException"></exception> /// <exception cref="Exception"></exception> /// <remarks>Writes an <see cref="IshFolder"/> object to the pipeline.</remarks> protected override void EndProcessing() { try { // 1. Validating the input WriteDebug("Validating"); List <IshFolder> returnIshFolders = new List <IshFolder>(); // 2. Doing Retrieve WriteDebug("Retrieving"); _requestedMetadata = IshSession.IshTypeFieldSetup.ToIshRequestedMetadataFields(IshSession.DefaultRequestedMetadata, ISHType, new IshFields(RequestedMetadata), Enumerations.ActionMode.Read); if (_retrievedIshFolders.Count > 0) { var folderCardIds = _retrievedIshFolders.Select(ishFolder => Convert.ToInt64(ishFolder.IshFolderRef)).ToList(); WriteDebug($"Retrieving CardIds.length[{folderCardIds.Count}] RequestedMetadata.length[{_requestedMetadata.ToXml().Length}] 0/{folderCardIds.Count}"); // Devides the list of folder card ids in different lists that all have maximally MetadataBatchSize elements List <List <long> > devidedFolderCardIdsList = DevideListInBatches <long>(folderCardIds, IshSession.MetadataBatchSize); int currentFolderCardIdCount = 0; foreach (List <long> folderCardIdBatch in devidedFolderCardIdsList) { // Process card ids in batches string xmlIshFolders = IshSession.Folder25.RetrieveMetadataByIshFolderRefs(folderCardIdBatch.ToArray(), _requestedMetadata.ToXml()); IshFolders retrievedObjects = new IshFolders(xmlIshFolders); returnIshFolders.AddRange(retrievedObjects.Folders); currentFolderCardIdCount += folderCardIdBatch.Count; WriteDebug($"Retrieving CardIds.length[{ folderCardIdBatch.Count}] RequestedMetadata.length[{ _requestedMetadata.ToXml().Length}] {currentFolderCardIdCount}/{folderCardIds.Count}"); } } else if (_retrievedFolderIds.Count > 0) { WriteDebug($"Retrieving CardIds.length[{ _retrievedFolderIds.Count}] RequestedMetadata.length[{_requestedMetadata.ToXml().Length}] 0/{_retrievedFolderIds.Count}"); // Devides the list of folder card ids in different lists that all have maximally MetadataBatchSize elements List <List <long> > devidedFolderCardIdsList = DevideListInBatches <long>(_retrievedFolderIds, IshSession.MetadataBatchSize); int currentFolderCardIdCount = 0; foreach (List <long> folderCardIdBatch in devidedFolderCardIdsList) { // Process card ids in batches string xmlIshFolders = IshSession.Folder25.RetrieveMetadataByIshFolderRefs(folderCardIdBatch.ToArray(), _requestedMetadata.ToXml()); IshFolders retrievedObjects = new IshFolders(xmlIshFolders); returnIshFolders.AddRange(retrievedObjects.Folders); currentFolderCardIdCount += folderCardIdBatch.Count; WriteDebug($"Retrieving CardIds.length[{folderCardIdBatch.Count}] RequestedMetadata.length[{_requestedMetadata.ToXml().Length}] {currentFolderCardIdCount}/{_retrievedFolderIds.Count}"); } } else if (FolderPath != null) { // Retrieve using provided parameter FolderPath // Parse FolderPath input parameter: get basefolderName(1st element of an array) string folderPath = FolderPath; string[] folderPathElements = folderPath.Split( new string[] { IshSession.FolderPathSeparator }, StringSplitOptions.RemoveEmptyEntries); string baseFolderLabel = folderPathElements[0]; // remaining folder path elements string[] folderPathTrisoft = new string[folderPathElements.Length - 1]; Array.Copy(folderPathElements, 1, folderPathTrisoft, 0, folderPathElements.Length - 1); WriteDebug($"FolderPath[{ folderPath}]"); string xmlIshFolder = IshSession.Folder25.GetMetadata( BaseFolderLabelToEnum(IshSession, baseFolderLabel), folderPathTrisoft, _requestedMetadata.ToXml()); IshFolders retrievedFolders = new IshFolders(xmlIshFolder, "ishfolder"); returnIshFolders.AddRange(retrievedFolders.Folders); } else { // Retrieve using BaseFolder string (enumeration) var baseFolder = EnumConverter.ToBaseFolder <Folder25ServiceReference.BaseFolder>(BaseFolder); WriteDebug($"BaseFolder[{baseFolder}]"); string xmlIshFolders = IshSession.Folder25.GetMetadata( baseFolder, new string[0], _requestedMetadata.ToXml()); IshFolders retrievedFolders = new IshFolders(xmlIshFolders, "ishfolder"); returnIshFolders.AddRange(retrievedFolders.Folders); } // 3b. Write it if (!Recurse) { WriteDebug($"returned object count[{returnIshFolders.Count}]"); WriteObject(IshSession, ISHType, returnIshFolders.ConvertAll(x => (IshBaseObject)x), true); } else { WriteParentProgress("Recursive folder retrieve...", 0, returnIshFolders.Count); foreach (IshFolder ishFolder in returnIshFolders) { WriteParentProgress("Recursive folder retrieve...", ++_parentCurrent, returnIshFolders.Count); if (_maxDepth > 0) { RetrieveRecursive(ishFolder, 0, _maxDepth); } } } } catch (TrisoftAutomationException trisoftAutomationException) { ThrowTerminatingError(new ErrorRecord(trisoftAutomationException, base.GetType().Name, ErrorCategory.InvalidOperation, null)); } catch (Exception exception) { ThrowTerminatingError(new ErrorRecord(exception, base.GetType().Name, ErrorCategory.NotSpecified, null)); } finally { base.EndProcessing(); } }
public ProductNotifyQueryVM() { NotifyStatusList = EnumConverter.GetKeyValuePairs <NotifyStatus>(EnumConverter.EnumAppendItemType.All); }
public static XsdType FindConverter(Type type) { if (type == null) throw new ArgumentNullException("type"); var actualType = Nullable.GetUnderlyingType(type) ?? type; bool isNullable = !type.IsInterface && !type.IsClass && IsNullable(type); XsdType result; if (actualType.IsEnum) { lock (_syncRoot) { EnumConverter enumConverter; if (!EnumConverters.TryGetValue(actualType, out enumConverter)) { enumConverter = new EnumConverter(actualType); EnumConverters.Add(actualType, enumConverter); } result = enumConverter; } } else { _convertersByType.TryGetValue(actualType, out result); } if (result != null && isNullable) result = new NullableConverter(actualType, result); return result; }