Change default access modifier for controls created in UI designer - c#

I'm creating winforms using visual inheritance. In order to be able to manipulate inherited UI controls in child classes I need to set the controls in the base classes to protected accessibility instead of private. I can do this manually, but would like to be able to change the default behavior for the solution I'm working on. Is this possible>

Please go to properties and then modifiers change private to protected.
This image hopefully help you.
properties->modifiers->protectes

Working with WinForms for a couple of years, but without knowing everything that is possible (who can?), what you want to achieve is not possible. You'll have to do it manually. For my own purpose, how would you want it to be feasible? Which kind of options are you expecting that will help you achieve your goal that is really application specifics. Do you want the possibility to set all the controls on a form with protected access modifier? If it is the case, I think that we should discuss more about design. If not, then you'll have to set them manually.

Related

Knowing when in design mode

From within a class library, I'd like to know if it is being accessed during design mode as opposed to normal runtime.
I tried using System.ComponentModel.LicenseManager.UsageMode but it seemed to have a value of Runtime even when I was editing a form.
UPDATE:
To clarify, I want to know if I am in design mode not from within a component, but rather from within a separate class that happens to be called by other items from within a form or control. I have a Utility class which is being called indirectly from a control and it is there that I need to know if I am in design mode or not.
I don't think Component.DesignMode will help in this case. What if the component or control is not loaded on the forms designer ? What you may try in this case is, create an enum that only sets the one value at normal startup which otherwise remains to another value by default. You can now check the value of the enum instance and decide if it's a design-time or runtime.
You can use Component.DesignMode to check this. However, be aware that this will always report false inside the constructor of the component, so it needs to be checked later. For details, see Debugging Design-Time Controls.
Edit in response to comments and edit:
Unfortunately, the LicenseMananger, as well as most other services which provide information about whether you're in Design Time (including Component.DesignMode and DesignerProperties.IsInDesignMode) as specifically geared at handling user interface elements. This makes sense, as they're intended to tell you when your item is being "designed" on a designer surface, which requires the component to be registered in the designer.
There is no single property that will cleanly tell you this from within an arbitrary class.
I could see two options, both of which are less than ideal:
Pass the required information into your class (ie: a Component or DependencyObject), so the methods above can be used to check for design-time access correctly. This is probably a more maintainable approach, and will likely work properly in more situations.
Resort to the "hack" of checking the current process name and looking for "devenv" - this is pretty awful, as it assumes Visual Studio only, relies on the executable name, etc... In general, I'll mention it because you'll find it with enough searching, but wouldn't recommend it, as it's very easy to circumvent and has many limitations and flaws.
Is it not possible to use Component.DesignMode property?
Here's some info on applying attributes in order to get design-time specific behavior: http://msdn.microsoft.com/en-us/library/37899azc.aspx

accessing Winform`s private UI Component into another class in C#

I have WinForm which is a tab based and including all Tabs it has around 60 UI Components. Depending upon value selected in some UI Components i am Auto filling rest of the UI components.For this i would like to write a helper class.But the problem is if i pass Winform object to that class i am not able to access values on that Form because all the member are declared private.
one possible solution is that I can write around 60 properties in the Winform but i think this is not the best way to do it. I would like to know what is the best way to handle problem like these ?
You could change the Modifiers for your UI components from private to internal. This would allow all classes within the same project to directly access the components.
However, I would argue that exposing the necessary components through properties is a better design than exposing them publically/internally. I acknowledge that it includes a fair amount of typing, but it's safer as you can expose them cleanly, in a manner specific to your use case.
That being said - there are a couple of things I would consider:
Can this be refactored into a smaller class, using fewer components by using UserControls? This might make it more managable, as well as promote reuse. 60 UI elements is a fair amount for a single screen.
Can you refactor this to pass the data, instead of trying to work with the controls directly? For example, you could auto-fill the data via a shared interface, and data bind the controls to the data, or something similar.
You can declare the members of a WinForm as public protected, protected internal, and internal. You can do this either in the properties window for a specific component (go to the Modifiers property) or you can change them in the Designer of the form (they are declared after the "Windows Form Designer generated code").
If you don't want to make the members public, nor make a property or method to get that information, then all you're left with is attempting to get the value via reflection, which is perhaps the worst option of all three.
Your best solution would be to make properties for each of those private members and expose them that way.
One way to approach this is to create a class that contains all of the data that you want to bind to (e.g. a class that implements INotifyPropertyChanged).
Then share this instance between the WinForm and the other class. Voila!

What is the best way to do validations in windows forms

What is the best way to do validation in a windows forms application?
What is the easiest way?
What is the most attractive (to the end user) way?
Regards,
-Kushan-
Concerning UI validation, I have a set of control validators, and I just plug 'em in where I need them by assigning their control. You can show errors using ErrorProvider, all you need is encapsulated framework to automate things.
First there is the ValidatorBase class. Make it abstract and inherit the Component class so you can have design time support. Store a private instance of ErrorProvider here, and use something like Template Method pattern (create a Validate method, which in turn calls the protected abstract DoValidation method). In concrete implementations of the base class just override the DoValidation and put your logic here. You can have EmptyValidator (check if control's value isn't empty), RegexValidator (check controls value with some reg. expression), GroupValidator (do Validate on every ValidatorBase instance in some list), whatever you want.
In the base class, you can add things like design-time support for properties (the error message, icon, control to validate etc...)
EDIT1: Now, concerning validation other then in the UI, that is the domain of your business layer, and your rules. There are frameworks / patterns for those things too, but I think you are asking about the UI validation.
EDIT2: ASP.NET has a set of similar validators built-in, although with more functionalities (client side validation, etc...), but to be honest, I don't like them that much.
EDIT3: also check:
Is there any validation control available in .net win forms like asp.net web form?
One interface you might consider looking at is IDataErrorInfo along with the ErrorProvider class. I've got an old blog post that provides a list of the DataBinding classes and interfaces that might help: Data Binding Classes, Interfaces, and Attributes in Windows Forms 2.0.

WinForms: automating common chores

When adding a control to my form, currently I have to wire it up with my save and load code, with my internal data structures and I have to do this with all my controls. This scenario severely violates the DRY (don't repeat yourself) principle and can introduce subtle bugs.
I have came up with the idea of traversing all the Controls in a foreach loop, the Name property will be the key and the Text (or whatever depending on the type) will be the value in a dictionary (filtering for user input controls during the procedure). This way I will have to serialize/deserialize the dictionary to save/load it.
So, why am I asking? I am a beginner and I think there are more proven and tested methods for accomplishing the same task then what I came up with.
And sorry for my clunky English, I have not had the fortune to learn it as my first language.
Thanks for your help
note: I know about WPF, but I have to stick to .net 2.0
There are already good examples for doing that, see RealPosition. We modified this source to do form/control position saving in our project by just placing a component on the form in the designer and specifying the necessary properties there. Look at the IExtenderProvider and ISupportInitialize interfaces on MSDN too.
Ideally you want all the controls to inherit from a base class, the base class can then deal with all of this when each control is initialised. If you need the dictionary then pass the dictionary into a method, the method can then set all the various properties required on the control.
If each control inherits, then the logic is shared and DRY :)

Should I use internal or public visibility by default?

I'm a pretty new C# and .NET developer. I recently created an MMC snapin using C# and was gratified by how easy it was to do, especially after hearing a lot of horror stories by some other developers in my organisation about how hard it is to do in C++.
I pretty much went through the whole project at some point and made every instance of the "public" keyword to "internal", except as required by the runtime in order to run the snapin. What is your feeling on this, should you generally make classes and methods public or internal?
I believe in blackboxes where possible. As a programmer, I want a well defined blackbox which I can easily drop into my systems, and have it work. I give it values, call the appropriate methods, and then get my results back out of it.
To that end, give me only the functionality that the class needs to expose to work.
Consider an elevator. To get it to go to a floor, I push a button. That's the public interface to the black box which activates all the functions needed to get the elevator to the desired floor.
What you did is exactly what you should do; give your classes the most minimal visibility you can. Heck, if you want to really go whole hog, you can make everything internal (at most) and use the InternalsVisibleTo attribute, so that you can separate your functionality but still not expose it to the unknown outside world.
The only reason to make things public is that you're packaging your project in several DLLs and/or EXEs and (for whatever reason) you don't care to use InternalsVisibleTo, or you're creating a library for use by third parties. But even in a library for use by third parties, you should try to reduce the "surface area" wherever possible; the more classes you have available, the more confusing your library will be.
In C#, one good way to ensure you're using the minimum visibility possible is to leave off the visibility modifiers until you need them. Everything in C# defaults to the least visibility possible: internal for classes, and private for class members and inner classes.
I think you should err on the side of internal classes and members. You can always increase an item's visibility but decreasing it can cause problems. This is especially true if you are building a framework for others.
You do need to be careful though not to hide useful functionality from your users. There are many useful methods in the .NET BCL that cannot be used without resorting to reflection. However, by hiding these methods, the surface area of what has to be tested and maintained is reduced.
I prefer to avoid marking classes as public unless I explicitly want my customer to consume them, and I am prepared to support them.
Instead of marking a class as internal, I leave the accessibility blank. This way, public stands out to the eye as something notable. (The exception, of course, is nested classes, which have to be marked if they are to be visible even in the same assembly.)
Most classes should be internal, but most non-private members should be public.
The question you should ask about a member is "if the class were made public would I want to member the member to be exposed?". The answer is usually "yes (so public)" because classes without any accessible members are not much use!
internal members do have a role; they are 'back-door access' meant only for close relatives that live in the same assembly.
Even if your class remains internal, it is nice to see which are front-door members and which are back-door. And if you ever change it to public you are not going to have to go back and think about which are which.
Is there any reason you need to use Internal instead of Private? You do realise that Internal has assembly level scope. In other words Internal classes/members are accessible to all classes in a multi-class assembly.
As some other answers have said, in general go for the highest level of encapsulation as possible (ie private) unless you actually need internal/protected/public.
I found a problem using internal classes as much as possible. You cannot have methods, properties, fields, etc of that type (or parameter type or return type) more visible than internal. This leads to have constructors that are internal, as well as properties. This shouldn't be a problem, but as a matter of fact, when using Visual Studio and the xaml designer, there are problems. False positive errors are detected by the designer due to the fact that the methods are not public, user control properties seems not visible to the designer. I don't know if others have already fallen on such issues...
You should try to make them only as visible as possible, but as stated by Mike above, this causes problems with UserControls and using the VS Designer with those controls on forms or other UserControls.
So as a general rule, keep all classes and UserControls that you aren't adding using the Designer only as visible as they need to be. But if you are creating a UserControl that you want to use in the Designer (even if that's within the same assembly), you will need to make sure that the UserControl class, its default constructor, and any properties and events, are made public for the designer to work with it.
I had a problem recently where the designer would keep removing the this.myControl = new MyControl() line from the InitializeComponent() method because the UserControl MyControl was marked as internal along with its constructor.
It's really a bug I think because even if they are marked as internal they still show up in the Toolbox to add in the Designer, either Microsoft needs to only show public controls with public constructors, or they need to make it work with internal controls as well.
You should tend toward exposing as little as possible to other classes, and think carefully about what you do expose and why.
It depends on how much control you have over code that consumes it. In my Java development, I make all my stuff public final by default because getters are annoying. However, I also have the luxury of being able to change anything in my codebase whenever I want. In the past, when I've had to release code to consumers, I've always used private variables and getters.
I like to expose things as little as possible. Private, protected, internal, public: give classes, variables, properties, and functions the least amount of visibility they need for everything to still work.
I'll bump something's visibility up that chain toward public only when there's a good reason to.
I completely disagree with the answers so far. I feel that internal is a horrid idea, preventing another assembly from inheriting your types, or even using your internal types should the need for a workaround come about.
Today, I had to use reflection in order to get to the internals of a System.Data.DataTable (I have to build a datatable lightning fast, without all of its checks), and I had to use reflection, since not a single type was available to me; they were all marked as internal.
by default class is created as internal in c#:
internal means: Access is limited to the current assembly.
see
http://msdn.microsoft.com/en-us/library/0b0thckt.aspx
Good Article the defaults scope is internal:
http://www.c-sharpcorner.com/UploadFile/84c85b/default-scope-of-a-C-Sharp-class/
Do not choose a "default". Pick what best fits the visibility needs for that particular class. When you choose a new class in Visual Studio, the template is created as:
class Class1
{
}
Which is private (since no scope is specified). It is up to you to specify scope for the class (or leave as private). There should be a reason to expose the class.

Categories

Resources