I've got a simple factory that's built in C# that instantiates and configures validators that are built in ASP.net and JavaScript. I want a way to test if I'm accidently trying to set a validator twice (for example, having two RequiredValueValidators is not a great idea and could cause ui/ux problems) on the same Control, but I also wish to make sure that validators that use the same same building mechanisms, but in a different way, are preserved (such as two RegularExpressionValidators that use different RE, but not two that use the same RE.)
I've tried a few different possible techniques that I'll detail these as answers below- but in essence I need a technique to pass a description on how to compare two validators of the same base type to discern if they are equal( N.B. 'equal' is NOT 'identical', they could have different IDs (etc) but still do the same job.) that's interpretable at runtime and accessible to other areas of my c# .dll to actually run the check.
My answers will be community wiki with the intent that errors/pitfalls that I fell into will be edited out/corrected/discussed by the community, rather than being merely downvoted for being initially incorrect, so that others' won't suffer the same fate.
One attempt I've had is to set a predicate as an attribute of the method in my factory that builds the validator. This would then be accessed by using reflection somewhere else and then used to compare two potential validators.
A major flaw in this is that you cannot set predicates (or delegates for that matter) as attributes.
A possible work-around is where you give a an individual property (containing the predicate delegate or IEquatable<> implementation and then retrieve that - however there are a lot of different things to consider when comparing validators (what type, configurations, does it rely on other controls etc....) so unless you can create a base class or interface that can deal with different types of IEquatable<ValidatorType> this is also impossible...
I've also tried creating a small, static switch case method within my factory that will be able to simply output another small configurations class that would be created by the switch case. This in essence is much simpler than the previous question, but it's not without it's problems. For example, I cannot define my return and parameter types correctly so that a RegularExpressionValidator can check if it's correct within the same code block as a ValidDateValidatorcheck.
Related
Preamble:
I'm working on implementing a system where a developer can specify on object of type T which has N number of properties.
What I'm trying to accomplish:
I'd like to be able to provide more concrete control over how these properties are set and retrieved. This is difficult because of the limitless number of configurations possible.
Solutions I'm pursuing:
Is it possible to set getters dynamically?
Either through attributes? Generate the methods after the fact during construction like :
foreach(var property in typeOf(T).GetProperties())
{
//dynamically generate getter method which returns this property.
}
Possibly wrap type T in a container object which has the type as one of its properties. Then set up some type of special getter for that.
Why I want to do this:
Currently all the types for T get converted based on Typecode. Allowing people using this library to easily parse in values from various sources (databases, text files, app configs, etc.) as properties of type T. The point being to deliver these properties as type safe values rather than magic strings.
This is the impetus for wanting to use reflection for this but I could see numerous other applications for this I would imagine.
I could just say "Hey make all of your types nullable." so that it would be easy to determine which properties have been set in type T. I'd like to abstract away even that though.
The other option for this would be "Make sure you understand that certain types have default values. Be certain you're ready to accept those values, or set default values of your own (including making it nullable and setting it to null if so desired). Essentially trusting this to the developer rather than abstracting it. <==== This is what I'm currently doing.
Being able to dynamically generate methods, especially getters and setters, dynamically via reflection or a combination of reflection and C# Actions would be incredibly valuable. Any insight or ideas would be greatly welcome. Either ways of accomplishing the solutions I'm pursuiing or another idea which achieves the same ends.
I don't believe you can set accessor methods on properties of static types. Another challenge that I think you will have to deal with will be your goal to provide type safety - you see, if your types are built in run-time, compile-time checks will not work, which means you'll have to rely on dynamic a lot - this is slow. But not all is lost. You have at least two options:
The quick and dirty way
You can generate proxy classes that would inherit from your concrete types. Theese will give you ability to intercept method calls to base members and do pretty much anything you please. See Castle DynamicProxy
The hard but proper way (actually first option is using this behind the scenes)
You're looking at IL Generator namespace. This is a step above linq expression trees in a sense that you can generate your own assembly and types, all programmatically. This however is incredibly complex and error prone. I'd suggest you try option one first and only generate your own IL if you absolutely must.
UPD I know you didn't want magic strings, an I guess this is a bit less conventional solution, but also check out CSharpCodeProvider of CodeDOM namespace
After playing around with Asp.Net MVC for some time I have decided to actually use it in a project. One of the issues that came up is that the frontend site might have different validation rules for a given model than the admin panel.
I am aware of the MetadataType property but since you have more than one contexts this would not work for us out of the box.
In order to solve this I implemented a custom ModelMetadataProvider that redirects the default ModelMetdataProvider to a different type based on the request's execution context. This works pretty well for displaying the needed UI.
The part of this solution I do not like is that I ended up reading the stack from my custom model metadata provider to determine if the given call is for model binding. This is because when I did not do that I would correctly get "Object does not match target type" during the call to TryUpdateModel from the Controller since the model binder was trying to use properties from type A to set values to an instance of type B.
Is reading the call stack such a bad idea for production?
Is there a way to replicate the MetadataTypeAttribute behavior selectively without using attributes?
Thanks in advance,
John
This is one of those instances where you wish the ASP.NET MVC Team hadn't sealed a class - I'm sure they had their reasons. I was going to suggest simply creating your own attribute, derived from MetadataTypeAttribute.
One way to go about this is to take the source of the attribute and write your own:
http://dotnetinside.com/framework/v4.0.30319/framework/v4.0.30319/System.ComponentModel.DataAnnotations/MetadataTypeAttribute
Although, of course, this makes your code less maintainable.
I would assert that to the best of my knowledge, you are already making the right decision with a ModelMetadataProvider as your solution. I'm a little nervous for you regarding analysing the call stack though, change locations, move something to an area; you get my drift, i.e. it would be very easy to break the code with a build time decision that isn't found until runtime or beyond QA.
You haven't supplied how the context is roughly determined, but I would personally tackle that by adding a property to the class itself with an Enum (finite possibilities and design time breakage) with a list of possible contexts, then during spin up of the class, populate it, ready for execution of the Provider, which will pass through the correct metatdatatype based on the value of the Enum.
Many ways to skin this cat, but something that is going to break on build will serve you best, IMHO.
Unless you are using MVC 6 you may find ModelMetadata Fluent Configuration useful.
Some nice examples of how to use it can be found here and here.
What is really important is that it is just code which is completely under your control. Thus, once you have different contexts, you may decide to define different configurations, or you may play a bit harder and make (a set of) different registrations for different contexts.
What really helps is "decorating" (the term used on purpose!) properties of a base class, at least nothing seems to stooping you from doing it.
EDIT: Model Metadata shouldn't be confused with WCF RIA Services Contrib.
Background:
I have 2 instances of an object of the same type. One object is populated with the configuration of a device I'm connected to, the other object is populated with a version of the configuration that I've stored on my hard drive.
The user can alter either, so I'd like to compare them and present the differences to the user.
Each object contains a number of ViewModel properties, all of which extend ViewModelBase, which are the ones I want to compare.
Question:
Is a better way to do this than what I'm about to propose.
I'm thinking of using Reflection to inspect each property in my objects, and for each that extend ViewModelBase, I'll loop through each of those properties. For any that are different, I'll put the name and value into a list and then present that to the user.
Rather than inventing this wheel, I'm wondering if this is this a problem that's been solved before? Is there a better way for it to be done?
Depending on the amount of properties to be compared, manual checking would be the more efficient option. However, if you have lots of properties or want the check to be dynamic (i.e. you just add new properties and it automagically works), then I think Reflection is the way to go here.
Why not just implement the equals operator for your type?
http://msdn.microsoft.com/en-us/library/ms173147(v=vs.80).aspx
Edit: Having read more carefully I see what you're actually asking is what the most efficient way of doing the actual comparison is.
Doing it via reflection saves on code but is slower. Doing it with lots of manual comparions is fairly quick but more code.
If you are fairly determent and lazy in the good way. You can mix benefits of both solutions. With help of tool like cci you can emit method that compares properties. The beauty of this is that your reflection code will be executed on compile time leaving you with strait forward method to execute at runtime. This allows you to change models as you see fit and not worry about comparison code. There is a down side to this and that is learning cci which is quite challenging.
Although this is a fairly common problem, I am struggling with what the best way to approach it (if it needs approached at all in this case).
I have inherited a website (ASP.NET, C#) part of which contains a class full of static methods (it's a very large class, honestly). One method in particular is for sending e-mails. It has every possible parameter I can think of and it works well enough. However, the internals of that particular method are rather cumbersome to manage and understand due to the fact that everything is shoved inside - particularly when most of the parameters aren't used. In addition, it is somewhat difficult to handle errors, again, due to all the parameters for this one method.
Would it make more sense to actually have an EMail class which is instantiated when you want to send an e-mail? This just "feels" more right to me, though I can't full explain why. What are your thoughts on the way to go in this particular case? How about in general?
Thanks.
What you're describing sounds like an example of the aphorism, "You can write FORTRAN in any language."
A massive class full of static methods is often (not always) a sign that somebody just didn't "get" OOP, was stuck in a procedural-programming mindset and was trying to twist the language to do what he wanted.
As a rule of thumb: If any method, static or instance, takes more than about 5 parameters, it's often a sign that the method is trying to do too many things at once, and is a good candidate for refactoring into one or more classes.
Also, if the static methods are not really related, then they should at least be split up into classes that implement related functionality.
I'm actually wondering why you'd have a "send e-mail" method at all, given that the System.Net.Mail namespace handles just about every case, and is configurable via the app.config/web.config file, so you don't need to pass it a server name or port. Is this perchance a "notification" method - something that individual pages are supposed to call out to in order to send one of several "standard" messages based on templates with various values filled in, and certain headers/footers automatically added? If so, there are a number of designs for this type of interaction that are much easier to work with than what you seem to have inherited. (i.e. MailDefinition)
Update: Now having seen your comment that this is being used for exception handling, I think that the most appropriate solution is an actual exception handler. There are a ton of resources on this. For ASP.NET WebForms, I actually took the one Jeff Atwood wrote years ago, ported it to C# and made a few changes (like ignoring 404 errors). There are a number of good links in this previous question.
My preference these days is just to treat exception handling (and subsequent e-mailing of exception reports) as a subset of logging. log4net has an SmtpAppender that's quite capable, and you can configure it to only be used for "fatal" errors (i.e. unhandled exceptions - in your handler, you just make a LogFatal call).
The important thing, which you'll no doubt pick up from the SO link above and any referenced links, is that there are actually two anti-patterns here - the "miscellaneous" static class, and catching exceptions that you don't know how to handle. This is a poor practice in .NET - in most cases you should only catch application-specific exceptions that you can recover from, and let all other exceptions bubble up, installing a global exception handler if necessary.
Here are the Microsoft guidelines for when to use static types, generally.
Some things I would add, personally:
You must use static types to write extension methods.
Static types can make unit testing hard as they are difficult/impossible to mock.
Static types enforce immutability and referentially transparent functions, which can be a good design. So use them for things which are designed to be immutable and have no external dependencies. E.g., System.Math.
Some argue (e.g.) that the Singleton pattern is a bad idea. In any event, it would be wrong to think of static types as Singletons; they're much more broad than that.
This particular case has side-effects (sending e-mails) and doesn't appear to require extension methods. So it doesn't fit into what I would see as the useful case for static types. On the other hand, using an object would allow mocking the e-mail, which would be helpful for a unit test. So I think you're correct to say that a static type is inappropriate here.
Oh my gosh yes.
It sounds like its an old Classic ASP app that was ported.
It violates the single responsibility principle. If you can refactor that class. Use overloading for that function.
That is an example of the Utils anti-pattern.
It is always a good idea to separate those methods according on their responsibility. Creating an Email class is definitely a Good Idea™. It will give you a much nicer interface to use, and it allows you to mock out the Email in tests.
See The Little Manual of API Design, which describes the benefits of classes having minimal constructors and lots of getters/setters over the alternative of using constructor/methods having many parameters.
Since most of the parameters of the methods you mention are not used, a better approach is to use simple constructors that assume reasonable default settings for the internal variables. Having setter methods allows you to then set the few parameters (and only those parameters) that require non-default values.
I am fairly new to reflection and I would like to know, if possible, how to create an instance of a class then add properties to the class, set those properties, then read them later. I don't have any code as i don't even know how to start going about this. C# or VB is fine.
Thank You
EDIT: (to elaborate)
My system has a dynamic form creator. one of my associates requires that the form data be accessible via web service. My idea was to create a class (based on the dynamic form) add properties to the class (based on the forms fields) set those properties (based on the values input for those fields) then return the class in the web service.
additionally, the web service will be able to set the properties in the class and eventually commit those changes to the db.
If you mean dynamically create a class, then the two options are:
Reflection.Emit - Difficult, Fast to create the class
CodeDom - Less Difficult, Slower to create the class
If you mean create an instance of an existing class, then start with Activator.CreateInstance to create an instance of the object, and then look at the methods on Type such as GetProperty which will return a PropertyInfo that you can call GetValue and SetValue on.
Update: For the scenario you describe, returning dynamic data from a web service, then I'd recommend against this approach as it's hard for you to code, and hard for statically-typed languages to consume. Instead, as suggested in the comments and one of the other answers, some sort of dictionary would likely be a better option.
(Note that when I say return some sort of dictionary, I am speaking figuratively rather than literally, i.e. return something which is conceptually the same as a dictionary such as a list of key-value pairs. I wouldn't recommend directly returning one (even if you're using WCF which does support this) because it's typically better to have full control over the XML you return.)
I know this is being overly simplified by why not just KISS and generate the required Xml to return through the Web Service and then parse the returned Xml to populate the database.
My reasoning is that for the expanded reason you suggest doing this I can see the value or reason for wanting a dynamic class?
The Execution-Time Code Generation chapter of Eric Gunnerson's book (A Programmer's Introduction to C#) has some great information on this topic. See page 14 and onwards in particular. He outlines the two main methods of accomplishing dynamic class/code generation (CodeDOM and the Reflection.Emit namespace). It also discusses the difficulty and performance of the two approaches. Have a read through that, and you ought to find everything you might need.
The real question is, what do you need to use those properties for?
What are gonna be the use cases? Do you need to bind those properties to the UI somehow? Using what kind of technology? (WPF, Windows Forms?)
Is it just that you need to gather a set of key/value pairs at runtime? Then maybe a simple dictionary would do the trick.
Please elaborate if you can on what it is you need, and I'm sure people here can come up with plenty of ways to help you, but it's difficult to give a good answer without more context.