C# and Windows Forms control naming guidelines - c#

Does anyone have any guidelines/best practices for naming conventions for Forms and controls (e.g., events, buttons)?

I usually use Systems Hungarian notation
Example:
btnSubmit: is button
lblAccountNum : variable is a label

In WinForms I usually use suffixes, so for example:
submitButton
accountNumberLabel
etc.
But a lot of companies still use a prefix, like anthares said.

I don't believe any special rules are needed for forms development; the Microsoft .NET naming guidelines cover it.
I name forms like any other class in the application: MainForm, SaveDialog, etc.
I name controls like any other field within a class: okButton, nameTextBox, etc.

I usually prefix the full class name e.g. textBoxName. I find it easier to read than three letter prefixes and it's consistent with the names that are generated by the IDE. I only name controls that are referred to by code. Controls that are databound usually don't need a name.

The following example is most of the .net programmer is used
Control: Label
Prefix : lbl
Example: lblFirstName

The reason that the prefixes are not the full class names in most of the companies but some abbreviations of the class name are as follows:
Most of the naming conventions are approved before Visual Studio 2010.
All Visual Studio versions before 2010 have their inteli sense filter with something like "starts with" instead of contains.
That's why a lot of people / architects / leaders decided it will be a better idea to type "txt" and inteli sense will filter all textboxes for you, so then you just type "E" for example and you get txtEmail. If you have the full class name, you will need to type "textBoxE" to get the same result in inteli sense. This adds a lot of overheat when you have complex UI.
Now with Visual Studio 2010 you get a better inteli sense so you can just type "em" and you can easilly see the "textBoxEmail" in the list (along with Email and some other things that contain "em"). Still I seem to prefer to have 2-3 or up ot 4 letters abbreviation that will allow me to filter in inteli sense by control type (specially for UI) than having to type textBox. The reason I prefer it is that even if you are puzzled for a while with some control type (e.g. "rg" for RadGrid) you will need 5 minutes 3-4 times to remember it and start typing without thinking about it. While if you have radGrid everywhere you will need to hit 7 strokes to get to the meaningful one that will filter for you (e.g. "radGridC" in "radGridCustomers").
I do agree that only naming controls that are referenced in the code is usually enough.

Related

Visual Studio Templates - custom parameters

I am using VS 2015 templates to create a project for me, within my C# classes I have substitutions like $projectname$ and they work great if I name my project like this - MyTemplatedProject. I use $projectname$ for the part of class names and namespaces.
If I create generate a class like $projectname$Context, it becomes MyTemplatedProjectContext and all is well.
But if I name my project MyTemplatedProject.FrontEnd I have problems with the classes that are generated because they have the . in their name.
The substitution $projectname$Context becomes MyTemplatedProject.FrontEndContext and that does not work for a class name.
How do I create custom parameters based $projectname$, ideally I would have a parameter like $projectnameUpToFirstDot$ which only returns MyTemplatedProject when the project name is MyTemplatedProject.FrontEndContext?
I had exactly the same problem a week ago. I just needed some customed variables inside of my template, which would resolve in $projectname$ upper case and one other in lower case. Things like that.
It turned out for me to be the most effective and flexible way to develop my own project wizard using VS' custom wizard template.
Unless JavaScript & HTML is not a no-go for you, it is pretty easy to have some string manipulation on variables like $projectname$ there.
Once you set it up, go in default.js and edit in function
function onFinish()
{
...
var prjName = wizard.FindSymbol('PROJECT_NAME');
wizard.AddSymbol('PROJECT_NAME_WITHOUT_DOTS', prjName.split('.')[0]);
...
}
split('.') removes all dots and devides it into an array of strings. With [0] you select just the part up to the first dot.
In your template files you can then address the symbol PROJECT_NAME_WITHOUT_DOTS with the following syntax:
class [!output PROJECT_NAME_WITHOUT_DOTS] {
...
}
If you just want to generate a valid class name based on the project name, instead of creating a custom template parameter, you can change $projectname$ to $safeprojectname$, which is documented as:
The name provided by the user in the New Project dialog box, with all unsafe characters and spaces removed.

Control/variable naming conventions in ASP.NET

I think the main distinction in naming is between logic and view-related objects. You might have a variable named “UserName” in the code behind file of a page, but then also a .NET TextBox in which a user is supposed to enter their username (a sensible ID would also be “UserName”). How can we differentiate (ID-wise), between the logic “UserName” and the view “UserName”. My question is, what is a sensible distinction to make when coming up with these names?
In my opinion, a variable name/control ID should never describe what it IS, only what it DOES. “tbUserName” describes that it is a TextBox, “strUserName” defines that it is a string.
One idea would be to prefix all view related objects with “vwUserName” and keep the logic part as “UserName”. Does that make sense? What about when we have a situation where you have validators? Would you name them “vwUserNameRequiredValidator”, or “vwEmailAddressFormatValidator”? In that situation would you need to describe what it actually is? Would you give a .NET RequiredFieldValidator object an ID of “rfvUserName”?
I really want to get an idea of what other people think on this, because I want to come up with a sensible and consistent naming convention system going forward. I’m interesting to hear arguments for any type of system.
Hungarian notation is so 1990s... ;-)
I would use UserName for logic and userName for id.
I tend to use _userName as a variable and UserName as property in code behind, and as ID for a text box UserNameField. I find it easier to work with the intellisense in this way, instead of prefixing as we did in the VB-days with txtUserName.
Edit: not calling it UserNameTextBox, but UserNameField is also easier to work with if you want to the exchange the field (that is TextBox) to another control (it may not apply to this example of username though.
For controls, I always add a prefix like:
Textbox - txtName - I don't use tb because it can be confusing since I use tbl for HtmlTable
Checkbox - cbIsNameRequired
RequiredFieldValidator - rfvName
For variables:
Name
IsNameRequired
etc..
It is all about getting used to a pattern but always have a pattern..

ClassificationTypeDefinition list of BaseDefinitions for Visual Studio 2010

Does anyone know where I can get a list of BaseDefinitions for the ClassificationTypeDefitions in Visual Studio 2010?
I'm trying to define a base definition of "UserTypes" but it doesn't seem to work. For those that don't quite know what I'm talking about and need code to make it easier...
[Export(typeof(ClassificationTypeDefinition))]
[Name("keyword")]
[BaseDefinition("keyword")]
internal static ClassificationTypeDefinition KeywordDefinition = null;
That currently uses the keyword definition of c# for highlighting or what not. But I can't seem to get the one for User types to work (Class/enum/structure names and other similar objects). I've tried using the vs settings file and using the definitions defined in there but the definition "User Types" didn't work.
Thanks, in advance
The PredefinedClassificationTypeNames type has a list of common/shared ones, but "User Types" is an example of one that is supplied by languages.
The short answer is that the [BaseDefinition] should match up with the display name in the Fonts and Colors dialog for language services that haven't moved off the VS2008 interfaces (like C#). If it isn't working when that is the case, you may be able to convince it to work by adding a second classification type definition with that name ("User Types").
The long answer is this:
In order to supply classification type information for these languages, the editor dynamically generates them the first time you open a file that is associated with a language service. The synchronization process is essentially:
Walk through the colorable items provided by the language service (IVsColorableItemsProvider)
If any of the colorable items don't have associated classification types, generate a new classification type for it (using IClassificationTypeRegistryService.CreateClassificationType).
Walk through the information from Fonts and Colors to create/modify formatting information for these classification types
So the problem would be that the type doesn't exist at the time that your classification type definition is picked up by the editor. However, adding a classification type definition for the would-be-dynamically generated type should keep both parts happy: your type's base definition will be set up correctly, and the synchronization process will happily skip step #2, since there is already an item by that name.

ReSharper conventions for names of event handlers

When I add new event handler for any event, VS creates method like object_Click.
But ReSharper underlines this method as Warning, because all methods should not have any delimeters such as "_".
How can I customize rules of ReSharper so that it doesn't underline such methods? Or may be I should rename such methods?
Thanks in advance.
For C# (or VB), make the following change:
ReSharper | Options | Languages | C# | C# Naming Style, Advanced settings...
Change 'Event subscriptions on fields' from $object$_On$event$ to $object$_$event$.
You may also want to add additional rules to entity kinds like 'Types and namespaces' to account for code-generated classes such as 'Default'. For example, add a new rule with a '' Name Prefix and a Name Style 'UpperCamelCase'.
Personally, I'd suggest renaming the methods. Generally I think VS comes up with terrible names for both controls and events.
I prefer to make a method name say what it does, not what calls it. That promotes reuse as well. Admittedly the signature of an event handler is often not ideal for reuse - I'd argue that often a lambda expression calling a method with more sensible parameters would be useful:
button.Click += (sender, args) => SaveCurrentDocument();
but obviously the designer doesn't support that :(
Of course, renaming all the methods is going to be more work than just changing the R# settings, if you can find some that work...
I just created an extension for Visual Studio 2010, EventHandler Naming, that lets you specify with a simple pattern what you want your generated eventhandler names to be. The default pattern in the extension is On$(SiteName)$(EventName) which will give you event names like OnBtnNameClick instead of btnName_Click. You can get the extension at http://tech.einaregilsson.com/2010/12/22/better-eventhandler-names-in-visual-studio-2010/
On your file menu you should have "Resharper" Click it -> Options -> Naming conventions (on left menu).
From there you can specify what naming conventions are used for each of the naming types/styles.

Localization for Winforms from designmode?

I need to bind labels or items in a toolstrip to variables in Design Mode.
I don't use the buit-in resources not the settings, so the section Data is not useful. I am taking the values out from an XML that I map to a class.
I know there are many programs like:
http://www.jollans.com/tiki/tiki-index.php?page=MultilangVsNetQuickTourForms
but they work with compiled resx. I want to use not compiled XML.
I know that programatically i can do it, i create a method (for example, UpdateUI()), and there I assign the new values like this:
this.tsBtn.Text=Class.Texts.tsBtnText;
I would like something i could do from Design Mode or a more optimized way than the current one. Is there any Custom Control out there or Extension?
Aleksandar's response is one way to accomplish this, but in the long run it's going to be very time consuming and won't really provide much benefit. The bigger question that should be asked is why do you not want to use the tools and features built-in to .NET and Visual Studio or at least use a commercial third-party tool? It sounds like you are spending (have spent?) a lot of time to solve a problem that has already been solved.
Try with inheriting basic win controls and override OnPaint method. Example bellow is a button that has his text set on paint depending on value contained in his Tag property (let suppose that you will use Tag property to set the key that will be used to read matching resource). Then you can find some way to read all cache resource strings from xml files (e.g. fictional MyGlobalResources class.
public class LocalizedButton : Button
{
protected override void OnPaint(PaintEventArgs pevent)
{
base.OnPaint(pevent);
this.Text = MyGlobalResources.GetItem(this.Tag.ToString());
}
}
You can use satellite assemblies for localization and generate them using your XML file as a source for the translated entities.
more about satellites http://msdn.microsoft.com/en-us/library/21a15yht(VS.71).aspx
sure it's not from design mode, but there's no way to do it this way with your restrictions.

Categories

Resources