I have a question about when to validate inputs on C# form applications.
When taking inputs from a form application, you can run all the validation as you parse in the data from the text fields in the main form class, to then use wherever. For example:
Method 1:
class Car
{
private string registration { set; get; } // NO VALIDATION HERE
}
// in the form class
private void add_Click(object sender, EventArgs e)
{
// get registration
int reg_valid = Validate.registration(txtReg.Text); // VALIDATION IS DONE HERE
if(reg_valid)
{
Car.registration = txtReg.Text;
} else {
// Registration invalid - throw error
}
}
There will be no validation in the actual Car object as it is all done in the form class.
The other way is to validate the input in the actual class it is stored in like:
Method 2:
class Car
{
// out registration
private string registration;
// we can set our registration here and return false if there is an error
bool set_registration(registration)
{
int reg_valid = Validate.registration(registration); // VALIDATION IS DONE HERE
if(reg_valid) {
this.registration = registration;
} else {
return false; // if error
}
return true; // if all goes well
}
}
// in the form class
private void add_Click(object sender, EventArgs e)
{
// get registration
string registration = txtReg.Text; // NO VALIDATION DONE HERE
// we can then store this in our object
if( ! Car.set_registration(registration))
{
// Registration invalid - throw error
}
}
Method 1 seems cleaner, but one of the reasons why we use private attributes is so that we can validate any parsing arguments which is why method 2 seems the better option. Also, using method 2, errors have to be carried up the stack possibly many times, which leads to repeated if statements.
* Please note, this code has not been ran so may contain errors.
Caution : Opinion-based answer !
It depends on the requirements of the Project, its scale, and the time you have (and many other factors of importance like "User Friendly Application" or of no importance like "my own taste would be..")
Due to the wide range of possible cases per individual, the answer cannot be expressed in a general guideline which would fulfill the needs of everyone.
Your question addressed two objects to manipulate :
one Form used as an User Interface where the user can input anything (assumption defined by "the user enter *any* value then click a Button")
a Class Property that is fed with the value (Setter) when it's valid.
You have no time, requirements just tells "Input a value", this is a small task in the Project of no critical importance on a small class used within this Button, and you're very lazy :
=> In Button Click, make a rigid validation with one or two forbidden checks that whip out any non allowed value, and shows a MessageBox depending on the nature of the Error. Only pass a Value to the class and go further when you have a valid value.
.
You have no time, simple requirements, small task of no critical importance but with a class largely used, but you're lazy :
=> Move the validation above in the class then Throw one, two or three generic Exceptions with custom messages. In any UI action using that class, use Try/Catch to capture the exception in the ButtonClick and display a MessageBox without going further in case of captured Exception.
.
You have 5 minutes, simple requirements, small non critical task, important Class role :
=> Like previously but, decide whether another way to show user is more recommended (depending of your target users) like changing the background color of a TextBox after you click a button, displaying the message in a Label, instead of annoying the user with a dialog box...
.
You have 10 minutes, simple requirements, repetitive task, important Class role :
=> Find a way to quickly test a given value and creates a public or friend (static ?) function in your Class that returns the result of a validation attempt, like an UICarValidationEnum Enumeration (* see Edit below) of possible Validation Errors :
a) UICarValidationEnum.Valid
b) .TooLong
c) .NullValue
d) .ForbiddenChars
e) ...
You can then use that validation Function inside and outside your Class. That way, you can handle invalid Setter attempts both before performing the Setter and while performing it, aswell as both using you class along with UI and without. The drawback is you can't avoid double validation if you check if the data is valid outside the class (In your Button for eg.)
.
Time matters, but requirements is efficient inputs, repetitive task of great importance, class largely used - you can't be lazy :
=> Handle both UI Validation and Class Validation. Why ? The UI Part addresses the "efficient inputs" part, and the Class Part addresses the "role of the Class". You can use the Validator Function above, or implement much more Exceptions upon Setter like in the other cases above. You're increasing the number of handled Exceptions/Invalid inputs by providing much more information to the user upon Button Click.
Remember : Class largely used. The move here is to implement the maximum coding to handle different cases of invalid inputs, to reduce the amount of code to write elsewhere in your project while still be able to handle all those cases.
.
Time matters, User Friendly Application, repetitive task, important Class :
=> Reconsider the UI Layout and behaviour, validation is mainly UI, but Class is still doing it by itself :
a) User hates Dialog Boxes (whatever DialogBox, message, openfile, etc.. avoid them whenever possible)
b) User hates aggressive colors
c) User hates validation
d) ...... User hates a lot of things..!
The role of the Function Validation above is of importance here : Capture the User Input actions. If it's a TextBox for example, capture the TextChanged Event, then call the Class validation Function. Update information in a Label notifying any encountered error, and change the background color of the TextBox to a friendly color, but related to an error standard, like light Pink. Don't use Color.Red, that's too agressive for most users. Seeing Red 200 times a day can lead to unexpected behaviours at the end of the day.
Only enable the Button when ALL Inputs are valid. Don't make a button per input, User hates endless validations.
.
Time doesn't really matter, User Friendly Application, repetitive task, important Class :
=> Along with the previous option, improve UI response.
Add graphic icons in your label, and/or consider the use of an ErrorProvider in your Form. Users like simple icons rather than long similar messages.
Consider the use friendly sounds to notify poping errors (not everyone is "kind of visual receptive")
.
Time doesn't matter at all, User Friendly Application, repetitive task, important Class :
=> Keep capturing user inputs live, but implement suggestive corrections related to. If it's a TextBox, use AutoCompleteCollection with predefined and fixed Inputs suggestions in the collection when user attempts to input invalid Datas (you'll need a Function for that).
Live disable other inputs when they are incompatible with user's choices/actions.
.
Time really matters, User Friendly recommended, repetitive task, important Class :
=> Don't overload your Form with validations routines.
Create a Custom Control for that specific Input. Overload your custom control with the validations. If your class cannot be used outside this UI, don't bother creating validations inside. Move everything in your custom Control and, even forbid invalid chars (if it's a textbox) whenever possible. In this specific case, you're going to use the UserControl as the Validator component of your Datas.
Otherwise, use the Class validating Function scheme upon Input and display the appropriate error in an User Friendly way whenever possible through that user Control (case where your Class may be used without the UserControl, which would generally be the case)
Etc. etc. etc.
I know I'm more considering the user who's going to use the Application than the one who's going to write the code. But have a look at Baltasarq's answer. In fact, best move is to do both. The three first options are there only for a simple Class of no real importance in your whole Project. We've all created that tiny Class to begin with, and we didn't bother to make strong validation controls. I think that most of us still use those kind of classes. However, as times goes by, some of those classes become more and more used.. then we were faced to the need of stronger validations schemes.
That's the cutting corners way. It's unsafe, but it works... until something happens...
=> Try to do both whenever possible. You don't know what may happen, who is going to use your Class, whether your boss will change his mind and ask you to create a specific UI for that Class to be user friendly for everyone...
Since a while, when I have time upon creating a Class, I'm in fact
creating at least two classes :
- MyClass_Class
- MyClass_Form
- (and perhaps MyClass_UserControl)
- (and perhaps MyChildClassWithUnsafeSetters - used to set value that has already been validated for performance needs)
The core class always provide live Validation capabilities...
EDIT :
Property Validator Function sample using enums...
[Flags]
public enum registrationValidation_Enum
{
Valid = 0x01,
TooLong = 0x02,
InvalidChars = 0x04,
NullEntry = 0x08
// ...
}
This enum can be encapsulated within the class. Enums are easier to handle/memorize/retrieve than Exceptions Classes.
This is the Property Getter/Setter.
class Car
{
private string registration = "Unknown";
public string Registration
{
get
{
return registration;
}
set
{
validate_registration(value, True);
// Setter for the Property.
// Throws an Exception upon invalid value.
}
}
}
This is a Validator Function which is Public :
public registrationValidation_Enum test_registration(
string newRegistration)
{
registrationValidation_Enum checkResult =
registrationValidation_Enum.Valid;
// Do the checks here
if (newRegistration.Length > 10)
{
checkResult = checkResult | registrationValidation_Enum.TooLong;
}
if (containsNonAlphNumericChars(newRegistration))
{
checkResult = checkResult | registrationValidation_Enum.InvalidChars;
}
// ...
return checkResult;
}
And here is the Public version of the Setter :
// this bypass the double check : attempts to set the value if Valid.
// otherwise, either returns a validation result,
// either throws an exception.
public registrationValidation_Enum validate_registration(
string newRegistration,
bool canThrowException)
{
bool isValid = test_registration(newRegistration);
if (isValid == registrationValidation_Enum.Valid)
{
registration = newRegistration;
return registrationValidation_Enum.Valid;
}
else
{
if (canThrowException)
{
string exceptionMessage = "";
if (isValid | registrationValidation_Enum.TooLong)
{
exceptionMessage += "Registration too long"
+ Environment.NewLine;
}
if (isValid | registrationValidation_Enum.InvalidChars)
{
exceptionMessage +=
"Registration contains invalid characters"
+ Environment.NewLine;
}
// ....
Throw New Exception(exceptionMessage);
}
else
{
return isValid;
}
}
}
The public validate_registration(string, false) is there in case :
you don't want to double the validation upon Button Click
you don't live monitor the user Inputs
you don't want to handle cascading exceptions everywhere
you want have control over custom error messages per UI context (you can't always have a label to write errors in)
while attempting to set registration value, all in a row with a button click.
Put the validation result in a variable in any UI-side and display the appropriate notifications/users choices depending on the UI components you can display... This wouldn't have been that simple with Exceptions : Imagine you have both TooLong and InvalidChars. Are you going to show a dialogbox "Too Long" then click button then show another "Invalid Chars" dialog ?
Note : To make the class Localizable, with custom Exception messages using Culture, I would define Class Level Messages (string) variables which values depend on the loaded Culture.
You should have a Core of classes and also those classes related to the user interface. First, create the Core classes (the bussiness logic) of your application. Of course, you should do validation here. Actually, code as if you had no knowledge about who is going to implement the user interface. Also, take into account that users interfaces can change, while the core classes should remain untouched.
When coding the user interface, you wil realise that if you don't do any validation, exceptions will be raised when the user inputs some data cases. This will make you create validation also in the user interface classes.
So, the answer is, you will finally have validation on both parts of the application.
You would use public properties with private members, where you do the checking inside the properties and then assign it to class members.
class Car
{
private string registration;
public string Registration
{
get { return registration;}
set {
if(Validate.registration(value))
registration = value;
else
throw new Exception("Your exception message here");
}
}
}
private void add_Click(object sender, EventArgs e)
{
Car.Registration = txtReg.Text;
}
There are 2 validations:
data type/property limits/parsing;
logical (values between properties);
Have a look at PropertyGrid. It's basic (and pretty sufficient) validation is if your property accept value or throw:
class Car
{
private int _someValue;
public int SomeValue
{
get { return _someValue; }
set
{
if(value > 100)
throw new OutOfRangeException(...);
_someValue = value;
}
}
}
This ensures what Car can validate own properties no matter how they are set (deserialization, PropertyGrid, direct property value, reflection, etc).
Another thing is some logical validation, which can't be performed at instance level, or you simply don't care about it (let instance to be created without exceptions). This one has to be put into editor code (form what is used to create instance).
As for myself, talking about TextBox, I prefer to make custom MyTextBox control which has all parsing related validation (methods GetDouble(), GetInt(), GetIntTime(), etc) and possibility to setup/query it (properties IsDouble, IsInt, etc.).
I came across a Singleton implementation in a site I was tasked to make changes to. The only thing I know about Singleton is its definition and as such never had an opportunity to work "with" it. So I started to read articles and this one on Implementing the Singleton Pattern in C# nicely explains it. Except that the code I have looks not quite the same. Can some take a look at this and points out what this code does or how is it different?
public class Singleton<TSingleton> where TSingleton : class, new()
{
private static readonly Lazy<TSingleton> instance = new Lazy<TSingleton>(() => new TSingleton());
public static TSingleton Instance { get { return instance.Value; } }
}
This class is called like this Singleton<AccessLogger>.Instance.LogAccess(accessData); where accessData is an instance of AccessLoggerData and basically contains environment, page and user information. The accessData is an instance of AccessLoggerData class:
public class AccessLoggerData
{
public string Environment = Singleton<ApplicationSettings>.Instance.Environment;
public string Page, UserId;
public AccessLoggerData(string page, string user)
{
this.Page = page;
this.UserId = user;
}
}
Strangely as I'm writing this post and somehow it is becoming more clear as to how these pieces come together, but one thing remains unclear, why would it be necessary to allow only one instance of this accessData object?
This looks like a generic implementation of the singleton pattern using the (newish) Lazy keyword. In its default form it make sure that only a single instance of the object created is accessed (LazyThreadSafetyMode.ExecutionAndPublication). This is important as the initialization code of the object being created might have some side effects that would be undesirable if executed twice. Checkout http://csharpindepth.com/articles/general/singleton.aspx for some more information on this.
"why would it be necessary to allow only one instance of this accessData object?"
It's a little hard to say exactly just based on the code provided. Perhaps multiple users are active on the system at the same time. The class name AccessLoggerData suggests that info is being logged.
You'd only want one instance logging that data if it involves file access. You wouldn't want multiple instances competing for a file write lock. The problem with this is there's nothing to suggest that in the actual code. Maybe it's meant to allow one user at a time and their state is held by this Singleton. In that case, it's bad design. Considering there's another Singleton within AccessLoggerData for application settings, you have a Singleton as a global: not good. It may be Singletonitis by the former developer.
I have a very large (77 actions) controller that I am using to make a site with wizard-like functionality. The site is like a "job application manager" with multiple components such as an admin component and an end-user component. The component I'm working with is the part where the user would actually fill out a job application. The way things are structured with the other components, it makes the most sense to put all of the job application stuff in the same controller. All of these actions perform similar things but on different models, like so:
public class ExampleController : Controller
{
public ActionResult Action1()
{
Guid appId = new Guid(Session["AppId"].ToString());
... // logic to pull up correct model
return View(model)
}
[HttpPost]
public ActionResult Action1(FormCollection formValues)
{
Guid appId = new Guid(Session["AppId"].ToString());
... // logic to update the model
return RedirectToAction("Action2");
}
public ActionResult Action2()
{
Guid appId = new Guid(Session["AppId"].ToString());
... // logic to pull up the correct model
return View(model)
}
... // on and on and on for 74 more actions
}
Is there any way to reduce some of the constant redundancy that's in every one of the actions? Here is what I am thinking:
Creating a member variable Guid to store the appId and then overriding OnActionExecuting to populate this variable. Is this a good idea?
Implementing some kind of paging to cut down on the number of actions. Any suggestions on how to do that?
I would say yes to your first point and "it depends" to your second. Don't change your design just because you have a lot of methods, if all 77 ActionResult methods make sense to have, then keep them around.
Using a member variable and overriding OnActionExecuting seems like a great way to refactor that appID Guid code into a single place, so you can quickly and easily modify it in the future.
Normally for wizard view, a single action and page is used with multiple divs which can be shown according to the steps.
For example, a registration wizard screen having 4 steps, can be be handled in a single page with divs for each steps. You can make use of JavaScript and css to make it a wizard flow.
Make use of ajax to update different models, if necessary in between the steps.
You may want to put your logic (Job Manager related) in a single repository/manager class. Different controllers associated with different views(e.g AdminController, EndUserController etc) can call methods from same repository/manager class.
Another option could be replacing this..
Guid appId = new Guid(Session["AppId"].ToString());
..with a call to something like the following:
private Guid GetAppId(){
return new Guid(Session["AppId"].ToString());
}
Now you could just use GetAppId() instead wherever you currently use appId. You could of course cache the GUID in the form of a class variable, as you suggest, but it might be a good idea to limit the access and use of that variable to a method like this (get it's value via the method). Might be a little more flexible in case you want to change something later.
As for dividing the page into several pages; sure, go ahead, if it makes sense and feels right. Over 70 actions in one class does sound like a lot. If it makes more sense to keep them there however, you could try to move as much logic as possible out from the methods themselves, and into helper-classes instead. I always try to keep the actions as small as possible, and put the logic in separate classes, each of which is tailored to do one specific thing.
My point is, if each action is no more than 2-4 lines, then 70+ actions is not necessarily a problem.
If I have an aggregate root which consists of say:
class Parent
{
IEnumerable<Child> Children{ get; set; }
}
Children could contain any number of possible Child objects which are stored in the database.
What would be the best way of getting a total list of all Child objects to the application, so they can be presented in a UI allowing a user to attach/remove them from the Parent object?
Having a method in Parent such as
class Parent
{
IEnumerable<Children> GetAllChildObjects { get; set; }
}
would surely corrupt the model with implementation details?
Would it be ok to have a domain service which calls the Parent repository and retrieves a full list. The facade to the application could then call the service directly, ensuring the Parent model stays "pure".
Update:
To give a bit more detail, i'm tidying up a system and trying to give it some structure.
A User can hold a number of WorkLocations. WorkLocations are pretty simple. The current system contains a webpage which displays user details including a full list of valid WorkLocations. Selecting locations from the list updates the User model with the new locations.
Currently, the UI pretty much hits the DB and pulls out the full list of WorkLocations. I need to pull this back into a more structured form.
Or, does this suggest that WorkLocation should not be in the User root as it currently is?
Am I correct in thinking that you want all the WorkLocations from the database, regardless of what User they are attached to (if any)?
If so I would definitely go for the service approach, something like:
public interface IWorkLocationsService
{
IEnumerable<WorkLocation> GetAllWorkLocations();
}
You might want WorkLocation to be immutable so that all changes to them go through User, though I suspect this isn't necessary here.
Update:
You could then add the following methods to User
// This gets filled from the db somehow.
private IList<WorkLocation> workLocations;
// IEnumerable so that all external additions and
// removals must go through dedicated methods.
public IEnumerable<WorkLocation> WorkLocations
{
get { return workLocations; }
}
public void AddWorkLocation(WorkLocation locationToAdd)
{
workLocations.Add(locationToAdd);
// Do whatever else you need to, i.e. mark the item for saving.
}
public void RemoveWorkLocation(WorkLocation locationToRemove)
{
workLocations.Remove(locationToRemove);
// Do whatever else you need to, i.e. mark the item for saving.
}
If you really must get the list of SonOfFoo for some reason, by using simple high level interfaces such as IEnumerable, you're not corrupting the model with implementation details.
Depending on what you need done, it would be better to avoid getting a list of SonOfFoo though, having Foo manage the work would be better.
Also depending on the amount of details SonOfFoo has, it would be a good idea to encapsulate it on an interface with the methods that the UI/Facade would need to use.
Edit:
From your description, the UI needs a list of the WorkLocations a user can work at (a IEnumarable would be a good choice), and then after the user selects the location and confirms it, the UI notifies the control the switch of the user with the selected location.
I've been noticing static classes getting a lot of bad rep on SO in regards to being used to store global information. (And global variables being scorned upon in general) I'd just like to know what a good alternative is for my example below...
I'm developing a WPF app, and many views of the data retrieved from my db are filtered based on the ID of the current logged in user. Similarly, certain points in my app should only be accessable to users who are deemed as 'admins'.
I'm currently storing a loggedInUserId and an isAdmin bool in a static class.
Various parts of my app need this info and I'm wondering why it's not ideal in this case, and what the alternatives are. It seems very convienient to get up and running.
The only thing I can think of as an alternative is to use an IoC Container to inject a Singleton instance into classes which need this global information, the classes could then talk to this through its interface. However, is this overkill / leading me into analysis paralysis?
Thanks in advance for any insight.
Update
So I'm leaning towards dependency injection via IoC as It would lend itself better to testability, as I could swap in a service that provides "global" info with a mock if needed. I suppose what remains is whether or not the injected object should be a singleton or static. :-)
Will prob pick Mark's answer although waiting to see if there's any more discussion. I don't think there's a right way as such. I'm just interested to see some discussion which would enlighten me as there seems to be a lot of "this is bad" "that is bad" statements on some similar questions without any constructive alternatives.
Update #2
So I picked Robert's answer seeing as it is a great alternative (I suppose alternative is a weird word, probably the One True Way seeing as it is built into the framework). It's not forcing me to create a static class/singleton (although it is thread static).
The only thing that still makes me curious is how this would have been tackled if the "global" data I had to store had nothing to do with User Authentication.
Forget Singletons and static data. That pattern of access is going to fail you at some time.
Create your own custom IPrincipal and replace Thread.CurrentPrincipal with it at a point where login is appropriate. You typically keep the reference to the current IIdentity.
In your routine where the user logs on, e.g. you have verified their credentials, attach your custom principal to the Thread.
IIdentity currentIdentity = System.Threading.Thread.CurrentPrincipal.Identity;
System.Threading.Thread.CurrentPrincipal
= new MyAppUser(1234,false,currentIdentity);
in ASP.Net you would also set the HttpContext.Current.User at the same time
public class MyAppUser : IPrincipal
{
private IIdentity _identity;
private UserId { get; private set; }
private IsAdmin { get; private set; } // perhaps use IsInRole
MyAppUser(userId, isAdmin, iIdentity)
{
if( iIdentity == null )
throw new ArgumentNullException("iIdentity");
UserId = userId;
IsAdmin = isAdmin;
_identity = iIdentity;
}
#region IPrincipal Members
public System.Security.Principal.IIdentity Identity
{
get { return _identity; }
}
// typically this stores a list of roles,
// but this conforms with the OP question
public bool IsInRole(string role)
{
if( "Admin".Equals(role) )
return IsAdmin;
throw new ArgumentException("Role " + role + " is not supported");
}
#endregion
}
This is the preferred way to do it, and it's in the framework for a reason. This way you can get at the user in a standard way.
We also do things like add properties if the user is anonymous (unknown) to support a scenario of mixed anonymous/logged-in authentication scenarios.
Additionally:
you can still use DI (Dependancy Injection) by injecting the Membership Service that retrieves / checks credentials.
you can use the Repository pattern to also gain access to the current MyAppUser (although arguably it's just making the cast to MyAppUser for you, there can be benefits to this)
There are many other answers here on SO that explains why statics (including Singleton) is bad for you, so I will not go into details (although I wholeheartedly second those sentiments).
As a general rule, DI is the way to go. You can then inject a service that can tell you anything you need to know about the environment.
However, since you are dealing with user information, Thread.CurrentPrincipal may be a viable alternative (although it is Thread Static).
For convenience, you can wrap a strongly typed User class around it.
I'd try a different approach. The static data class is going to get you in trouble -- this is from experience. You could have a User object (see #Robert Paulson's answer for a great way to do this) and pass that to every object as you construct it -- it might work for you but you'll get a lot template code that just repeats everywhere.
You could store all your objects in a database / encrypted file with the necessary permissions and then dynamically load all of them based on your Users permissions. With a simple admin form on the database, it's pretty easy to maintain (the file is a little bit harder).
You could create a RequiresAdminPermissionAttribute object to apply to all your sensitive objects and check it at run-time against your User object to conditionally load to objects.
While the route you're on now has merit, I think there are some better options to try.