简体   繁体   中英

Dynamic code snippet c# visual studio

I am working on a WinForms project with some repetitive tasks everyday. So I thought creating code a snippet will help me out, but it works for fixed code only.

I want to dynamically create a code snippet, according to control names and some condition.

I want to add the code once the design part is done. I define the control names like intTextboxAge . The snippet should add auto validation for all textboxes, using the fuction defined below.

There have to be different controls based on the control's name prefix (int, str, dou, dec). Like such:

public void AutoCode()
{
    int i=0;
    foreach(On all controls)
    { 
        if(controls is textbox or combobox)
        {
            if(control.text starts with int)
            {
                a[i] = Validation.ValidateInt(labelError, control.text, val => acdnt.date = val);
            }
        }
    }
}

I want an auto generated code snippet, libraries will not be able to help me.

My motive is not to generate code for validation only by above example is just how we can do this.

I want to auto generate my all business logic code for master win forms like

  1. Validation
  2. Creating new Class for variables
  3. Datafilling in class after validation
  4. Auto creation of database function insert and update

Because in all above task only variable name changes rest business task remains same. How we can implement

Auto Creation of class- Class will created with by form name+"Class" and variable types will identified by first 3 char and will named same as control name.

Auto creation of database function insert and update - Will name database table name same as form name and column name same as control name, so that it can dynamically create insert and update query also.

Why i don't want to with class library because in that case it perform all operation at run time which will somewhere eat my performance.

With this we can save lots of time and efforts of coding world.

I want to add the code once the design part is done. I define the control names like intTextboxAge. The snippet should add auto validation for all textboxes, using the function defined below.

It would be better to have CustomControls with their own Validation, this way you don't need to add code after the design part is done:

在此输入图像描述

//Integer input CustomControl with validation label (pictured above)
public partial class intTextBox : UserControl
{
    public bool IsValid {get;set;}
    public intTextBox()
    {
        InitializeComponent();
        this.textBox1.TextChanged += this.intTextBox_TextChanged;
    }

    private void intTextBox_TextChanged(object sender, EventArgs e)
    {
        int n;
        IsValid = int.TryParse(this.textBox1.Text, out n);
        label1.Visible = !IsValid;
    }
}

There have to be different controls based on the control's name prefix (int, str, dou, dec)

While you can use control name prefix's I recommend creating your own UserControls by deriving off base controls and simply testing the control type:

//Decimal input UserControl
public class decTextBox : TextBox
{
    public string Text
    {
        get {
            return this.Text;
        }
    }

    public bool IsValid()
    {
        decimal n;
        bool isDecimal = decimal.TryParse(this.Text, out n);
        return isDecimal;
    }
}

....

public Control AutoCode(Control forEgTheForm)
{
    //Tip: You may need to recursively call this function to check children controls are valid
    foreach(var ctrl in forEgTheForm.Controls) { 
        if(ctrl is TextBoxBase) {
             if(ctrl is decTextBox) {
                 decTextBox txt = ((decTextBox)ctrl);
                 //If its not a valid value then set a[i]=true/false or in this example return the control...
                 if (!txt.IsValid()) return ctrl;
             }
        }
    }
}

I want to dynamically create a code snippet, according to control names and some condition.

If you're going to create code Snippets do it according to control types, not Control name prefix's so you dont need them to be dynamic.

...


It would be even more elegant not to have to write any Snippets or validation code. This is the ideal solution. I recommend doing this by using the right type of controls.

Textboxes are good for string, however for int's, dec's and dbl's you're better off using the NumericUpDown control. This way users will intuitively know they need to enter numbers (and wont be able to enter alphanumeric characters). After setting a couple of NumericUpDown control properties (either at design time or run time) you wont need to code in validation:

在此输入图像描述


I'm not sure about the cause of the performance degradation you're encountering? Though I suggest you bind controls to a class in a class library with all the business logic so that you can Unit Test. For the front-end validation though simply validating inputs are correct as shown above is the way to go.

You can try code generators based on scripts like CodeSmith (there is also something free).
You can write your script based on variables you define (also based on database items) then generate the code.
Generating code is a good approach becouse saves time but also standardize the code.

I think you can use the System.Reflection namespace combined with the System.CodeDom namespace to achieve what you want.

You can use the classes in the System.Reflection namespace and the System.Type class to discover the assembly name, the namespace, the properties, the methods, the base class, and plenty of other metadata about a class or variable. You'll then use these metadata aquired from your starting/source classes (eg.your Form Classes) to generate code of your target classes (your business and data classes) using CodeDOM.

Check this msdn link on How to: Create a Class using CodeDOM as a starting point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM