Dynamic code snippet c# visual studio
Asked Answered
G

3

12

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.

Galoot answered 8/6, 2015 at 4:27 Comment(10)
A specific example would help us to provide you a suggestion. Do you mean before the code snippet is inserted, your prompted for the dynamic values?Corey
Maybe you could look at tools like CodeRush or Resharper. They come with sophisticated template engines, they might work ( I am not associated with any of those tools )Defective
Rather than working out a code snippet, why not build up a library of appropriate methods? It would be far better to have this code once and then call it from multiple places than have the whole code in multiple places.Pyrrhonism
@JonSkeet as above code will contain lots of if condition's to generate code snippet. I need to check all the condition's every time i run code, which performance issue.Galoot
@Defective i need to go with open source which can modify according to my needsGaloot
Have you verified that there really is a performance issue, or are you guessing? Its not really clear what can be moved to compile-time...Pyrrhonism
@JonSkeet let me explain suppose i need to call function for validation of textbox for integer, which is hardcoded and i don't need to check for any if condition. If i go with class library i always need to check whether its for int or string.Galoot
@HotCoolStud As for performance, you could call the correct methods in the event handlers or use extension methods for each control type ( value type ).Defective
@HotCoolStud: So you'd have two methods - you don't have to write one method which performs every validation known to humankind.Pyrrhonism
For the Auto creation of database function insert and update part, is Entity Framework eligible ?Crosley
E
7

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:

enter image description here

//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:

enter image description here


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.

Excellency answered 11/6, 2015 at 11:22 Comment(3)
Happy to chat about this answer. I know it is not what you're asking for dynamic snippets but it was too long for a comment and proposes not needing to write snippets... CheersExcellency
I checked your update and think this QA is turning into a chameleon question. What did you think about my advice aiming for an OOP, DRY, SOLID approach?Excellency
sorry for less detailed question earlier .Galoot
H
1

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.

Hydroquinone answered 17/6, 2015 at 8:27 Comment(0)
C
1

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.

Crosley answered 17/6, 2015 at 12:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.