public static void SetValue(PropertyInfo prop, object value, IMapsDirectlyToDatabaseTable onObject) { //sometimes json decided to swap types on you e.g. int64 for int32 var propertyType = prop.PropertyType; //if it is a nullable int etc if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Nullable <>)) { propertyType = propertyType.GetGenericArguments()[0]; //lets pretend it's just int / whatever } if (value != null && value != DBNull.Value && !propertyType.IsInstanceOfType(value)) { if (propertyType == typeof(CatalogueFolder)) { //will be passed as a string value = value is string?new CatalogueFolder((Catalogue)onObject, (string)value) : (CatalogueFolder)value; } else if (propertyType == typeof(Uri)) { value = value is string?new Uri((string)value) : (Uri)value; } else if (typeof(Enum).IsAssignableFrom(propertyType)) { value = Enum.ToObject(propertyType, value);//if the property is an enum } else { value = UsefulStuff.ChangeType(value, propertyType); //the property is not an enum } } prop.SetValue(onObject, value); //if it's a shared property (most properties) use the new shared value being imported }
protected override bool SelectValueTypeImpl(DialogArgs args, Type paramType, object initialValue, out object chosen) { WritePromptFor(args); chosen = UsefulStuff.ChangeType(ReadLineWithAuto(), paramType); return(true); }
protected override bool SelectValueTypeImpl(string prompt, Type paramType, object initialValue, out object chosen) { if (DisallowInput) { throw new InputDisallowedException($"Value required for '{prompt}'"); } Console.WriteLine("Enter value for " + prompt + ":"); chosen = UsefulStuff.ChangeType(ReadLine(), paramType); return(true); }
protected override bool SelectValueTypeImpl(DialogArgs args, Type paramType, object initialValue, out object chosen) { //whatever else it is use string var typeTextDialog = new TypeTextOrCancelDialog(args, 1000, initialValue?.ToString()); if (typeTextDialog.ShowDialog() == DialogResult.OK) { chosen = UsefulStuff.ChangeType(typeTextDialog.ResultText, paramType); return(true); } chosen = null; return(false); }
private void setTextOrParseableProperty(object sender, EventArgs e) { Control senderAsControl = (Control)sender; int propertyIdx = (int)senderAsControl.Tag; try { if (string.IsNullOrWhiteSpace(senderAsControl.Text)) { _requiredProperties[propertyIdx].SetValue(SecondaryConstriant, null, null); } else { Type underlyingType = _requiredProperties[propertyIdx].PropertyType; _requiredProperties[propertyIdx].SetValue(SecondaryConstriant, UsefulStuff.ChangeType(senderAsControl.Text, underlyingType), null); } senderAsControl.ForeColor = Color.Black; lblException.Text = ""; } catch (Exception ex) { senderAsControl.ForeColor = Color.Red; //find the innermost exception int overflow = 0; string msg = ex.Message; while (ex.InnerException != null && overflow < 3) //only display up to 3 exception messages { ex = ex.InnerException; if (ex != null) { msg += "," + ex.Message; } overflow++; } lblException.Text = msg.Trim(','); } }
/// <summary> /// Returns the contents of this class expressed as the given <paramref name="paramType"/> or null if the current state /// does not describe an object of that Type /// </summary> /// <param name="paramType"></param> /// <returns></returns> public object GetValueForParameterOfType(Type paramType) { if (ExplicitNull) { return(null); } if (typeof(DirectoryInfo) == paramType) { return(new DirectoryInfo(RawValue)); } if (typeof(FileInfo) == paramType) { return(new FileInfo(RawValue)); } if (typeof(string) == paramType) { return(RawValue); } if (typeof(Type) == paramType) { return(Type); } if (typeof(DiscoveredDatabase) == paramType) { return(Database); } if (typeof(DiscoveredTable) == paramType) { return(Table); } //it's an array of DatabaseEntities if (paramType.IsArray && typeof(IMapsDirectlyToDatabaseTable).IsAssignableFrom(paramType.GetElementType())) { if (DatabaseEntities.Count == 0) { _logger.Warn($"Pattern matched no objects '{RawValue}'"); } return(DatabaseEntities.ToArray()); } if (typeof(IMapsDirectlyToDatabaseTable).IsAssignableFrom(paramType)) { return(GetOneDatabaseEntity <DatabaseEntity>()); } if (typeof(IMightBeDeprecated).IsAssignableFrom(paramType)) { return(GetOneDatabaseEntity <IMightBeDeprecated>()); } if (typeof(IDisableable) == paramType) { return(GetOneDatabaseEntity <IDisableable>()); } if (typeof(INamed) == paramType) { return(GetOneDatabaseEntity <INamed>()); } if (typeof(IDeleteable) == paramType) { return(GetOneDatabaseEntity <IDeleteable>()); } if (typeof(ICheckable) == paramType) { return(GetOneDatabaseEntity <ICheckable>()); } if (paramType.IsValueType && !typeof(Enum).IsAssignableFrom(paramType)) { return(UsefulStuff.ChangeType(RawValue, paramType)); } if (paramType.IsEnum) { return(Enum.Parse(paramType, RawValue, true)); } return(null); }
public SecondaryConstraintUI(ICatalogueRepository repository, SecondaryConstraint secondaryConstriant, string[] otherColumns) { const int rowHeight = 30; //the amount of additional space required to accomodate description labels int inflation = 0; _repository = repository; this.SecondaryConstriant = secondaryConstriant; _otherColumns = otherColumns; InitializeComponent(); if (repository == null) { return; } cbxConsequence.DataSource = Enum.GetValues(typeof(Consequence)); cbxConsequence.SelectedItem = secondaryConstriant.Consequence; //put the name of the secondary constraint into the header this.lblType.Text = SecondaryConstriant.GetType().Name; lblConsequence.Left = lblType.Right + 5; cbxConsequence.Left = lblConsequence.Right + 5; //work out what properties can be set on this constraint and create the relevant controls using reflection _requiredProperties = secondaryConstriant.GetType().GetProperties().Where(p => p.CanRead && p.CanWrite && p.GetSetMethod(true).IsPublic && p.Name != "Name" &&//skip this one, it is Writeable in order to support XMLSerialization... p.Name != "Consequence" &&//skip this one because it is dealt with explicitly !p.IsDefined(typeof(HideOnValidationUI), true) ).ToArray(); for (int i = 0; i < _requiredProperties.Length; i++) { var currentRowPanel = new Panel(); currentRowPanel.Bounds = new Rectangle(0, 0, tableLayoutPanel1.Width, rowHeight); currentRowPanel.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; currentRowPanel.Margin = Padding.Empty; tableLayoutPanel1.CellBorderStyle = TableLayoutPanelCellBorderStyle.Inset; tableLayoutPanel1.Controls.Add(currentRowPanel, 0, i + 1); Label lblName = new Label(); lblName.Text = _requiredProperties[i].Name; lblName.AutoSize = true; object currentValue = _requiredProperties[i].GetValue(SecondaryConstriant, null); //Hard Typed properties - Bool if (_requiredProperties[i].PropertyType == typeof(bool)) { CheckBox boolControl = new CheckBox(); boolControl.Text = _requiredProperties[i].Name; boolControl.Tag = i; boolControl.Checked = (bool)currentValue; boolControl.CheckStateChanged += (s, e) => _requiredProperties[(int)boolControl.Tag].SetValue(SecondaryConstriant, boolControl.Checked, null); currentRowPanel.Controls.Add(boolControl); } else if (_requiredProperties[i].PropertyType == typeof(PredictionRule)) //Hard Typed property PredictionRule { //for prediction rules fields ComboBox cbx = new ComboBox(); cbx.Items.AddRange(Validator.GetPredictionExtraTypes()); cbx.Items.Add(""); cbx.DropDownStyle = ComboBoxStyle.DropDownList; cbx.DisplayMember = "Name"; cbx.Tag = i; cbx.SelectedIndexChanged += (s, e) => _requiredProperties[(int)cbx.Tag].SetValue(SecondaryConstriant, cbx.SelectedItem is Type ? Activator.CreateInstance((Type)cbx.SelectedItem) : null); cbx.Width = 200; //The dropdown box is a list of Types but we are actually instantiating a value when user selects it (for XML Serialization). Consequently we must now get the Type for selection purposes if (currentValue != null) { cbx.SelectedItem = currentValue.GetType(); } currentRowPanel.Controls.Add(lblName); cbx.Left = lblName.Right + 5; currentRowPanel.Controls.Add(cbx); } else { //it's a value control (basically anything that can be represented by text (i.e. not a boolean)) Control valueControl; //if it is expects a column then create a dropdown box if (_requiredProperties[i].IsDefined(typeof(ExpectsColumnNameAsInput), true)) { //for column fields ComboBox cbx = new ComboBox(); cbx.Items.AddRange(_otherColumns); cbx.Items.Add(""); cbx.DropDownStyle = ComboBoxStyle.DropDownList; cbx.Tag = i; cbx.SelectedIndexChanged += (s, e) => _requiredProperties[(int)cbx.Tag].SetValue(SecondaryConstriant, UsefulStuff.ChangeType(cbx.SelectedItem, _requiredProperties[(int)cbx.Tag].PropertyType), null); cbx.Width = 350; valueControl = cbx; } else if (typeof(IMapsDirectlyToDatabaseTable).IsAssignableFrom(_requiredProperties[i].PropertyType))//it is a Catalogue type { ComboBox dd = new ComboBox(); dd.Tag = i; dd.Width = 350; dd.AutoCompleteSource = AutoCompleteSource.ListItems; dd.AutoCompleteMode = AutoCompleteMode.Suggest; var entities = _repository.GetAllObjects(_requiredProperties[i].PropertyType).ToArray(); if (!entities.Any()) { if (_requiredProperties[i].PropertyType == typeof(StandardRegex)) { MessageBox.Show("You currently do not have any standard regex concepts in your database. These can be created from the Table(Advanced) collection.", "No StandardRegex configured in your Catalogue"); } else { MessageBox.Show("You currently do not have any " + _requiredProperties[i].PropertyType + " in your database", "Catalogue Entity Collection Empty"); } } else { dd.Items.Add("<<Clear>>"); dd.Items.AddRange(entities); dd.SelectedIndexChanged += (s, e) => _requiredProperties[(int)dd.Tag].SetValue(SecondaryConstriant, dd.SelectedItem as IMapsDirectlyToDatabaseTable, null); } //See if it has a value IRevertable v = _requiredProperties[i].GetValue(SecondaryConstriant, null) as IRevertable; //It has a value, this is a dropdown control right here though so if the revertable state out of date then it means someone else made a change to the database while we were picking columns if (v != null) { v.RevertToDatabaseState(); } valueControl = dd; } else //otherwise create a textbox { //for string fields valueControl = new TextBox(); //if they edit this then write it to the SecondaryConstraint... we can't put i in directly because it goes out of scope so instead we stuff it into Tag and then //get it back at delegate execution time when they change the text. valueControl.Tag = i; valueControl.TextChanged += setTextOrParseableProperty; if (_requiredProperties[i].IsDefined(typeof(ExpectsLotsOfText), true)) { valueControl.Width = 300; } } if (currentValue != null) { valueControl.Text = _requiredProperties[i].GetValue(SecondaryConstriant, null).ToString().Replace("00:00:00", ""); } currentRowPanel.Controls.Add(lblName); valueControl.Left = lblName.Right + 5; currentRowPanel.Controls.Add(valueControl); } var desc = _requiredProperties[i].GetCustomAttribute <DescriptionAttribute>(); if (desc != null) { var lbl = new Label(); lbl.AutoSize = true; lbl.Text = desc.Description; lbl.Font = new Font(lbl.Font, FontStyle.Italic); //make some space for it inflation += lbl.Height - 7; lbl.Top = rowHeight - 7; currentRowPanel.Controls.Add(lbl); currentRowPanel.Height = rowHeight + lbl.Height; } } //first row tableLayoutPanel1.RowStyles[0].SizeType = SizeType.AutoSize; Height = (_requiredProperties.Length * rowHeight) + 35 + inflation; loadingComplete = true; }
/// <summary> /// Returns the contents of this class expressed as the given <paramref name="paramType"/> or null if the current state /// does not describe an object of that Type /// </summary> /// <param name="paramType"></param> /// <returns></returns> public object GetValueForParameterOfType(Type paramType) { if (ExplicitNull) { return(null); } if (typeof(DirectoryInfo) == paramType) { return(new DirectoryInfo(RawValue)); } if (typeof(FileInfo) == paramType) { return(new FileInfo(RawValue)); } if (typeof(string) == paramType) { return(RawValue); } if (typeof(Type) == paramType) { return(Type); } if (typeof(DiscoveredDatabase) == paramType) { return(Database); } if (typeof(DiscoveredTable) == paramType) { return(Table); } var element = paramType.GetElementType(); // If paramType is nullable e.g. 'int?' then this is the underlying time i.e. 'int' otherwise null var nullableType = Nullable.GetUnderlyingType(paramType); //it's an array of DatabaseEntities (IMapsDirectlyToDatabaseTable implements IDeleteable) if (paramType.IsArray && typeof(IDeleteable).IsAssignableFrom(paramType.GetElementType())) { if (DatabaseEntities.Count == 0) { _logger.Warn($"Pattern matched no objects '{RawValue}'"); } if (element != typeof(IDeleteable)) { var typedArray = Array.CreateInstance(element, DatabaseEntities.Count); for (int i = 0; i < DatabaseEntities.Count; i++) { typedArray.SetValue(DatabaseEntities[i], i); } return(typedArray); } return(DatabaseEntities.ToArray()); } if (typeof(IMapsDirectlyToDatabaseTable).IsAssignableFrom(paramType)) { return(GetOneDatabaseEntity <DatabaseEntity>()); } if (typeof(IMightBeDeprecated).IsAssignableFrom(paramType)) { return(GetOneDatabaseEntity <IMightBeDeprecated>()); } if (typeof(IDisableable) == paramType) { return(GetOneDatabaseEntity <IDisableable>()); } if (typeof(INamed) == paramType) { return(GetOneDatabaseEntity <INamed>()); } if (typeof(IDeleteable) == paramType) { return(GetOneDatabaseEntity <IDeleteable>()); } if (typeof(ICheckable) == paramType) { return(GetOneDatabaseEntity <ICheckable>()); } if (typeof(ILoggedActivityRootObject) == paramType) { return(GetOneDatabaseEntity <ILoggedActivityRootObject>()); } if (typeof(ICollectSqlParameters) == paramType) { return(GetOneDatabaseEntity <ICollectSqlParameters>()); } // is it a basic Type (value type or Enum)? var basicType = nullableType ?? paramType; if (basicType.IsValueType && !typeof(Enum).IsAssignableFrom(basicType)) { return(UsefulStuff.ChangeType(RawValue, basicType)); } if (basicType.IsEnum) { return(Enum.Parse(basicType, RawValue, true)); } return(null); }