When capturing build events you can simply listen to the DTE2.Events.BuildEvents event. However is it possible to listen to these events without the use of DTE. I have read and heard from several people and sources that you should generally avoid using DTE, if somehow possible, due to its bad implementation or whatever.
In general if you're trying to automate Visual Studio you can either use DTE, which is the standard automation approach, or use native interfaces. The native interfaces start 'IVs...', e.g. IVsSolution. In both cases the technology is ancient and poorly-documented. As you suggest, a native solution does tend to be better.
Having said that, for the tasks running on a build that I've needed I ended up using DTE, which can be easier to program and made to work reliably.
I've found the equally-ancient articles (not the tools!) on the mztools.com website to be quite useful on this stuff, as well as the MSDN docs of course. Add 'mztools' to your Google search. For example, what mztools says on build events (Google 'mztools build events') is useful even though it dates from 2013.
I just want to share the code which actually works and achieves exactly what I needed. This was possible through the help of #Rich N, thanks for that one. It is actually easier than I thought, it is always the same procedure
Get the Svs... class from the GetService method and cast it to the corresponding interface.
Than append the Event Handler Class with the Advise... method.
// First of get the IVsSolutionBuildManager via the SVsSolutionBuildManager with the GetService method
var service = GetService(typeof(SVsSolutionBuildManager)) as IVsSolutionBuildManager;
// Appending the Events
service.AdviseUpdateSolutionEvents(new Events(), out var cookie)
// The class which handles the Event callbacks
public class Events : IVsUpdateSolutionEvents
{
// The implemented methods from the interface
}
Related
I have a very simple wcf server. When a client uses an "operation" contract, I want to log this in a log file.
I came up with two solutions for this but I doubt they are good solutions and need some hints from the experts here.
My first solution:
instead of creating the host with typeof(serverclass), I use an instance of serverclass.
serverclass has an event and I attach an event handler to it that writes into the log.
The problem with this solution is it requires extra care with mult-threading, re-entrant, multi-session, per call settings ... etc.
My second solution:
use a static delegate inside serverclass and still create the host with typeof(serverclass). This way I can assign the logging function to the static delegate.
I don't feel this is the best way and I really appreciate comments or hints.
Thank you.
You may use WCF behaviour extensions to intercept the call and then write the log file.
There are various ways to intercept it by implementing various extension interfaces but message inspector is one of them.
Have a look here.
You could also consider an AOP approach. PostSharp is a good platform for this. The free version supports entry, exit, and error aspects.
I'm new to Java, I'm porting over our Windows Phone 7 library to run on Android. Due to syntax similarities this has been very simple so far. Our library is basically an abstracted http message queue that provides data persistence and integrity on mobile platforms. It only provides asynchronous methods which is a design choice. On WP7 I make use of delegates to call the user supplied callback when an async message has been processed and the servers response received.
To achieve the same thing on Android I've found two ways so far - A simple Java listener interface that contains OnSuccess and OnFailure methods that the user must implement, or using the Android handler class which provides a message queue between threads (http://developer.android.com/reference/android/os/Handler.html).
I've gone with the Handler at this stage as if I'm honest it is the most similar to a C# delegate. It also seems like less work for a user of our library to implement. Example of some user code to make use of our library:
connection.GetMessage("http://somerestservice.com", GetCallback);
Handler GetCallback = new Handler() {
public void handleMessage(Message message){
CustomMessageClass customMessage = (CustomMessageClass)message.obj;
if(customMessage.status == Status.Delivered) {
// Process message here,
// it contains various information about the transaction
// as well as a tag that can contain a user object etc.
// It also contains the servers response as a string and as a byte array.
}
}
};
Using this the user can create as many different handlers as they'd like, called whatever they'd like, and pass them in as method parameters. Very similar to a delegate...
The reason I'm wondering if I should move to a listener interface is because the more exposure I gain to Java the more it seems that's just how it's done and it's how third parties using our library would expect it to be done.
It's essentially the same process, except each time you wanted to do something different with the server response i.e. You might be fetching different types of data from different endpoints, you're going to have to create a custom class that implements our interface each time, as well as implementing any methods our interface has. Or of course you could have a single monolithic class that all server responses were funneled in to but have fun trying to figure out what to do with each individual response...
I may be a bit biased due to coming from C# but a listener seems a bit convoluted and I like the handler implementation better, do any Java developers have any thoughts/advice? It would be much appreciated.
Cheers!
The benefit of using the interface approach is loose coupling. This way, any class that implements your interface shouldn't be aware of (or be affected by) any thread management being done elsewhere and can handle the result object as appropriate within its scope.
BTW, I'm a big fan of AsyncTask. Have you tried using?
I don't think what you have there compiles.. you need to define the handler implementation before you use it?
But to the substance of your question, if you really do want a different handler implementation for each response, than the api you have seems fine.
I would use the listener pattern if all messages are handled in the same way, or the different handling only depends on the content in the message which could not be determined when making the getMessage call.
As an aside, typically in Java function and variable names begin with a lower case. Only class names begin with an upper case.
Greetings all,
I’m working on a C# program that requires being able to get the index of the hot item in Windows 7 Explorer’s new ItemsView control. Fortunately, Microsoft has provided a way to do this through UI Automation, by querying custom properties of the control.
Unfortunately, the System.Windows.Automation namespace inexplicably does not seem to provide a way to query custom properties! This leaves me with the undesirable position of having to completely ditch the C# Automation namespace and use only the unmanaged COM version. One way to do it would be to put all the Automation code in a separate C++/CLI module and call it from my C# application. However, I would like to avoid this option if possible, as it adds more files to my project, and I’d have to worry about 32/64-bit problems and such.
The other option is to make use of the ComImport attribute to declare the relevant interfaces and do everything through COM-interop. This is what I would like to do. However, the relevant interfaces, such as IUIAutomation and IUIAutomationElement, are FREAKING HUGE. They have hundreds of methods in total, and reference tons and tons of interfaces (which I assume I would have to also declare), almost all of which I will never ever use. I don’t think the UI Automation interfaces are declared in any Type Library either, so I can’t use TLBIMP.
Is there any way I can avoid having to manually translate a bajillion method signatures into C# and instead only declare the ten or so methods I actually need? I see that C# 4.0 added a new “dynamic” type that is supposed to ease COM interop; is that at all relevant to my problem?
Thanks
The most important thing (from the perspective of calling a COM method from C#) is that the methods appear in the interface in the right order. If you're not using a method, you can just declare it as void and nothing bad will happen (unless you actually call it!). This saves you from having to work out the correct signatures and define all the other types, etc. For example,
[ComImport, Guid("30cbe57d-d9d0-452a-ab13-7ac5ac4825ee"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IUIAutomation
{
void CompareElements();
void CompareRuntimeIds();
void GetRootElement();
// 50 or so other methods...
// ... define only the signatures for the ones you actually need
}
The methods should be defined in exactly the same order they appear in UIAutomationClient.h (in the Windows SDK).
I'm primarily an Objective-C/Cocoa developer, but I'm trying to implement the Observer pattern in C#.NET, specifically mimicking the NSKeyValueObserving protocols and methodology.
I've gotten as far as mimicking NSKVO with manual support, as described in Apple's KVO Programming Guide (see http://tinyurl.com/nugolr). Since I'm writing the setValue:forKey: methods myself, I can implement auto KVO notification through there.
However, I'd like to somehow implement auto KVO on all properties by dynamically overriding them at runtime. For example, replacing Button.Title.set with:
set {
this.willChangeValueForKey("title");
title = value;
this.didChangeValueForKey("title");
}
So, this is my question:
How do I dynamically override a method or property at runtime in C#? I've gotten as far as getting and invoking methods and properties by name using Reflection.MethodInfo. Alternatively, can I observe the runtime and find out when a method is about to be/has been called?
Dynamic metaprogramming and aspect oriented programming are not yet strongly supported in C#. What you can do, is look at a free tool called PostSharp - it allows supports weaving aspects into your code around properties and method calls quite easily.
You can implement the INotifyPropertyChanged interface (without postsharp) and it can be used in certain contexts to notify observers that a value of a property has changed. However, it still requires that each property actually broadcast the change notification - which generally requires it to be specifically coded to support that. Injecting change notification to existing code (without actually changing the source) is not an easy thing to do in straight-up C#. PostSharp (other other AOP/dynamic proxy libraries) make this sort of thing dramatically easier.
I'm not sure if you need to go down this road or not. But if you want to implement overrides of a method (i.e. generating new code for the method?) then it is possible with Emit. I would explore any other suggestions first before diving into those deep waters.
You're looking for INotifyPropertyChanged. You can dynamically implement that using PostSharp, Castle DynamicProxy or probably any other proxying library.
This does not solves the problem of having to add the tracking code dynamically, but can be interesting to read: Trackable Properties with Weak Events
With this stuff you are able to track changes to specific properties and it makes easier to implement INotifyPropertyChanged (i.e. track changes to all properties).
After doing extensive research on this subject, it appears that I can't do exactly what I'd like to do with .NET in its current state.
PostSharp's method is done at compile time, meaning I can't dynamically insert my own implementations to methods.
Reflection.Emit allows me to do this dynamically, but it generates a new instance of the created subclass - I need to do this so it works with the original instance.
INotifyPropertyChanging and INotifyPropertyChanged would be perfect if any of the existing .NET classes actually used them.
... so, at the moment I'm a bit stuck. I've put a more detailed piece on what I'm doing and how I'm trying to achieve in a post on my blog. Here's hoping .NET 4.0's dynamic dispatch will help!
All over our codebase we have this repeated pattern where there's an interface with one method. Is this a real design pattern? If so what is it and what would the benefits be?
Here are a few examples:
public interface IRunnable
{
void Run();
}
public interface IAction
{
void Perform();
}
public interface ICommand
{
void Execute(ActionArgs _actionargs);
}
I've seen this referenced as the Command pattern.
I first learned about it reading Uncle Bob's Agile Principles, Patterns, and Practices in C#.
I believe its elegance is its simplicity. I've used it when I wrote a file processing service. The service performed all of the administration of reading / deleting files. When a file needed to be processed, it's respective plugin was loaded. Each plugin implemented a Process method, and did whatever was needed to process that type of file. (Mainly, parse the contents and insert into a database.)
Everytime I had to process a new file type with a new layout, all I had to do was create a new Plugin that implemented Process.
This worked for me because I needed a simple solution. If you need to take in more than one parameter, this probably is not the pattern to use.
Any of these could very well be specific cases of the Command Pattern, depending on how it's being used and the context. Part of this would depend on why and how you're setting this up.
The command pattern also normally includes a concept of state and of various objects. Typically, this type of interface would suggest that, so I'm guessing this is what you are thinking of as a design pattern here, but without the caller or multiple targets it's difficult to tell if this is a classic example of it or not...
However, this, in and of itself, is just basic interface abstraction to me, and not something I'd classify as a design pattern.
As It was said it is a Command Design Pattern. But it is ( as for me ) more like Java way of achieving the result. In C# you can use delegates and in the C++ function pointers and functors.
There is no big sense to create more and more classes if you already have some implementation of the reaction in a some Class method. Which you can bind in the C++ or set to delegate in the C#. In Java I suppose you have no choice but to write the code you have found.
I'm not sure whether you could call it a design pattern as the interfaces you provided does not provide solutions to commonly experienced problems but rather solution to very specific problems in the project that you're developing.
The reason you're properly using interfaces is due to the fact that you cannot have all your classes that needs these methods extend a base class that contains these, yet you need to know that specific classes promise to implement these.
Might be, as some of the previous posters suggested: http://en.wikipedia.org/wiki/Command_pattern
You can remove this repetition (or prevent it for future code) by using lambda expressions. Lambda expressions are exactly for this situation.
If anything, then it's a functor. It's used in languages without first class function( pointer)s for the sort of things function( pointer)s are used for, such as the main function for a thread.
There are applications for Interfaces with only one method. I mean, in .NET there are plenty - INotifyPropertyChanged, for one (the PropertyChanged event). It just guarantees that an object has a certain method (regardless of what type of object it actually is), so you can call it (again, regardless of type).
Dim runnableObjects As List(Of Object)
runnableObjects.Add(New MyRunnableObject1)
runnableObjects.Add(New MyRunnableObject2)
For Each o As IRunnable In runnableObjects
o.Run()
Next
Maybe I'm missing something, but the first two look like they could be part of the strategy pattern. Basically, an object has a member of type IAction, and that member is assigned/reassigned at runtime based on the needs of the system to perform a task in a particular way (ie using a particular strategy).