I need to implement few custom properties in PropertyGrid at runtime. After reading dozens of articles, a simple & elegant solution I found is by #Simon Mourier in another stackoverflow thread:
Custom, Complicated, Dynamic Reflection Solution - C#
However, this solution add only expandable properties.
I need also root properties to be added dynamically, like "Name" in picture above.
This is the Holder class:
public class MyHolder
{
public MyHolder()
{
Objects = new List<object>();
}
public string Name { get; set; } // this is not dynamic
[TypeConverter(typeof(MyCollectionConverter))]
public List<object> Objects { get; private set; }
}
How can I modifpublic class MyHolder
{
public MyHolder()
{
Objects = new List<object>();
}
public string Name { get; set; }
[TypeConverter(typeof(MyCollectionConverter))]
public List<object> Objects { get; private set; }
}
I tried to derive the Holder class from CollectionBase,ICustomTypeDescriptor like in this old article
http://www.codeproject.com/Articles/9280/Add-Remove-Items-to-from-PropertyGrid-at-Runtime
But obvious, mixed things are not working.
How can I make root properties (like "Name") of Holder class to be dynamic, to be add at runtime too?
Thanks very much in advance,
Related
I've been getting my head into WPF the last few days, coming from a WinForms background, I just love the flexibility, especially in terms of binding.
However, I had a question after reading the following article on MVVM: http://blog.alner.net/archive/2010/02/09/mvvm-to-wrap-or-not-to-wrap.aspx
How to go about Models I have no control over, I cannot add interfaces to it, etcetera, I can only use them as-is?
Looking at the article, one option for me is to just directly expose the Model in my ViewModel, but would this be a good way to go about it? I could also use the wrapping option, but how do I bubble changes to those bubbles back to the ViewModel if they don't have a INotifyPropertyChanged interface? Are there any other options that allow TwoWay-binding to these Models?
EDIT:
Consider the following classes as models I cannot modify, what are my options:
[DataContract]
public class NPCTypeData
{
[DataMember]
public string Name;
[DataMember]
public List<NameAlias> Emotions;
}
[DataContract]
public class NameAlias
{
[DataMember]
public string Name;
[DataMember]
public string Alias;
}
I don't really care about the code required to turn these into bindable classes, I just want one or more examples on where to start with nested dependencies like this.
Do I copy all data to a Model that does have bindable properties and just leave these for serialization, do I wrap them, or what?
I agree with Henk, and would add that one option can be the "dynamic proxy class creation" which is what entity framework does. Basically: you have your POCO objects, and Entity framework can attach dynamically the necessary functionality to track the changes on model.
There's also an option to inherit from a class, and decorate the class with AOP attribute which generates all the necessary plumbing on the fly.
You can google for:
AOP INotifyPropertyChanged - http://www.postsharp.net/
Automatic INotifyPropertyChanged using Dynamic Proxy - http://jonas.follesoe.no/2009/12/23/automatic-inotifypropertychanged-using-dynamic-proxy/
When I had such problem, I basically used Henk solution, creating new classes and wrapping each property, using AutoMapper. Did it work & was it maintable? Yes, it worked, and it was maintable. Was it painful? Yes.
public class NPCTypeDataViewModel
{
public string Name {
get;
set;
}
public List<NameAliasViewModel> Emotions {
get;
set;
}
public NPCTypeDataViewModel(NPCTypeData data){
Name = data.Name;
Emotions = data.Emotions.Select(x => new NameAliasViewModel(x))
.ToList();
}
public NPCTypeData GetModel(){
var ntd = new NPCTypeData(){
Name = Name,
Emotions = Emotions.Select(emo => emo.GetModel())
.ToList()
};
return ntd;
}
}
public class NameAliasViewModel
{
public string Name {
get;
set;
}
public string Alias {
get;
set;
}
public NameAliasViewModel(NameAlias alias){
Name = alias.Name;
Alias = alias.Alias;
}
public NameAlias GetModel(){
return new NameAlias(){
Name = Name,
Alias = Alias
};
}
}
I'm currently trying to figure out how to have a wrapper class expose the properties of whatever it is wrapping without having to manually set them one by one in the wrapper class. I've been trying to figure out if this is even a good design choice or if I'm totally misguided and going off into a very bad placeā¢ by doing this.
I also already have my wrapper class inheriting something...
Example code below (fake objects so don't read into them please):
public class Car {
public String Name { get; set; }
public String Status { get; set; }
public String Type { get; set; }
public Car(takes params) {
// makes car!
}
}
public class CarWrapper : OtherAutomotiveRelatedThing {
public Car car;
public CarWrapper(Car c) {
car = c;
}
}
public class OtherAutomotiveRelatedThing {
public String Property1 { get; protected set; }
public String Property2 { get; protected set; }
}
I'm using inheritance on the wrapper object because I can not modify the base Car class and it needs the properties of other automotive thing. Multiple other classes inherit from OtherAutomotiveRelatedThing as well.
I return a list of the CarWrapper objects as Json (because I'm building a web app) and the wrapper object is causing problems for me. When cast/converted to Json the CarWrapper objects in the list all contain another nested object - the Car object and the framework I'm using can't get at its properties to do what it needs.
Is there a way to expose the wrapped Car object's properties at the "top level" of the CarWrapper without doing the following:
public class CarWrapper : OtherAutomotiveRelatedThing {
public Car car;
public String Name { get; private set; }
public String Status { get; private set; }
public String Type { get; private set; }
public CarWrapper(Car c) {
car = c;
this.Name = c.Name;
this.Status = c.Status;
this.Type = c.Type;
}
}
Please let me know if I'm not being clear, if you have any questions, or need/want more info.
Thanks!
For me it looks like you want prototype-style programming like in JavaScript, which is not they use in OOP.
Maybe it's good start to think of it as "If I have two different car wrappers (with differnt properties set), how should I pass any of them a method?" or "Can I have a single wrapper which wraps Car and Animal", and "How to expose public property which has the same name but different meaning for Car and Animal, like skin color?" etc
Answers may help you identify if you need say interfaces, or wrappers which expose public objects, or pure encapsulation, or changing language to say JavaScript.
I have a class I wish to modify the property names of.
However this class is buried about 6 classes deep in a much much larger class(also all custom classes).
My problem is I cant touch any of the existing classes.
The only solution I can think of is to derive from the root class, stick it in a new namespace, then create new classes at each stage inbetween the root class and the class I wanted to modify.
Hopefully this makes sense what Im trying to explain.
Is the above method the only way?
Because you've stated the class you want to extend is a partial class I'm going to recommend that you extend it as such as well. Now you can easily add the new properties, as you've already suggested, and extend the class by adding a class in the same namespace with the same name.
In the example below, both classes are named A and both classes are in the same namespace - those are the two keys to building partial classes.
public partial class A
{
public string PropertyA { get; set; }
public string PropertyB { get; set; }
}
public partial class A
{
public string PropertyC
{
get
{
var val = this.PropertyA;
// some more functionality maybe...
return val;
}
set
{
// some more functionality maybe...
this.PropertyA = value;
}
}
}
You could create properties with the new names, but keep the old properties there with the [Obsolete] attribute.
Perhaps as compromise you could create additional properties with the new names, then existing code uses the old properties. You could then additionally mark the old attributes as obsolete.
class Example
{
int oldField;
[Obsolete("This is obsolete")]
public int OldField
{
get
{
return this.oldField;
}
set
{
this.oldField = value;
}
}
public int NewField
{
get
{
return this.oldField;
}
set
{
this.oldField = value;
}
}
}
Is it possible to create classes within a template? Something like...
#{
public class MyClass {
public MyClass() {
Three = new List<string>();
}
public string One { get; set; }
public int Two { get; set; }
public List<string> Three { get; set; }
}
}
Currently I get "Unable to compile template. Check the Errors list for details." when I try to do this. I would like to take XML content and use XmlSerializer to create an instance of MyClass within the template. I can't do the deserialization before hand and shove it into the model because the classes could vary depending on the template.
Yes, this is completely possible. Use the #functions keyword:
#functions {
public class MyClass {
public MyClass() {
Three = new List<string>();
}
public string One { get; set; }
public int Two { get; set; }
public List<string> Three { get; set; }
}
}
I'll post my response from the CodePlex Discussion here:
I'm not sure that is currently possible. When you use codeblocks (#{ }), you're actually writing code within a method, e.g. your above code would do something like:
public void Execute()
{
this.Clear();
public class MyClass {
public MyClass() {
Three = new List<string>();
}
public string One { get; set; }
public int Two { get; set; }
public List<string> Three { get; set;}
}
}
...which of course, is not valid C#. The other problem you will face, is that to use xml serialisation/deserialisation, the type must be known, but if you are defining your type within the template itself, how could you deserialise it in the first place?
What you could do, is use a custom base template:
public class CustomTemplateBase<T> : TemplateBase<T>
{
public dynamic Instance { get; set; }
public dynamic CreateInstance(string typeName)
{
Type type = Type.GetType(typeName);
// You'd to your deserialisation here, I'm going to
// just cheat and return a new instance.
return Activator.CreateInstance(type);
}
}
Using a dynamic property and dynamic return type, we've defined a method that will let us create an instance (through activation or deserialisation, etc.) and call member access on it. To use that in a template, you could then do:
#{
Instance = CreateInstance("ConsoleApplication1.MyClass, ConsoleApplication1");
Instance.One = "Hello World";
}
<h1>#Instance.One</h1>
Where "MyClass" is a defined somewhere in my application. The important thing is, I'm creating an instance per template.
I would suggest using a specific ViewModel class, which could have a dynamic property (ExpandoObject) allowing you to populate it with any custom data structure as needed while still communicating strongly typed for whatever else your view might need.
This also keeps your view models separate from the views themselves, which is good practice (html and code don't mix too well where readability is a concern).
I have a class called Question that has a property called Type. Based on this type, I want to render the question to html in a specific way (multiple choice = radio buttons, multiple answer = checkboxes, etc...). I started out with a single RenderHtml method that called sub-methods depending on the question type, but I'm thinking separating out the rendering logic into individual classes that implement an interface might be better. However, as this class is persisted to the database using NHibernate and the interface implementation is dependent on a property, I'm not sure how best to layout the class.
The class in question:
public class Question
{
public Guid ID { get; set; }
public int Number { get; set; }
public QuestionType Type { get; set; }
public string Content { get; set; }
public Section Section { get; set; }
public IList<Answer> Answers { get; set; }
}
Based on the QuestionType enum property, I'd like to render the following (just an example):
<div>[Content]</div>
<div>
<input type="[Depends on QuestionType property]" /> [Answer Value]
<input type="[Depends on QuestionType property]" /> [Answer Value]
<input type="[Depends on QuestionType property]" /> [Answer Value]
...
</div>
Currently, I have one big switch statement in a function called RenderHtml() that does the dirty work, but I'd like to move it to something cleaner. I'm just not sure how.
Any thoughts?
EDIT: Thanks to everyone for the answers!
I ended up going with the strategy pattern using the following interface:
public interface IQuestionRenderer
{
string RenderHtml(Question question);
}
And the following implementation:
public class MultipleChoiceQuestionRenderer : IQuestionRenderer
{
#region IQuestionRenderer Members
public string RenderHtml(Question question)
{
var wrapper = new HtmlGenericControl("div");
wrapper.ID = question.ID.ToString();
wrapper.Attributes.Add("class", "question-wrapper");
var content = new HtmlGenericControl("div");
content.Attributes.Add("class", "question-content");
content.InnerHtml = question.Content;
wrapper.Controls.Add(content);
var answers = new HtmlGenericControl("div");
answers.Attributes.Add("class", "question-answers");
wrapper.Controls.Add(answers);
foreach (var answer in question.Answers)
{
var answerLabel = new HtmlGenericControl("label");
answerLabel.Attributes.Add("for", answer.ID.ToString());
answers.Controls.Add(answerLabel);
var answerTag = new HtmlInputRadioButton();
answerTag.ID = answer.ID.ToString();
answerTag.Name = question.ID.ToString();
answer.Value = answer.ID.ToString();
answerLabel.Controls.Add(answerTag);
var answerValue = new HtmlGenericControl();
answerValue.InnerHtml = answer.Value + "<br/>";
answerLabel.Controls.Add(answerValue);
}
var stringWriter = new StringWriter();
var htmlWriter = new HtmlTextWriter(stringWriter);
wrapper.RenderControl(htmlWriter);
return stringWriter.ToString();
}
#endregion
}
The modified Question class uses an internal dictionary like so:
public class Question
{
private Dictionary<QuestionType, IQuestionRenderer> _renderers = new Dictionary<QuestionType, IQuestionRenderer>
{
{ QuestionType.MultipleChoice, new MultipleChoiceQuestionRenderer() }
};
public Guid ID { get; set; }
public int Number { get; set; }
public QuestionType Type { get; set; }
public string Content { get; set; }
public Section Section { get; set; }
public IList<Answer> Answers { get; set; }
public string RenderHtml()
{
var renderer = _renderers[Type];
return renderer.RenderHtml(this);
}
}
Looks pretty clean to me. :)
Generally speaking, whenever you see switches on a Type or Enum, it means you can substitute in objects as the "Type" - said differently, a case for polymorphism.
What this means practically is that you'll create a different class for each Question type and override the RenderHTML() function. Each Question object will be responsible for knowing what input type it ought to output.
The benefits are that you remove the switch statement as well as produce good OO based code. The draw backs are that you add a class for every Question type (in this case minimal impact.)
You can for example use the strategy pattern:
Have all your HTML renderers implement a common interface, for example IQuestionRenderer, with a method name Render(Question).
Have an instance of Dictionary<QuestionType, IQuestionRenderer> in your application. Populate it at initialization time, perhaps based on a configuration file.
For a given instance of a question, do: renderers[question.Type].Render(question)
Or, you could have methods named RenderXXX where XXX is the question type, and invoke them by using reflection.
This is a classic case for using object inheritance to achieve what you want. Anytime you see a big switch statement switching on the type of an object, you should consider some form of subclassing.
I see two approaches, depending on how "common" these question types really are and whether rendering is the only difference between them:
Option 1 - Subclass the Question class
public class Question
{
public Guid ID { get; set; }
public int Number { get; set; }
public string Content { get; set; }
public Section Section { get; set; }
public IList<Answer> Answers { get; set; }
public virtual string RenderHtml();
}
public class MultipleChoiceQuestion
{
public string RenderHtml() {
// render a radio button
}
}
public class MultipleAnswerQuestion
{
public string RenderHtml() {
// render a radio button
}
}
Option 2 - Create a render interface, and make that a property on your question class
public class Question
{
public Guid ID { get; set; }
public int Number { get; set; }
public string Content { get; set; }
public Section Section { get; set; }
public IList<Answer> Answers { get; set; }
public IRenderer Renderer { get; private set; }
}
public interface IRenderer {
void RenderHtml(Question q);
}
public class MultipleChoiceRenderer : IRenderer
{
public string RenderHtml(Question q) {
// render a radio button
}
}
public class MultipleAnswerRenderer: IRenderer
{
public string RenderHtml(Question q) {
// render checkboxes
}
}
In this case, you would instantiate the renderer in your constructor based on the question type.
Option 1 is probably preferable if question types differ in more ways than rendering. If rendering is the only difference, consider Option 2.
It's a good idea to separate the rendering logic into its own class. You don't want rendering logic embedded into the business logic of your application.
I would create a class called QuestionRenderer that takes in a Question, reads its type, and outputs rendering accordingly. If you're using ASP.NET it could output webcontrols, or you could do a server control that outputs HTML.
Why not have a QuestionRenderer class (actually, it will be a control) which exposes a Question as a property which you can set.
In the render method, you can decide what to render based on the question type.
I don't like the idea of rendering details being in the same class as the data.
So, one option would be to have your rendering method simply generate one of a set of user controls that handled the actual HTML rendering.
Another would be to have a separate class QuestionRenderer which would have the various subclasses for question types (each of which would render the correct HTML).
I think what you want is an IUserType that convert the property from the hibernate mapping to the correct control type via some Question factory.
An example of the use of an IuserType can be found here:
NHibernate IUserType
in the example it converts a blob to an image for use on the client side but with the same idea you can make your page created with the QuestionType.
You could use the strategy pattern (Wikipedia) and a factory in combination.
public class Question
{
public Guid ID { get; set; }
public int Number { get; set; }
public QuestionType Type { get; set; }
public string Content { get; set; }
public Section Section { get; set; }
public IList<Answer> Answers { get; set; }
private IQuestionRenderer renderer;
public RenderHtml()
{
if (renderer == null)
{
QuestionRendererFactory.GetRenderer(Type);
}
renderer.Render(this);
}
}
interface IQuestionRenderer
{
public Render(Question question);
}
public QuestionRendererA : IQuestionRenderer
{
public Render(Question question)
{
// Render code for question type A
}
}
public QuestionRendererB : IQuestionRenderer
{
public Render(Question question)
{
// Render code for question type B
}
}
public QuestionRendererFactory
{
public static IQuestionRenderer GetRenderer(QuestionType type)
{
// Create right renderer for question type
}
}
Only the public properties need to be included in NHibernate.
The rendering is definitely a UI concern, so I'd separate that from the Question class and add a factory to isolate the switching logic (the QuestionControl base class inherits from WebControl and would contain the majority of the rendering logic):
RadioButtonQuestionControl: QuestionControl {
// Contains radio-button rendering logic
}
CheckboxListQuestionControl: QuestionControl {
// Contains checkbox list rendering logic
}
QuestionControlFactory {
public QuestionControl CreateQuestionControl(Question question) {
// Switches on Question.Type to produce the correct control
}
}
Usage:
public void Page_Load(object sender, EventArgs args) {
List<Question> questions = this.repository.GetQuestions();
foreach(Question question in Questions) {
this.Controls.Add(QuestionControlFactory.CreateQuestionControl(question));
// ... Additional wiring etc.
}
}
Stating the obvious: You could probably use a factory method to get the instance of the required rendered class and call render on that to get the required output.
The approach I would take is to create a separate Control (or a HtmlHelper method if you're in MVC) for each visual style you would like your questions to be rendered using. This separates the concerns of representing the question as an object and representing it visually neatly.
Then you can use a master Control (or method) to choose the correct rendering method based on the type of the Question instance presented to it.