Inheritance of a .Net interface in C#: How to access base members - c#

Inheritance of a .Net interface: How to access to base properties
I want to create my own category class inherited from Microsoft.Office.Interop.Outlook.Category interface but I am trying to access members of the base interface without success.
I tried base.Name and this.Name both give me:
Error 2 'object' does not contain a definition for 'Name'
Using VS 2013, .Net 4.5
Code:
using System;
using Outlook = Microsoft.Office.Interop.Outlook;
namespace MyCategory
{
public class MyCategory : Outlook.Category
{
private string colorName;
public string ColorName
{
get
{
return this.colorName;
}
set
{
//Name is a member of Outlook.Category
//https://msdn.microsoft.com/en-us/library/office/microsoft.office.interop.outlook.category_members.aspx
this.colorName = base.Name;
//
}
}
}
}

So far I see on your code, you didn't implement interface. You're not inheriting from a class but following contract established by Outlook.Category interface. There is no "base" members here, you have to add members to your class.
If you put mouse cursor above Outlook.Category it should offer to implement it for you.
I recommend you to take a deeper look to how interfaces work on C#

You are mistaking implementing an interface with object inheritance. Even though they both use the same syntax, they are very different.
An interface is a contract to allow many different implementations of the same general methods and properties. It is a guarantee that the class you wrote supports certain actions. You have to write the implementations for interfaces. This allows others at a higher level to not care about the details of how something gets accomplished, yet it allows them to know it will get accomplished.
Object inheritance allows you to use a parent class's (non-private) stuff. It's really taking a parent class and adding more features. In fact, in Java, this is known as "extending" a class. Find a class that already implements the interface Outlook.Category and inherit from that class and then call base.Name(). Then you could override or extend any additional behavior that you need.
I'm not familiar with the Outlook namespace, but the CategoryClass seems to be a class that implements your interface. You could try inheriting from that.

What is it exactly that you are trying to do? Add a new category in Outlook? In that case, you simply need to access Outlook category storage (either the registry or the default store in the profile).
Take a look at the IPM.Configuration.CategoryList hidden message in the Calendar folder - you can see it using OutlookSpy (I am its author): go to the Calendar folder, click IMAPIFolder button on the OutlookSpy ribbon, go to the "Associated Contents" tab, find the message with PR_MESSAGE_CLASS property = "IPM.Configuration.CategoryList", double click on it. The data will be in the PR_ROAMING_XMLSTREAM property. That hidden message can be accessed using MAPIFolder.GetStorage in the Outlook Object Model.
You can also use Redemption (I am also its author) to add a new category - see the RDOCategories object. Something like the following will do the job (VBA):
set vSession = CreateObject("Redemption.RDOSession")
vSession.MAPIOBJECT = Application.Session.MAPIOBJECT
set vStore = vSession.Stores.DefaultStore
set vCategories = vStore.Categories
set vCategory = vCategories.Add("Redemption Category", olCategoryColorPeach)

Related

Wrapping C# classes to use with polymorphism through a common interface

I've got several C# classes each with similar properties.
(They're part of an SDK and their code can’t be changed.)
Person.Name
Product.Name
Order.Name
I want to use these classes polymorphically, but they don’t implement a common interface or derive from a common base class, so that’s not possible.
To get around this, I’d like to wrap each one in another class that does implement a common interface, and wire-up each class property to its corresponding interface property.
What would be a suitable name for the wrapper classes? Wrapper, Decorator, Adaptor, Proxy? Does this pattern have a name? Is there a better approach?
(I don't want to use dynamic duck-typing or an impromptu interface.)
It looks like Adapter, because you are adapting the existing interfaces to the specific requirements.
(I don't want to use dynamic duck-typing or an impromptu interface.)
So what is wrong with a NamedObject?
public class NamedObject
{
public string Name { get; set; }
}
It literally says what it is, nothing less, nothing more.
I'd stick with CodeCaster's idea, and perhaps with a dash of Func<T> for no other reason than I get withdrawal symptoms when I don't use angle brackets...
public class NamedEntity
{
public string Name { get { return _getName(); } }
private Func<string> _getName;
public NamedObject(Func<string> getName)
{
_getName = getName;
}
}
And then call thus:
var named = new[]
{
new NamedEntity(() => person.Name),
new NamedEntity(() => product.Name),
new NamedEntity(() => order.Name)
};
The added benefit with this is when the value of the property changes on the target object, it changes within the NamedEntity reference too via the Func, this means within the life span of the objects you can get away with wrapping them once. You can also do the inverse with Funcs that set values as well as get, and can adapt more properties.
I am not immediately sure what pattern this represents (if any), though I would guess Adapter pattern (which is a type of wrapper pattern). However, it could also be argued to be a Proxy pattern. Not sure really.
Maybe you can just change the namespace and keep the names of the original classes.
Technically, I think the most correct name would be Adapter, see this question.
Adapter is used when you have an abstract interface, and you want to map that interface to another object which has similar functional role, but a different interface.
You don't have abstract interface, but "similar functional role, but a different interface".

Designing a contract for plugins

I was thinking about designing a proper contract for future plugins creation for an application I'm currently working on. Basically the idea is to define an interface, but I want the application to be aware of plugins that currently presented to the system and to show the user a nice list of plugins with their names and a brief descriptions which ofcourse the developer of the plugin should provide, the user of the application shouldn't be able to alter this easily so an additional config file is not an option. I don't want to use the class name of filename of the assembly for this. Also I think that it should be accessable without instantiating the plugin, but maybe through reflection, something like: assembly.GetType(type).GetProperty("Name").GetValue(null, null).ToString();. Ofcourse I could provide some logic to check for existance something like if(assembly.GetType(type).GetProperty("Name") != null), but this is not a good idea either, because if the property does not exist the end user won't have an idea of what that plugin does, not even what it's name is.
Now, it should behave like a static property, but static is not overridable so it seems that I cannot declare it as a part of an interface nor in an abstract class. Maybe I'm on wrong way, and it only looks like a static property and I can achive this functionality through another approach. So the brief question might be "How to enforce the third party developer to provide some meta information about his plugin". Please advise.
You could try with two interfaces:
IAddIn for be the main interface that all add-ins will implement.
IAddInInfo for be the interface providing the metadata of the add-in (name, publisher, description version etc.)
Each add-in should implement both of these. An IAddInInfo implementation could be like this:
public class ScannerAddInInfo : IAddInInfo
{
public string Name { get { return "Scanner"; } }
public string Description { get { return "Add-in for acquiring images from a scanner device"; } }
}
To ensure that all implementations of add-ins come with metadata, you can make IAddIn a generic interface like:
public interface IAddIn<T> where T : IAddInInfo
{
T Info { get; }
//Continue with the rest of the members you would want every add-in to have.
}
Then the scanner add-in implementation would be:
public class ScannAddIn : IAddIn<ScannerAddInInfo>
{
private ScannerAddInInfo _info = new ScannerAddInInfo();
public ScannerAddInInfo Info { get { return _info; } }
//Continue with the rest of the IAddIn implementation.
}
Then you could load the add-in assembly from a special add-in folder and create instances of the types implementing IAddInInfo and show the info from the discovered add-ins in your application. Note that no add-ins are created yet. To do so you will need to add some more reflection to find the types implementing IAddIn<ScannerAddInInfo>.
To make this simpler you could add the add-in type name to the IAddInInfo interface or something like that.
The only drawback to this approach is that you will have to load all assemblies found in your special add-in folder even if they do not include any add-ins.
To avoid this you could try Mono.Cecil. You then will have to do something like this:
AssemblyDefinition ad = AssemblyDefinition.ReadAssembly(assemblyPath);
foreach (TypeDefinition td in ad.MainModule.GetTypes())
{
if (td.BaseType != null && td.BaseType.FullName == "MyNamespace.MyAddInBase")
{
return true;
}
}
To load the assemblies you can use Assembly.LoadForm and to create instances of the add-ins and add-in infos, one of the Activator.CreateInstance overloads.
Good luck.
To add some 'meta data' to your plugins, you can use attributes. Create a custom attribute for your plugins and read out the information with reflection and show it in your application.
More info about attributes:
Creating Custom Attributes (C# and Visual Basic)
Accessing Attributes by Using Reflection
The thing you should do is basically define your interface and expect other people to implement their concrete classes and give that runtime object to you somehow (your predefined methods, configuration etc.)
But there is some mechanism called dependency injection. That allows you to define your interface and your entry points while a "system" takes care of matchmaking your entry points and implementers' concretes. There is "System.ComponentModel.Composition" namespace for this purpose.
I knew there was a framework called "Unity" doing such job. I guess composition namespace is somewhat a simplified version of unity. You can check help for "ImportAttribute" and "ExportAttribute" classes for some cue.

Interface: Setter without a Getter

I came across an interface recently that only defined a setter like so:
public interface IAggregationView
{
DataTable SetSiteData { set; }
}
I queried this, and it is believed that this is one of the practices advocated by Microsoft for WebPart design (for SharePoint). In fact this example is directly copied from their examples.
I see this as a bad pattern, I don't see why someone should be able to set a value, and then not be able to read it again, and I believe a setter should always be accompanied with a getter (but not necessarily the other way around).
I'm wondering if anyone can explain the benefit of only having a setter, why Microsoft might be suggesting it in this case, and if it's really a good pattern to be following?
There are two scenarios I can see where this might be reasonable:
it is not possible get the value, for example a password; however, I would replace that with a void SetPassword(string) method, personally
the API it is designed for has no requirement to ever read the value, and it is being restricted purely to expose the minimum required API
Re my first point, a Set... method may not be ideal if the consuming API is essentially an automated mapper that assigns values to properties; in that scenario properties would indeed be preferable.
Re your "I don't see why someone should be able to set a value, and then not be able to read it again" - by the same point, however, it could be argued that someone setting the value already knows the value (they set it), so they have no requirement to do this.
But yes; it is very unusual to have a set-only property.
The role of get and set in interface properties is slightly different from those in classes.
public interface IAggregationView
{
DataTable SetSiteData { set; }
}
class AggregationViewImp : IAggregationView
{
public DataTable SetSiteData { get; set; } // perfectly OK
}
The interface specifies that the property should at least have a public setter. The definition and accessibility of the getter is left to the implementing class.
So if the interface contract only needs to write, get can be left open. No need to demand a public getter.
As a consequence, you cannot really specify a read-only property in interfaces either. Only 'at least read access'.
interface IFoo
{
int Id { get; }
}
class Foo : IFoo
{
public int Id { get; set; } // protected/private set is OK too
}
I can imagine using it for (manual) dependency injection. A class may need to have a collaborator injected that it only uses internally. Of course one would normally choose to do this in the class' constructor, but there may be times when one would wish to change the collaborator at runtime.
Classes that implement the interface may add a getter. Most uses of the property may be via an implementing class, not via the interface itself. In which case most code has the ability to get and set the property. The only reason for the interface may be that there is some common code that accesses a common subset of the methods/properties of a family of classes. That code only requires the setter, not the getter. The interface documents that fact.
An interface is just a facility for declaring a group of operations that are "atomically needed" (e.g. if you need to call method A, you'll need to read property B and set property C).
So as always, it depends.
In my experiences such interfaces crop up due to some special need, not for architectural reasons. For example in ASP.NET applications people sometimes make the Global.asax generated type derive from such an interface when they want to maintain global state. Someone might create an initialization value in a separate part of the application and need to publish it to a global place.
I usually like to replace a set-only property with a SetXxx method and make the method check that it is called at most once. That way I clearly enforce "initialization style" which is much less of a smell (imho).
Certainly one cannot set to never produce such a thing but it is to be avoided and will certainly raise questions during code review.

Using the generated .net classes to extend own classes. HowTo?

I used the OWLGrinder to create the assembly and imported the library into my project. That works fine. Now I want to write my own set of classes. Therefore I extended these with the equivalent of the assembly. But it just doesn't work.
The ontology holds a class named ManagementObject.
I created another Class (C#) called RealWorldObject:
public class RealWorldObject : ManagementObject
{
public RealWorldObject(string uri) : base(uri) { }
public RealWorldObject(string uri, RdfDocument rdfdocument) : base(uri, rdfdocument) { }
public RealWorldObject(RdfDocument rdfdocument) : base(rdfdocument) { }
public String getClassName()
{
return this.OwlClassName;
}
public static RdfDocument addRealWorldObjectIndividualt(RdfDocument rdfDocument)
{
Vehicle vehicle = new Vehicle("vehicle1", rdfDocument);
FixedEvent fxE1 = new FixedEvent("autoGekauft", rdfDocument);
fxE1.agent = new xmlns.com.foaf._01.Person("robert", rdfDocument);
vehicle.hasFixedEvent = fxE1;
return rdfDocument;
}
Which leads to the error:
ObjectManagement.Object.RealWorldObject does declare one (and only one) OwlClassAttribute. This is an implementation bug of the plugin.
How else should I extend the generated classes by the OWLGrinder.
Thx it is a long time ago that I used C#, so I'm kind of rusty.
The auto-generated classes produced by OwlGrinder.exe have not been designed for inheritance in mind. I am not saying it is wrong, it is just not designed for that. The auto-generated classes contain plenty of metadata defined as class attributes and inheritance hides all of that. The infrastructure counts on the presence of these attributes and if they are hidden, you get these runtime error messages.
Using Visual Studio Object Browser, take a look of the attributes over the auto-generated classes. OwlClassAttribute, SubClassOfAttribute, LightVersionAttribute are certainly mandatory. You may simply copy/paste the class attributes of ManagementObject on the top of your RealWorldObject class. I assume, it will work. But again, you might bump into additional show stoppers, as you do not follow the default routes ROWLEX has been designed for. This is a bit living on the edge :)
Instead of inheritance, you might consider reverse engineering your auto-generated assembly to C# using Reflector or other tools. Having the source code in your hand, you may modify the generated classes directly. You might make your ManagementObject class partial, and implement your additional methods in a separate file.

Class hierarchy in C#: how to do it correctly? ('friend' keyword wanted)

I have a class:
public class MyClass {
private List<string> folderList;
// .... a lot of useful public methods here.....
}
Everything is fine. The list of folders is encapsulated, the class is accessible through public methods. OK. Now I need an "options" form that allows a user to choose folders for MyClass. There is a catch: new Setup class must have access to private folderList field (or I have to provide public methods to get and set the folder list - it's essentially the same). In old good C++ I would use 'friend' feature because nobody but Setup class may access folderList. But there is no 'friend' feature in C# (I'm a newbie in the C# world).
P.S. Actually I just made folderList public, but I feel there is a better solution.
Thanks.
You can use "internal" keyword to make your method available only within your assembly/project and if you want to access your internal methods in other project or assembly then you can use "InternalsVisibleTo" attribute, where you can access your internals only in that assembly for which you define this attribute.
MSDN Internal Keyword
I believe the keyword you're looking for is internal. It is loosely equivilent to C++'s friend.
Internal provides assembly-level visibility.
Paired with Femaref's suggestion of using a Property, and you should have your full solution.
I am not sure if this is what he/she wanted. He/she did not put the requirement that the potential client will be in current assembly... Accordingly, when using friend in c++ (which was never considered a good style) you must know the exact type of the class which will be entitled to access the member. If this class is not part of the program you are writing, you cannot grant access this way.
If you want conditional access to some property or method of an instance of a class, you will need to implement some kind of entitlement mechanism, for example:
public IList<Folder> GetFolderList(Object pClient, IEntitlementService pService) {
if (pService.IsEntitledToAccess(this, pClient) {
return folderList;
} else {
throw new AccessNotGrantedException("...");
}
}
I believe there are built-in utilities in the .Net framwork for that purpose, just go and google (or bing)...
As an exact answer to the question I would suggest the following - create a separate interface IFolderList:
interface IFolderList
{
IList<string> FolderList { get; }
...
}
Well, you can add other required members to interface
In the class MyClass implement this interface explicitly.
As a result, the class Setup can gain access to data through an explicit cast to an interface IFolderList or work only with these interface.
An alternative to making an internal method to be used by your Setup class would be to use the Visitor pattern and add a method that takes a Setup class instance as a parameter, then uses the private folderList to initialize/change Setup state as required. Of course that would require the appropriate public methods on the Setup class, so might not fit your needs.
Making folderList field public is the worst case. Exposing implementation details through public fields or through poorly designed public property (there are no differences for collections between public fields and public property with getter and setter).
With public fields you can't promote a field to be a property when you want to add validation, change notification, put it into an interface or change your collection type from one type to another.
BTW, Jeffrey Richter in annotation to Framework Design Guideline mentioned that "Personally, I always make my fields private. I don't even expose fields as internal, because doing so would give me no protection from code in my own assembly"
I think the best way to add explicit interface that expose strict abstraction to MyClass clients.
For example, you may add two separate methods to retrieving folders and to adding new folder to this storage:
class MyClass {
//You should return IList<string>
public IList<string> MyList {get {return myList;} }
//Or even IEnumerable<string>, because you should return
//as minimal interface as your clients needs
public IEnumerable<string> MyList {get {return myList;} }
//You may expose this functionality through internal
//method, or through protected internal method,
//but you should avoid direct access to your implementation
//even for descendants or another classes in your assembly
public void AddElement(string s) {myList.Add(s);}
private List<string> myList;
}
That's what properties are for in C#:
public class MyClass
{
private List folderList;
public List FolderList
{
get {return folderList;}
set {folderList = value;}
}
}
Properties encapsulate the private fields, provide possibilites for validation while setting. Also, you should read up on Generics (abit like templates in c++) and use List<T> instead of List to have a strongly typed collection.
However, you probably wont be able to achieve what you plan unless Setup derives from MyClass. In that case, you can use a protected field.

Categories