What's the first line of the following code called?
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual IController Controller
{
get { return controller; }
set { controller = value; }
}
It's called an attribute. Attributes are used to describe properties, methods, etc. They serve to provide metadata, among other things.
In this case, the DesignerSerializationVisibility.Hidden attribute means that the Controller property isn't visible to the design-time serializer.
Positional parameters are parameters of the constructor of the attribute. They are mandatory and a value must be passed every time the attribute is placed on any program entity. On the other hand Named parameters are actually optional and are not parameters of the attribute's constructor.
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false,
Inherited = false)]
public class HelpAttribute : Attribute
{
public HelpAttribute(String Description_in)
{
this.description = Description_in;
this.verion = "No Version is defined for this class";
}
protected String description;
public String Description
{
get
{
return this.description;
}
}
protected String version;
public String Version
{
get
{
return this.version;
}
//if we ever want our attribute user to set this property,
//we must specify set method for it
set
{
this.verion = value;
}
}
}
[Help("This is Class1")]
public class Class1
{
}
[Help("This is Class2", Version = "1.0")]
public class Class2
{
}
[Help("This is Class3", Version = "2.0",
Description = "This is do-nothing class")]
public class Class3
{
}
more...
Related
My Custom Sitecore control inherits from Sitecore.Web.UI.HtmlControls.Control. This Class defines the Property Value as follows:
public virtual string Value {
get {
return this.GetViewStateString("Value");
}
set {
if (!(value != this.Value))
return;
this.SetViewStateString("Value", value);
}
}
My custom class is defined as follows:
public class ClientProfileSelector : Sitecore.Web.UI.HtmlControls.Control, IContentField {
...
public override string Value {
get {
return this.MyOwnValue;
}
set {
if (!(value != this.MyOwnValue))
return;
this.MyOwnValue = value;
}
}
...
}
The code of the entire class is available here.
My class is automatically instantiated by Sitecore, but I know it is running because I can step into other methods defined therein. For example the method GetValue() in my custom class calls the field Value like so:
public string GetValue() {
return string.IsNullOrEmpty(CalculatedValue) ? CalculatedValue : Value;
}
but when I step over it after adding breakpoints in both my definition and the base class' one, the execution stops in the base class.
What am I doing wrong?
I'm having a Property in the Remote Server named HasChar of the type Bool. I need to redefine it in my Derived class with some modification. But the Base Property didn't marked as Partial, abstract or extern. But I need to Redefine, How can I achieve? In the Derived Class, I need to access the HasChar Property of Base Class in the Derived Class, if the value is False, then I have to make the BlogText as String.Empty
Note: The Base Class is in Remote Server, I Can't able to Change it or
initiate for the Changes. The Base Class Property don't marked as
Partial, abstract or extern. Don't create any additional property to achieve this. Kindly give the solution related to Override or similar.
My Base Class
public class BlogBase
{
private string _blogText = string.Empty;
public string BlogText
{
get { return _blogText; };
set
{
_blogText = value;
HasChar = _blogText.Length >0 ? true : false;
}
}
public bool HasChar { get; set; }
}
My Derived Class : Rough Code
public class BlogChild : BlogBase
{
private bool _hasChar = false;
public bool HasChar
{
get { return _hasChar; };
set
{
_hasChar = value;
if(!_hasChar)
BlogText = string.Empty;
}
}
}
Hide the original property with the new keyword.
public new bool HasChar
{
private bool _hasChar;
get { return _hasChar; }
set
{
// do other stuff
_hasChar = value;
}
}
I want to validate condition on class definition in the build process and show build error in case that something is not validated.
In the build process attribute instance is created for each class that defined by this attribute.
I want to check something like for example that the class does not have more than 4 properties(just for example, this is not my intention). How can I get the type from the attribute constructor for each class?
(Without passing it as parameter).
Example:
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class ValidatePropertiesAttribute:ValidationAttribute
{
public ValidatePropertiesAttribute()
{
if(Validate()==false)
{
throw new Exception("It's not valid!! add more properties to the type 'x'.");
}
}
public bool Validate()
{
//check if there are at least 4 properties in class "X"
//Q: How can I get class "X"?
}
}
[ValidateProperties()]
public class ExampleClass
{
public string OnOneProperty { get; set; }
}
Is it possbile?
If not, is there any other way to do it?
(add validation to the build process and show errors in case that something was not validated)
This solution may work
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class ValidatePropertiesAttribute:ValidationAttribute
{
private Type TargetClass;
public ValidatePropertiesAttribute(Type targetClass)
{
TargetClass = targetClass;
if(Validate() == false)
{
throw new Exception("It's not valid!! add more properties to the type 'x'.");
}
}
public bool Validate()
{
//Use Target Class,
//if you need extract properties use TargetClass.GetProperties()...
//if you need create instance use Activator..
}
}
Use this attribute as follows
[ValidateProperties(typeof(ExampleClass))]
public class ExampleClass
{
public string OnOneProperty { get; set; }
}
Referencing to my previous question, the story begins in that fact that I have a bunch of svcutil-generated classes. They are generated from external WSDL. Here you go:
First request class:
public partial class getcarsRequest
{
[System.ServiceModel.MessageHeaderAttribute(Namespace = "http://svc.datadomains.com/revision123_2/")]
public CarsServiceApp.RequestHeader Header;
[System.ServiceModel.MessageBodyMemberAttribute(Name = "getcarsRequest", Namespace = "carinfo", Order = 0)]
public CarsServiceApp.getcars MessageWrap;
public getcarsRequest()
{
}
public getcarsRequest(CarsServiceApp.RequestHeader Header, CarsServiceApp.getcars getcarsRequest1)
{
this.Header = Header;
this.MessageWrap = getcarsRequest1;
}
}
public partial class getcars
{
private MessageType messageField;
private MessageDataGetcarsRequest messageDataField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Order = 0)]
public MessageType Message
{
get
{
return this.messageField;
}
set
{
this.messageField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Order = 1)]
public MessageDataGetcarsRequest MessageData
{
get
{
return this.messageDataField;
}
set
{
this.messageDataField = value;
}
}
}
public partial class MessageDataGetcarsRequest
{
private AppDataGetcarsRequest appDataField;
private AppDocumentType appDocumentField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Order = 0)]
public AppDataGetcarsRequest AppData
{
get
{
return this.appDataField;
}
set
{
this.appDataField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Order = 1)]
public AppDocumentType AppDocument
{
get
{
return this.appDocumentField;
}
set
{
this.appDocumentField = value;
}
}
}
public partial class AppDataGetcarsRequest
{
private string addressField;
private int codeField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Order = 0)]
public address address
{
get
{
return this.addressField;
}
set
{
this.addressField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Order = 1)]
public int code
{
get
{
return this.codeField;
}
set
{
this.codeField = value;
}
}
}
Second:
public partial class getdriversRequest
{
[System.ServiceModel.MessageHeaderAttribute(Namespace = "http://svc.datadomains.com/revision123_2/")]
public carsServiceApp.RequestHeader Header;
[System.ServiceModel.MessageBodyMemberAttribute(Name = "getdriversRequest", Namespace = "driverinfo", Order = 0)]
public carsServiceApp.getdrivers MessageWrap;
public getdriversRequest()
{
}
public getdriversRequest(carsServiceApp.RequestHeader Header, carsServiceApp.getdrivers getdriversRequest1)
{
this.Header = Header;
this.MessageWrap = getdriversRequest1;
}
}
public partial class getdrivers
{
private MessageType messageField;
private MessageDataGetdriversRequest messageDataField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Order = 0)]
public MessageType Message
{
get
{
return this.messageField;
}
set
{
this.messageField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Order = 1)]
public MessageDataGetdriversRequest MessageData
{
get
{
return this.messageDataField;
}
set
{
this.messageDataField = value;
}
}
}
public partial class MessageDataGetdriversRequest
{
private AppDataGetdriversRequest appDataField;
private AppDocumentType appDocumentField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Order = 0)]
public AppDataGetdriversRequest AppData
{
get
{
return this.appDataField;
}
set
{
this.appDataField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Order = 1)]
public AppDocumentType AppDocument
{
get
{
return this.appDocumentField;
}
set
{
this.appDocumentField = value;
}
}
}
public partial class AppDataGetdriversRequest
{
private string nameField;
private int customerCodeField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Order = 0)]
public name name
{
get
{
return this.nameField;
}
set
{
this.nameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Order = 1)]
public int customerCode
{
get
{
return this.customerCodeField;
}
set
{
this.customerCodeField = value;
}
}
}
This is just two entity generated by svcutil. There are another entities that like this two differs only by most underlying AppData property. I wrote a power shell script that preparing raw generated file renaming some fields but this is not enough to get all work done.
How can I compose classes unity? It seems like I should use parametrized interface...
I need united classes structure to devise common useful functions like checking that request is correct or create request from scratch.
Thanks in advance, guys! My brains are boiled about that stuff.
QUESTION EDIT #1
Ok, guys, here is that I would like to have. Let say we want to check any service method's request for correctness. If some request's AppData property isn't null we should consider that request as correct. Actually it would be better for us to have some common class' method for such checking. But how can we make that method if any request class has different AppData property types?
Let take a look at two generated classes and draw some imaginary path to each AppData properties.
For first class, getcarsRequest we have (in parentheses we has appropriate class type):
request (getcarsRequest) -> MessageWrap (getcars) -> MessageData
(MessageDataGetcarsRequest) -> AppData (AppDataGetcarsRequest)
For the second we have next path:
request (getdriversRequest) -> MessageWrap (getdrivers) -> MessageData
(MessageDataGetdriversRequest) -> AppData (AppDataGetdriversRequest)
So how can we redevise and reduce them to some generic interface? If we have an appropriate, common interface for that two classes we could write some CheckRequest(IRequest<T> request).
I hope I get some clarity here. Any advices/sentences will be very appreciated. If you have any questions for me please feel free to bring them to me.
As I understand it, you have two class structures that are effectively duplicated: car and driver. Instead of modifying the generated classes, you should focus on restructuring your input wsdl (which we havent seen yet).
In order to remove this duplication, consider making two Objects: car and driver and restructuring the wsdl operations in such a way that they can operate on either type of Object. In Object Oriented terms, both car and driver should inherit from the same base class that will have abstract methods that can be called by the wsdl operations. These abstract methods would then need to be implemented in the car and driver derived/concrete classes.
If you cannot edit your WSDL to provide a common type, I see two possibilities:
You could create generic wrapper classes that are parametrized with the known type. The classes would mimic the structure of the concrete classes (generated by svcutil) including their hierarchy. Then you wrap the raw object in the appropritate wrapper and use the wrapper from that point on.
Advantage: interaction with the wrapper classes are similar to the original (raw) objects without much runtime overhead.
Disadvantage: You need to create and maintain the class layout/hierarchy of the original (raw) objects as the WSDL changes.
Alternatively, you can use reflection to call the appropriate methods on the objects -- you will need to calculate the method names based on the concrete type (e.g. callFunction(o, "get", "car") to call ((GetCarsRequest)o).getCars()).
Advantage: you do not need to create and maintain a shadow type hierarchy to match the original type layout/hierarchy.
Disadvantage: reflection in general is much slower than achieving the same result via compiled bytecode.
Both of these approaches require you to know for sure at all times which type of object you are dealing with, which should not be an issue as that is the case already in your current setup.
Refactoring might be the best option, but if it isn't feasible, you can take advantage of the fact that they're partial and add an interface.
public IData<TRequest> {
T AppData { get; set; }
bool IsValid { get; }
}
public partial class MessageDataGetdriversRequest : IData<AppDataGetcarsRequest>
{
bool IsValid { get { this.AppData != null; } }
}
public partial class MessageDataGetdriversRequest: IData<AppDataGetdriversRequest>
{
bool IsValid { get { this.AppData != null; } }
}
Then you can do var data = getcars.MessageData; or var data = getdrivers.MessageData;, and then check data.IsValid.
It's also possible to implement IsValid as an extension method on this IData<T> instead of a property of IData, in which case you wouldn't even need to declare it for each class (but it would be a method, not a property).
public partial class MessageDataGetdriversRequest : IData<AppDataGetcarsRequest> { }
public partial class MessageDataGetdriversRequest: IData<AppDataGetdriversRequest> { }
public static bool IsValid(this IData<T> data)
{
return data.AppData != null;
}
I have a lot of similar classes generated by svcutil from some external WSDL file. Any class has a Header property and string property which named class name + "1".
For instance, I have classes: SimpleRequest that has Header property and SimpleRequest1 property.
Another one is ComplexRequest that has Header property and ComplexRequest1 property.
So, I want to create a common interface for such classes. So, basically I can define something like that:
interface ISomeRequestClass {
string Header;
// here is some definition for `class name + "1"` properties...
}
Is it possible to define such member in interface?
Here is post edit goes...
Here is sample of generated class:
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
[System.ServiceModel.MessageContractAttribute(IsWrapped=false)]
public partial class SimpleRequest
{
public string Header;
[System.ServiceModel.MessageBodyMemberAttribute(Name="SimpleRequest", Namespace="data", Order=0)]
public SimpleRequestMsg SimpleRequest1;
public SimpleRequest()
{
}
public SimpleRequest(string Header, SimpleRequestMsg SimpleRequest1)
{
this.Header = Header;
this.SimpleRequest1 = SimpleRequest1;
}
}
POST EDIT 2
I changed definition of this annoying +1 property to represent real actual picture. It's all has different class types. So how can I pull it out to common interface?
POST EDIT 3
Here is coupled question that could bring more clarify.
EDIT (after seeing your code sample): Technically speaking, your code does not have a Header property, it has a Header field. This is an important difference, since you cannot specify fields in an interface. However, using the method described below, you can add properties to your classes that return the field values.
Is it possible to define such member in interface?
No, interface names cannot be dynamic. Anyway, such an interface would not be very useful. If you had an instance of class ISomeRequestClass, what name would you use to access that property?
You can, however, use explicit interface implementation:
interface ISomeRequestClass {
string Header { get; set; }
string ClassName1 { get; set; }
}
class SomeClass : ISomeRequestClass {
string Header { ... }
string SomeClass1 { ... }
// new: explicit interface implementation
string ISomeRequestClass.ClassName1 {
get { return SomeClass1; }
set { SomeClass1 = value; }
}
}
You could define your interface more generally:
interface ISomeRequestClass {
string HeaderProp {get; set;}
string Prop {get; set;}
}
And your concrete classes could be extended (in an extra code file) by mapping interface members to class fields like so:
public partial class SimpleRequest : ISomeRequestClass
{
public string HeaderProp
{
get
{
return Header;
}
set
{
Header = value;
}
}
public string Prop
{
get
{
return SimpleRequest1;
}
set
{
SimpleRequest1= value;
}
}
}
Putting aside for a moment the naming of your classes and properties.
If you're looking to create an interface with a property relevant to your specific +1 type, you have a couple of options.
Use a base class for your +1's
If both of your +1 classes inherit from the same base class you can use this in your interface definition:
public interface IFoo
{
[...]
PlusOneBaseType MyPlusOneObject{get;set;}
}
Create a generic property on your interface
This method allows you to specify the type for the +1 property as a generic parameter:
public interface IFoo<TPlusOneType>
{
[...]
TPlusOneType MyPlusOneObject{get;set;}
}
Which you might use like:
public class SimpleRequest : IFoo<SimpleRequest1>
{
[...]
}
Update
Given that your classes are partial classes, you could always create a second (non machine generated) version of the partial class that impliments your interface.
You mentioned svcutil so I assume you are using these classes as WCF DataContracts?
If that is the case then you could make use the name property of DataMemberAttribute.
interface IRequest
{
string Header { get; set; }
string Request1 { get; set; }
}
[DataContract]
class SimpleRequest : IRequest
{
[DataMember]
public string Header { get; set; }
[DataMember(Name="SimpleRequest1"]
public string Request1 { get; set; }
}
[DataContract]
class ComplexRequest : IRequest
{
[DataMember]
public string Header { get; set; }
[DataMember(Name="ComplexRequest1"]
public string Request1 { get; set; }
}
If you are concerned giving yourself more work when you regenerate the code at some point in the future, then I recommend you write a PowerShell script to do this transformation automatically. After all svcutil is just a script written by some guy at Microsoft. It is not magic or "correct" or "standard". Your script can make a call to scvutil and then make a few quick changes to the resulting file.
EDIT (After seeing your edit)
You are already using MessageBodyMemberAttribute's Name property so just change this:
public string SimpleRequest1;
To
public string Request1;
Do you actually need these classes to have a common interface? I'd be tempted to instead create a wrapper interface (or just a concrete class) which could then use reflection to access the fields in question:
// TODO: Make this class implement an appropriate new interface if you want
// to, for mocking purposes.
public sealed class RequestWrapper<TRequest, TMessage>
{
private static readonly FieldInfo headerField;
private static readonly FieldInfo messageField;
static RequestWrapper()
{
// TODO: Validation
headerField = typeof(TRequest).GetField("Header");
messageField = typeof(TRequest).GetField(typeof(TRequest).Name + "1");
}
private readonly TRequest;
public RequestWrapper(TRequest request)
{
this.request = request;
}
public string Header
{
get { return (string) headerField.GetValue(request); }
set { headerField.SetValue(request, value); }
}
public TMessage Message
{
get { return (TMessage) messageField.GetValue(request); }
get { messageField.SetValue(request, value); }
}
}
You could use expression trees to build delegates for this if the reflection proves too slow, but I'd stick to a simple solution to start with.
The advantage of this is that you only need to write this code once - but it does mean creating a wrapper around the real request objects, which the partial class answers don't.