Visual Studio 2010/2012/2013, Class Diagram: how to show interface as base class, not as "lillypop"? - visual-studio-2010

Since the interface is already on the diagram I would like to show inheritance reference explicitly. But I can't find how...

There is a bug in VS 2005 up to 2012 that won't allow it to work.
I have a work arround that might trick it into drawing the inheritance for interfaces.
Say your interface is called IMyInterface. You have to replace it with an abstract class implementing that interface and use it instead of your interface. The code would make use of the conditional compilation and will look like this:
//to generate class diagram, add 'CLSDIAGRAM' to the conditional symbols on the Build tab,
// or add '#define CLSDIAGRAM' at the top of this file
#if CLSDIAGRAM
#warning CLSDIAGRAM is defined and this build should be used only in the context of class diagram generation
//rename your interface by adding _
public interface IMyInterface_
{
int MyProperty { get; }
void MyMethod();
}
//this class will act as an interface in the class diagram ;)
public abstract class IMyInterface : IMyInterface_ // tricks other code into using the class instead
{
//fake implementation
public int MyProperty {
get { throw new NotImplementedException(); }
}
public void MyMethod()
{
throw new NotImplementedException();
}
}
#else
// this is the original interface
public interface IMyInterface {
int MyProperty { get; }
void MyMethod();
}
#endif
That's likely to show it as you wish.
In your case IMyInterface will become IMedicine.

Related

How do you create a simple Automation Extender for Visual Studio with UITypeEditor

In Visual Studio when you select project or project items in the solution explorer there are times when you might want to add custom properties to the properties window(the window that pops up when you press F4). Also, to fill in the values of those properties I need to add a button to pop up a form so I can collect information from the user at design time.
What is the simplest implementation of this so I can get started?
How would I create a user interface to collect the value some how by using UITypeEditAttribute?
This is the simplest implementation I could come up with.
Since this is an advanced topic, it is implied that you feel comfortable with completing all the steps before you start the implementation(these are all common programming tasks).
If anything is not clear enough just comment and I will try to simplify. Note that this is configured to create a custom property for a Visual C# file within visual studio. When you run or debug your visual studio package followed by clicking any .cs file, the custom property should show in the properties window. The comments provided are required instructions.
Create a Visual Studio package.
Create an interface that implements the custom properties that you would like to add to the properties page.
Create a class that implements the custom property interface and decorate the custom property with attributes.
Create class that implements IExtenderProvider interface and override GetExtender and CanExtend methods.
Create a new class that inherits from UITypeEditor and override GetEditStyle and EditValue methods.
Let's get started.
1. Create Package in visual studio.
Package.cs
// ...
public sealed class ThePackage : Package
{
private DTE2 Host;
private ObjectExtenders _extensionManager;
private MyExtenderProvider _extenderProvider;
protected override void Initialize()
{
Host = (DTE2)Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(SDTE));
_extenderProvider = new MyExtenderProvider();
_extenderProviderCookie = Host.ObjectExtenders.RegisterExtenderProvider(VSConstants.CATID.CSharpFileProperties_string,
"MyExtenderProvider", _extenderProvider);
}
protected override void Dispose(bool disposing)
{
Host.ObjectExtenders.UnregisterExtenderProvider(_extenderProviderCookie);
_extenderProvider = null;
base.Dispose(disposing);
}
}
2. Create class that implements your desired custom properties.
[ComVisible(true)] // Important!
public interface IMyDynamicExtender
{
String NewProperty { get; set; }
}
3. Create a class that implements the custom property interface.
[ComVisible(true)] // Important!
public class NewPropertyExtender : IMyDynamicExtender, IDisposable
{
// These attibutes supply the property with some information
// on how to display and which UITypeEditor to use.
[DisplayName("New Property")]
[Category("New")]
[Description("Specifies the new property")]
[Editor(typeof(CustomUiTypeEditor), typeof(UITypeEditor))]
public String NewProperty { get; set; }
private readonly IExtenderSite _extenderSite;
private readonly int _cookie;
private bool _disposed;
public NewPropertyExtender(IExtenderSite extenderSite, int cookie)
{
_extenderSite = extenderSite;
_cookie = cookie;
}
public void Dispose()
{
Dispose(true);
// take the instance off of the finalization queue.
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (_disposed) return;
if (disposing && _cookie != 0)
{
_extenderSite.NotifyDelete(_cookie);
}
_disposed = true;
}
}
4. Create class that implements [IExtenderProvider] interface and override [GetExtender] and [CanExtend] methods.
public class MyExtenderProvider : IExtenderProvider
{
private IMyDynamicExtender _extender;
public object GetExtender(string extenderCatid, string extenderName,
object extendeeObject, IExtenderSite extenderSite,
int cookie)
{
return _extender = CanExtend(extenderCatid, extenderName, extendeeObject) ?
new NewPropertyExtender(extenderSite, cookie) : null;
}
public bool CanExtend(string extenderCatid, string extenderName, object extendeeObject)
{
// Some implementation will be here in the real world.
return true;
}
}
5. Create a new class that inherits from [UITypeEditor] and override [GetEditStyle] and [EditValue] methods.
public class CustomUiTypeEditor : UITypeEditor
{
public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
{
return UITypeEditorEditStyle.Modal;
}
public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
{
// Use the result of a dialog or something else here.
return "HELLO WORLD";
}
}

Does Subject.Subscribe only work in a static instance (or am I missing something)

I'm mucking about with reactive extensions and Iv'e hit a snag that I can't for the life of me work out what the cause is.
If I use a .NET 4 console mode app, where everything is static as follows:
using System;
using System.Reactive.Subjects;
using FakeDal;
using FakeDal.Entites;
using RxProducer;
namespace Runner
{
class Program
{
private static readonly Subject<DaftFrog> _subject = new Subject<DaftFrog>();
private static readonly Repository<DaftFrog> _frogRepo = new Repository<DaftFrog>();
static void Main()
{
_subject.Subscribe(RespondToNewData);
}
private static void RespondToNewData(DaftFrog frog)
{
_frogRepo.Save(frog);
}
}
}
DaftFrog is just a test class in my fake DAL class, this is a simple .NET 4 Class library project, the DaftFrog class, is a simple poco with a few fields in, the dal.save method just simply does a console.WriteLine of a field in the DaftFrog object.
Both classes are just simple stand in's for the real things once I get around to making the RX code work.
Anyway, back to the problem, so the code above works fine, and if I do a few
_subject.OnNext(new DaftFrog());
calls, the fake dal class, prints out what I expect and everything works fine...
HOWEVER>....
If I then transport this code as is, to a class library, and then new up that class library from within my "static program" as follows:
using System.Reactive.Subjects;
using FakeDal;
using FakeDal.Entites;
namespace RxProducer
{
public class Producer
{
private readonly Subject<DaftFrog> _subject = new Subject<DaftFrog>();
private readonly Repository<DaftFrog> _frogRepo = new Repository<DaftFrog>();
private int _clock;
public void Start()
{
_subject.Subscribe(RespondToNewData);
}
public void Stop()
{
}
public void Tick()
{
if(_clock % 5 == 0)
{
DaftFrog data = new DaftFrog();
_subject.OnNext(data);
}
_clock++;
}
private void RespondToNewData(DaftFrog frog)
{
_frogRepo.Save(frog);
}
}
}
And then use that class in my program
using System;
using RxProducer;
namespace Runner
{
class Program
{
private static readonly Producer _myProducer = new Producer();
static void Main()
{
_myProducer.Start();
while(!line.Contains("quit"))
{
_myProducer.Tick();
line = Console.ReadLine();
}
_myProducer.Stop();
}
}
}
Then my project fails to compile.
Specifically it fails on the line:
_subject.Subscribe(RespondToNewData);
in the RxProducer class library, mores the point, the error the compiler throws back makes little sense either:
Error 1 The best overloaded method match for 'System.Reactive.Subjects.Subject<FakeDal.Entites.DaftFrog>.Subscribe(System.IObserver<FakeDal.Entites.DaftFrog>)' has some invalid arguments H:\programming\rxtesting\RxProducer\Producer.cs 17 7 RxProducer
Error 2 Argument 1: cannot convert from 'method group' to 'System.IObserver<FakeDal.Entites.DaftFrog>' H:\programming\rxtesting\RxProducer\Producer.cs 17 26 RxProducer
At first I thought that it might have been the static thing, so I made everything in the class library static, and that made no difference at all.
Iv'e really not done much with Rx until now, but I work with C# and VS 99% of the time, so I'm aware that the error is telling me it can't convert a type of some description, I just don't understand why it's telling me that, esp when the code works perfectly in the static program, but not in a class library.
Shawty
UPDATE
Second thoughts, I just know there are going to be those who insist that I post the fakedal and daft frog definitions, even though IMHO they won't be required, but to pacify the hordes of pretenders who will ask here they are :-)
using System;
namespace FakeDal
{
public class Repository<T>
{
public void Save(T entity)
{
Console.WriteLine("Here we write T to the database....");
}
}
}
namespace FakeDal.Entites
{
public class DaftFrog
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsTotalyDaft { get; set; }
}
}
Include using System; into file where you have Producer, this will help to convert RespondToNewData to IObserver<T>.
Sounds like the compiler is having trouble inferring the Action...might be missing a using statement for the relevant extension method. Alternatively, try either of:
_subject.Subscribe ((Action<DaftFrog>) RespondToData);
Or:
var obs = Observer.Create ( I forget the overload );
_subject.Subscribe( obs);

Windows Phone - Using generic class for PhoneApplicationPage

I have a Page which consist of AddPage.xaml and AddPage.xaml.cs. I want to create a generic class AddPage which extends from PhoneApplicationPage to outsource some repetitive code like Save or Cancel.
If I change the base class from PhoneApplicationPage to my new generic class, I get this error: Partial declarations of 'AddPage' must not specify different base classes.
To accomplish this you need to do the following.
First, create your base class
public class SaveCancelPhoneApplicationPage : PhoneApplicationPage
{
protected void Save() { ... }
protected void Cancel() { ... }
}
Then, your AddPage needs to be modified to inherit from the base class. The main places this is needed is within the code (AddPage.xaml.cs) AND within the xaml
Code:
public partial class AddPage : SaveCancelPhoneApplicationPage { ... }
Xaml:
<local:SaveCancelPhoneApplicationPage
x:Class="MyPhone.Namespace.AddPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MyPhone.Namespace"
<!-- other xaml elements -->
</local:SaveCancelPhoneApplicationPage>
UPDATE: Info added based on comments
If you need to have generic like functionality and you must use the Page to do this (rather than a ViewModel) then you can still do this using generic methods
public abstract class SaveCancelPhoneApplicationPage : PhoneApplicationPage
{
protected override void OnNavigatedTo(blaa,blaa)
{
var obj = CreateMyObject();
obj.DoStuff();
}
// You should know what your objects are,
// don't make it usable by every phone dev out there
protected MyBaseObject MyObject { get; set; }
protected T GetMyObject<T>() where T : MyBaseObject
{
return MyObject as T;
}
}
public class AddPage : SaveCancelPhoneApplicationPage
{
public AddPage()
{
MyObject = new MyAddObject();
}
}
In order to outsource some functions you just declare some add class which does the common work. Having another page doesn't do that work.
public class Add
{
public bool SaveContent(string filename, string content)
{
....//some content
return true;
}
public string ViewContent(string filename)
{
string content="";
.....
return content;
}
}
Add this part of code where you thought it is redundant.
Add obj=new Add();
obj.SaveContent("myfile.txt","Hello.This is my content.");
string content("myfile.txt");
Tell me if this is what you intend or not.

Can Ninject resolve abstract dependencies after the object is initialised?

Does anyone know if it's possible to use Ninject to resolve any unresolved abstract dependencies outside of the instantiation process? I've just been looking into constructor injection vs property/method/field injection, but it looks to me as though Ninject is still expecting to be the creator of the type using the IKernel.Get<>() method.
Basically, we're using MVC3 to build our product, and we've come up against a situation where we want the default ModelBinder to map form values to an instance of the object, and then be able to call a method on the submitted ViewModel that is dependent on an abstract interface e.g.
public class InviteFriend {
[Required]
public string EmailAddress { get; set; }
public void Execute() {
var user = IUserRepository.GetUser(this.EmailAddress);
if (user == null) {
IUserRepository.SaveInvite(this.EmailAddress);
}
MailMessage toSend = new MailMessage(); // Obviously some logic to prepare the body, subject and other mail properties
SmtpClient.Send(toSend);
}
}
where the controller action would receive InviteFriend as the method argument. We want Ninject to be able to resolve that IUserRepository dependency, but I can't quite work out how to since the object itself is instantiated by the MVC ModelBinder rather than Ninject IKernel.Get<>().
Maybe the solution is a Ninject-based ModelBinder, or does that seem a really bad idea?
EDIT TO ADD: After the comments below, I realise that my hastily mocked-up code sample doesn't really reflect what we're facing. I've updated the code sample to reflect that the logic for InviteFriend.Execute() is more complex than just calling a method on one repository. Potentially, this is logic representing a discrete task that could co-ordinate interactions between multiple different domain objects and multiple repositories. The repositories are defined abstractly, and ideally would be resolved by Ninject.
I think what you are looking for is somewhat the following scenario:
public class InviteFriend {
[Required]
public string EmailAddress { get; set; }
// More information
}
public interface ICommand {
void Execute();
}
public class InviteFriendCommand : ICommand
{
public InviteFriend(InviteFriend info, IUserRepository userRepo, IMailSender mailSender) {
this.inviteFriend = info;
this.userRepo = userRepo;
this.mailSender = mailSender;
}
public void Execute() {
var user = this.userRepo.GetUser(this.inviteFriend.EmailAddress);
if (user == null) {
this.userRepo.SaveInvite(this.inviteFriend.EmailAddress);
}
MailMessage toSend = new MailMessage(); // Obviously some logic to prepare the body, subject and other mail properties
this.mailSender.Send(toSend);
}
}
public interface ICommandFactory {
ICommand CreateInviteFriendCommand(InviteFriend info);
}
public class CommandFactory {
public CommandFactory(IResolutionRoot resolutionRoot) {
this.resolutionRoot = resolutionRoot;
}
ICommand CreateInviteFriendCommand(InviteFriend info) {
this.resolutionRoot.Get<InviteFriendCommand>(new ConstructorArgument("info", info));
}
}
public class YourController {
// Somewhere
var command = this.commandFactory.CreateInviteFriendCommand(info);
command.Execute();
}
public class YourModule : NinjectModule {
override Load() {
Bind<IUserRepository>().To<UserRepo>().InRequestScope();
Bind<ICommandFactory>().To<CommandFactory>().InRequestScope();
Bind<InviteFriendCommand>().ToSelf().InRequestScope();
}
}
Forgive me when you need to tweak it a bit. I hacked it together with my out of brain compiler ;)
Thank you for all your comments, but I've subsequently found the information I was looking for.
The answer is that it is possible to inject dependencies post-instantiation with Ninject. The solution is as follows:
public class InviteFriend {
[Inject]
public IUserRepository UserRepo { get; set; }
[Required]
public string EmailAddress { get; set; }
public void Execute() {
var user = UserRepo.GetUser(this.EmailAddress);
if (user == null) {
UserRepo.SaveInvite(this.EmailAddress);
}
MailMessage toSend = new MailMessage(); // Obviously some logic to prepare the body, subject and other mail properties
SmtpClient.Send(toSend);
}
}
With client code then using the Ninject kernel as follows:
IKernel container = new StandardKernel(new ModuleWithMyBindings());
container.Inject(instanceOfInviteFriend);
The code itself is a bit more sophisticated than that i.e. I'm not instantiating a new IKernel each time I need it.
I realise that this is architecturally less pure than some of the suggestions put forward in comments, but in the spirit of YAGNI, this is good enough for now and we can always refactor later on with some of the good suggestions in Daniel's answer. However, this was a question about the capabilities of Ninject rather than an architectural review question, and this is what I consider the answer to my own question :)

Visual Studio code generated when choosing to explicitly implement interface

Sorry for the vague title, but I'm not sure what this is called.
Say I add IDisposable to my class, Visual Studio can create the method stub for me. But it creates the stub like:
void IDisposable.Dispose()
I don't follow what this syntax is doing. Why do it like this instead of public void Dispose()?
And with the first syntax, I couldn't work out how to call Dispose() from within my class (in my destructor).
When you implement an interface member explicitly, which is what the generated code is doing, you can't access the member through the class instance. Instead you have to call it through an instance of the interface. For example:
class MyClass : IDisposable
{
void IDisposable.Dispose()
{
// Do Stuff
}
~MyClass()
{
IDisposable me = (IDisposable)this;
me.Dispose();
}
}
This enables you to implement two interfaces with a member of the same name and explicitly call either member independently.
interface IExplict1
{
string InterfaceName();
}
interface IExplict2
{
string InterfaceName();
}
class MyClass : IExplict1, IExplict2
{
string IExplict1.InterfaceName()
{
return "IExplicit1";
}
string IExplict2.InterfaceName()
{
return "IExplicit2";
}
}
public static void Main()
{
MyClass myInstance = new MyClass();
Console.WriteLine( ((IExplcit1)myInstance).InstanceName() ); // outputs "IExplicit1"
IExplicit2 myExplicit2Instance = (IExplicit2)myInstance;
Console.WriteLine( myExplicit2Instance.InstanceName() ); // outputs "IExplicit2"
}
Visual studio gives you two options:
Implement
Implement explicit
You normally choose the first one (non-explicit): which gives you the behaviour you want.
The "explicit" option is useful if you inherit the same method from two different interfaces, i.e multiple inheritance (which isn't usually).
Members of an interface type are always public. Which requires their method implementation to be public as well. This doesn't compile for example:
interface IFoo { void Bar(); }
class Baz : IFoo {
private void Bar() { } // CS0737
}
Explicit interface implementation provides a syntax that allows the method to be private:
class Baz : IFoo {
void IFoo.Bar() { } // No error
}
A classic use for this is to hide the implementation of a base interface type. IEnumerable<> would be a very good example:
class Baz : IEnumerable<Foo> {
public IEnumerator<Foo> GetEnumerator() {}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { }
}
Note how the generic version is accessible, the non-generic version is hidden. That both discourages its use and avoids a compile error because of a duplicate method.
In your case, implementing Dispose() explicitly is wrong. You wrote Dispose() to allow the client code to call it, forcing it to cast to IDisposable to make the call doesn't make sense.
Also, calling Dispose() from a finalizer is a code smell. The standard pattern is to add a protected Dispose(bool disposing) method to your class.

Resources