Server/FormEditObject.cs
author StephaneLenclud
Tue, 16 Aug 2016 12:59:32 +0200
changeset 235 ba14a29944c4
child 236 6ba20e02d04f
permissions -rw-r--r--
Removing JSON type converter from ear manager.
Using bindings for some application settings.
     1 using System;
     2 using System.Collections.Generic;
     3 using System.ComponentModel;
     4 using System.Data;
     5 using System.Diagnostics;
     6 using System.Drawing;
     7 using System.Linq;
     8 using System.Text;
     9 using System.Threading.Tasks;
    10 using System.Windows.Forms;
    11 using SharpLib.Display;
    12 using SharpLib.Ear;
    13 using System.Reflection;
    14 using Microsoft.VisualBasic.CompilerServices;
    15 using SharpLib.Utils;
    16 
    17 namespace SharpDisplayManager
    18 {
    19     /// <summary>
    20     /// Object edit dialog form.
    21     /// </summary>
    22     public partial class FormEditObject<T> : Form where T : class
    23     {
    24         public T Object = null;
    25 
    26         public FormEditObject()
    27         {
    28             InitializeComponent();
    29         }
    30 
    31         /// <summary>
    32         /// 
    33         /// </summary>
    34         /// <param name="sender"></param>
    35         /// <param name="e"></param>
    36         private void FormEditAction_Load(object sender, EventArgs e)
    37         {
    38             // Populate registered actions
    39             IEnumerable < Type > types = Reflection.GetConcreteClassesDerivedFrom<T>();
    40             foreach (Type type in types)
    41             {
    42                 ItemObjectType item = new ItemObjectType(type);
    43                 comboBoxActionType.Items.Add(item);
    44             }
    45 
    46             if (Object == null)
    47             {
    48                 // Creating new issue, select our first item
    49                 comboBoxActionType.SelectedIndex = 0;
    50             }
    51             else
    52             {
    53                 // Editing existing object
    54                 // Look up our item in our combobox 
    55                 foreach (ItemObjectType item in comboBoxActionType.Items)
    56                 {
    57                     if (item.Type == Object.GetType())
    58                     {
    59                         comboBoxActionType.SelectedItem = item;
    60                     }
    61                 }
    62             }            
    63         }
    64 
    65         private void buttonOk_Click(object sender, EventArgs e)
    66         {
    67             FetchPropertiesValue(Object);
    68         }
    69 
    70         private void FormEditAction_Validating(object sender, CancelEventArgs e)
    71         {
    72 
    73         }
    74 
    75         private void comboBoxActionType_SelectedIndexChanged(object sender, EventArgs e)
    76         {
    77             //Instantiate an action corresponding to our type
    78             Type actionType = ((ItemObjectType) comboBoxActionType.SelectedItem).Type;
    79             //Create another type of action only if needed
    80             if (Object == null || Object.GetType() != actionType)
    81             {
    82                 Object = (T)Activator.CreateInstance(actionType);
    83             }
    84             
    85             //Create input fields
    86             UpdateTableLayoutPanel(Object);
    87         }
    88 
    89 
    90         /// <summary>
    91         /// Get properties values from our generated input fields
    92         /// </summary>
    93         private void FetchPropertiesValue(T aAction)
    94         {
    95             int ctrlIndex = 0;
    96             foreach (PropertyInfo pi in aAction.GetType().GetProperties())
    97             {
    98                 AttributeObjectProperty[] attributes =
    99                     ((AttributeObjectProperty[]) pi.GetCustomAttributes(typeof(AttributeObjectProperty), true));
   100                 if (attributes.Length != 1)
   101                 {
   102                     continue;
   103                 }
   104 
   105                 AttributeObjectProperty attribute = attributes[0];
   106 
   107                 if (!IsPropertyTypeSupported(pi))
   108                 {
   109                     continue;
   110                 }
   111 
   112                 GetPropertyValueFromControl(iTableLayoutPanel.Controls[ctrlIndex+1], pi, aAction); //+1 otherwise we get the label
   113 
   114                 ctrlIndex+=2; //Jump over the label too
   115             }
   116         }
   117 
   118         /// <summary>
   119         /// Extend this function to support reading new types of properties.
   120         /// </summary>
   121         /// <param name="aAction"></param>
   122         private void GetPropertyValueFromControl(Control aControl, PropertyInfo aInfo, T aAction)
   123         {
   124             if (aInfo.PropertyType == typeof(int))
   125             {
   126                 NumericUpDown ctrl=(NumericUpDown)aControl;
   127                 aInfo.SetValue(aAction,(int)ctrl.Value);
   128             }
   129             else if (aInfo.PropertyType.IsEnum)
   130             {
   131                 // Instantiate our enum
   132                 object enumValue= Activator.CreateInstance(aInfo.PropertyType);
   133                 // Parse our enum from combo box
   134                 enumValue = Enum.Parse(aInfo.PropertyType,((ComboBox)aControl).SelectedItem.ToString());
   135                 //enumValue = ((ComboBox)aControl).SelectedValue;
   136                 // Set enum value
   137                 aInfo.SetValue(aAction, enumValue);
   138             }
   139             else if (aInfo.PropertyType == typeof(bool))
   140             {
   141                 CheckBox ctrl = (CheckBox)aControl;
   142                 aInfo.SetValue(aAction, ctrl.Checked);
   143             }
   144             else if (aInfo.PropertyType == typeof(string))
   145             {
   146                 TextBox ctrl = (TextBox)aControl;
   147                 aInfo.SetValue(aAction, ctrl.Text);
   148             }
   149             //TODO: add support for other types here
   150         }
   151 
   152         /// <summary>
   153         /// 
   154         /// </summary>
   155         /// <param name="aInfo"></param>
   156         /// <param name="action"></param>
   157         private Control CreateControlForProperty(PropertyInfo aInfo, AttributeObjectProperty aAttribute, T aAction)
   158         {
   159             if (aInfo.PropertyType == typeof(int))
   160             {
   161                 //Integer properties are using numeric editor
   162                 NumericUpDown ctrl = new NumericUpDown();
   163                 ctrl.AutoSize = true;
   164                 ctrl.Minimum = Int32.Parse(aAttribute.Minimum);
   165                 ctrl.Maximum = Int32.Parse(aAttribute.Maximum);
   166                 ctrl.Increment = Int32.Parse(aAttribute.Increment);
   167                 ctrl.Value = (int)aInfo.GetValue(aAction);
   168                 return ctrl;
   169             }
   170             else if (aInfo.PropertyType.IsEnum)
   171             {
   172                 //Enum properties are using combo box
   173                 ComboBox ctrl = new ComboBox();
   174                 ctrl.AutoSize = true;                
   175                 ctrl.Sorted = true;                
   176                 ctrl.DropDownStyle = ComboBoxStyle.DropDownList;
   177                 //Data source is fine but it gives us duplicate entries for duplicated enum values
   178                 //ctrl.DataSource = Enum.GetValues(aInfo.PropertyType);
   179 
   180                 //Therefore we need to explicitly create our items
   181                 Size cbSize = new Size(0,0);
   182                 foreach (string name in aInfo.PropertyType.GetEnumNames())
   183                 {
   184                     ctrl.Items.Add(name.ToString());
   185                     Graphics g = this.CreateGraphics();
   186                     //Since combobox autosize would not work we need to get measure text ourselves
   187                     SizeF size=g.MeasureString(name.ToString(), ctrl.Font);
   188                     cbSize.Width = Math.Max(cbSize.Width,(int)size.Width);
   189                     cbSize.Height = Math.Max(cbSize.Height, (int)size.Height);
   190                 }
   191 
   192                 //Make sure our combobox is large enough
   193                 ctrl.MinimumSize = cbSize;
   194 
   195                 // Instantiate our enum
   196                 object enumValue = Activator.CreateInstance(aInfo.PropertyType);
   197                 enumValue = aInfo.GetValue(aAction);
   198                 //Set the current item
   199                 ctrl.SelectedItem = enumValue.ToString();
   200 
   201                 return ctrl;
   202             }
   203             else if (aInfo.PropertyType == typeof(bool))
   204             {
   205                 CheckBox ctrl = new CheckBox();
   206                 ctrl.AutoSize = true;
   207                 ctrl.Text = aAttribute.Description;
   208                 ctrl.Checked = (bool)aInfo.GetValue(aAction);                
   209                 return ctrl;
   210             }
   211             else if (aInfo.PropertyType == typeof(string))
   212             {
   213                 TextBox ctrl = new TextBox();
   214                 ctrl.AutoSize = true;
   215                 ctrl.Text = (string)aInfo.GetValue(aAction);
   216                 return ctrl;
   217             }
   218             //TODO: add support for other control type here
   219 
   220             return null;
   221         }
   222 
   223         /// <summary>
   224         /// Don't forget to extend that one and adding types
   225         /// </summary>
   226         /// <returns></returns>
   227         private bool IsPropertyTypeSupported(PropertyInfo aInfo)
   228         {
   229             if (aInfo.PropertyType == typeof(int))
   230             {
   231                 return true;
   232             }
   233             else if (aInfo.PropertyType.IsEnum)
   234             {
   235                 return true;
   236             }
   237             else if (aInfo.PropertyType == typeof(bool))
   238             {
   239                 return true;
   240             }
   241             else if (aInfo.PropertyType == typeof(string))
   242             {
   243                 return true;
   244             }
   245             //TODO: add support for other type here
   246 
   247             return false;
   248         }
   249 
   250         /// <summary>
   251         /// Update our table layout.
   252         /// Will instantiated every field control as defined by our action.
   253         /// Fields must be specified by rows from the left.
   254         /// </summary>
   255         /// <param name="aLayout"></param>
   256         private void UpdateTableLayoutPanel(T aAction)
   257         {
   258             toolTip.RemoveAll();
   259             //Debug.Print("UpdateTableLayoutPanel")
   260             //First clean our current panel
   261             iTableLayoutPanel.Controls.Clear();
   262             iTableLayoutPanel.RowStyles.Clear();
   263             iTableLayoutPanel.ColumnStyles.Clear();
   264             iTableLayoutPanel.RowCount = 0;
   265 
   266             //We always want two columns: one for label and one for the field
   267             iTableLayoutPanel.ColumnCount = 2;
   268             iTableLayoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
   269             iTableLayoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
   270 
   271 
   272             if (aAction == null)
   273             {
   274                 //Just drop it
   275                 return;
   276             }
   277             
   278             //IEnumerable<PropertyInfo> properties = aAction.GetType().GetProperties().Where(
   279             //    prop => Attribute.IsDefined(prop, typeof(AttributeObjectProperty)));
   280 
   281 
   282             foreach (PropertyInfo pi in aAction.GetType().GetProperties())
   283             {
   284                 AttributeObjectProperty[] attributes = ((AttributeObjectProperty[])pi.GetCustomAttributes(typeof(AttributeObjectProperty), true));
   285                 if (attributes.Length != 1)
   286                 {
   287                     continue;
   288                 }
   289 
   290                 AttributeObjectProperty attribute = attributes[0];
   291 
   292                 //Before anything we need to check if that kind of property is supported by our UI
   293                 //Create the editor
   294                 Control ctrl = CreateControlForProperty(pi, attribute, aAction);
   295                 if (ctrl == null)
   296                 {
   297                     //Property type not supported
   298                     continue;
   299                 }
   300 
   301                 //Add a new row
   302                 iTableLayoutPanel.RowCount++;
   303                 iTableLayoutPanel.RowStyles.Add(new RowStyle(SizeType.AutoSize));
   304                 //Create the label
   305                 Label label = new Label();
   306                 label.AutoSize = true;
   307                 label.Dock = DockStyle.Fill;
   308                 label.TextAlign = ContentAlignment.MiddleCenter;
   309                 label.Text = attribute.Name;
   310                 toolTip.SetToolTip(label, attribute.Description);
   311                 iTableLayoutPanel.Controls.Add(label, 0, iTableLayoutPanel.RowCount-1);
   312 
   313                 //Add our editor to our form
   314                 iTableLayoutPanel.Controls.Add(ctrl, 1, iTableLayoutPanel.RowCount - 1);
   315                 //Add tooltip to editor too
   316                 toolTip.SetToolTip(ctrl, attribute.Description);
   317 
   318             }        
   319 
   320         }
   321 
   322         private void buttonTest_Click(object sender, EventArgs e)
   323         {
   324             FetchPropertiesValue(Object);
   325 
   326             //If our object has a test method with no parameters just run it then
   327             MethodInfo info = Object.GetType().GetMethod("Test");
   328             if ( info != null && info.GetParameters().Length==0)
   329             {
   330                 info.Invoke(Object,null);
   331             }
   332 
   333         }
   334     }
   335 }