add-in for visual studio 2010 compile error Connect class - c#

Here:
Is there a way to specify outlining defaults in Visual Studio 2008 so that a file opens up with members collapsed by default?
..I could find an example for programming addins.. but unfortunately it doesnt compile :-(
Error 1
'CollapsedMembers.Connect' does not contain a definition for
'_openHandler' and no extension method '_openHandler' accepting a
first argument of type 'CollapsedMembers.Connect' could be found
(are you missing a using directive or an assembly reference?)
D:\CollapsedMembers\Connect.cs 77 18 CollapsedMembers
In fact there is no _openHandler there.. I have already tried all the .NET Framework versions but had unfortunately no success.
In OnOpenHandler.cs I have the OnOpenHandler implemented:
namespace CollapsedMembers
{
internal class OnOpenHandler
{
DTE2 _application = null;
EnvDTE.Events events = null;
EnvDTE.DocumentEvents docEvents = null;
... and so on...
can anyone help please?
[Edit:] Connect.cs is like following:
using System;
using Extensibility;
using EnvDTE;
using EnvDTE80;
namespace CollapsedMembers
{
/// <summary>The object for implementing an Add-in.</summary>
/// <seealso class='IDTExtensibility2' />
public class Connect : IDTExtensibility2
{
/// <summary>Implements the constructor for the Add-in object. Place your initialization code within this method.</summary>
public Connect()
{
}
/// <summary>Implements the OnConnection method of the IDTExtensibility2 interface. Receives notification that the Add-in is being loaded.</summary>
/// <param term='application'>Root object of the host application.</param>
/// <param term='connectMode'>Describes how the Add-in is being loaded.</param>
/// <param term='addInInst'>Object representing this Add-in.</param>
/// <seealso class='IDTExtensibility2' />
public void OnConnection(object application, ext_ConnectMode connectMode, object addInInst, ref Array custom)
{
_applicationObject = (DTE2)application;
_addInInstance = (AddIn)addInInst;
switch (connectMode)
{
case ext_ConnectMode.ext_cm_UISetup:
case ext_ConnectMode.ext_cm_Startup:
//Do nothing OnStartup will be called once IDE is initialised.
break;
case ext_ConnectMode.ext_cm_AfterStartup:
//The addin was started post startup so we need to call its initialisation manually
InitialiseHandlers();
break;
}
}
/// <summary>Implements the OnDisconnection method of the IDTExtensibility2 interface. Receives notification that the Add-in is being unloaded.</summary>
/// <param term='disconnectMode'>Describes how the Add-in is being unloaded.</param>
/// <param term='custom'>Array of parameters that are host application specific.</param>
/// <seealso class='IDTExtensibility2' />
public void OnDisconnection(ext_DisconnectMode disconnectMode, ref Array custom)
{
}
/// <summary>Implements the OnAddInsUpdate method of the IDTExtensibility2 interface. Receives notification when the collection of Add-ins has changed.</summary>
/// <param term='custom'>Array of parameters that are host application specific.</param>
/// <seealso class='IDTExtensibility2' />
public void OnAddInsUpdate(ref Array custom)
{
}
/// <summary>Implements the OnStartupComplete method of the IDTExtensibility2 interface. Receives notification that the host application has completed loading.</summary>
/// <param term='custom'>Array of parameters that are host application specific.</param>
/// <seealso class='IDTExtensibility2' />
public void OnStartupComplete(ref Array custom)
{
InitialiseHandlers();
}
/// <summary>Implements the OnBeginShutdown method of the IDTExtensibility2 interface. Receives notification that the host application is being unloaded.</summary>
/// <param term='custom'>Array of parameters that are host application specific.</param>
/// <seealso class='IDTExtensibility2' />
public void OnBeginShutdown(ref Array custom)
{
}
private DTE2 _applicationObject;
private AddIn _addInInstance;
private void InitialiseHandlers()
{
this._openHandler = new OnOpenHandler(_applicationObject);
}
}
}

_openHandler is a member of Connect class and it isn't defined, and you are using it the
private void InitialiseHandlers()
{
this._openHandler = new OnOpenHandler(_applicationObject);
}
method you copied. You need to define a OnOpenHandler _openHandler member for Connect class.

Related

WCF Named Pipes across the user session on same machine. Possible?

Requirement
I am trying to create a "Single Instance" winforms app with args to be passed if second instance invoked. I hope Mutex will not work like this. I have made a WCF pipe on the winform app so that if another instance came, it will be notified to Main Instance with the required args which I will process the args on the Main Instance as required and second instance closed after notifying.
Issue:
The above code seems to be working fine, problem arises when it comes to multiple user session, When I logon to the machine as "User A" and opens my app, it opens up the app (Main instance). At the same time, if another user logon say "User B" and tries to open up the app, IT HAPPILY OPENS UP :(
Code:
Here is my code for single instance with WCF.
public static class SingleInstanceManager
{
/// <summary>
/// Raised when another instance attempts to start up.
/// </summary>
public static event StartupEventHandler OtherInstanceStarted;
/// <summary>
/// Checks to see if this instance is the first instance running on this machine. If it is not, this method will
/// send the main instance this instance's startup information.
/// </summary>
/// <param name="guid">The application's unique identifier.</param>
/// <returns>True if this instance is the main instance.</returns>
public static bool VerifySingleInstance(Guid guid)
{
if (!AttemptPublishService(guid))
{
NotifyMainInstance(guid);
return false;
}
return true;
}
/// <summary>
/// Attempts to publish the service.
/// </summary>
/// <param name="guid">The application's unique identifier.</param>
/// <returns>True if the service was published successfully.</returns>
private static bool AttemptPublishService(Guid guid)
{
try
{
ServiceHost serviceHost = new ServiceHost(typeof(SingleInstance));
NetNamedPipeBinding binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None);
serviceHost.AddServiceEndpoint(typeof(ISingleInstance), binding, CreateAddress(guid));
serviceHost.Open();
return true;
}
catch
{
return false;
}
}
/// <summary>
/// Notifies the main instance that this instance is attempting to start up.
/// </summary>
/// <param name="guid">The application's unique identifier.</param>
private static void NotifyMainInstance(Guid guid)
{
NetNamedPipeBinding binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None);
EndpointAddress remoteAddress = new EndpointAddress(CreateAddress(guid));
using (ChannelFactory<ISingleInstance> factory = new ChannelFactory<ISingleInstance>(binding, remoteAddress))
{
ISingleInstance singleInstance = factory.CreateChannel();
singleInstance.NotifyMainInstance(Environment.GetCommandLineArgs());
}
}
/// <summary>
/// Creates an address to publish/contact the service at based on a globally unique identifier.
/// </summary>
/// <param name="guid">The identifier for the application.</param>
/// <returns>The address to publish/contact the service.</returns>
private static string CreateAddress(Guid guid)
{
return string.Format(CultureInfo.CurrentCulture, "net.pipe://localhost/{0}", guid);
}
/// <summary>
/// The interface that describes the single instance service.
/// </summary>
[ServiceContract]
private interface ISingleInstance
{
/// <summary>
/// Notifies the main instance that another instance of the application attempted to start.
/// </summary>
/// <param name="args">The other instance's command-line arguments.</param>
[OperationContract]
void NotifyMainInstance(string[] args);
}
/// <summary>
/// The implementation of the single instance service interface.
/// </summary>
private class SingleInstance : ISingleInstance
{
/// <summary>
/// Notifies the main instance that another instance of the application attempted to start.
/// </summary>
/// <param name="args">The other instance's command-line arguments.</param>
public void NotifyMainInstance(string[] args)
{
if (OtherInstanceStarted != null)
{
Type type = typeof(StartupEventArgs);
ConstructorInfo constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, Type.EmptyTypes, null);
StartupEventArgs e = (StartupEventArgs)constructor.Invoke(null);
FieldInfo argsField = type.GetField("_args", BindingFlags.Instance | BindingFlags.NonPublic);
Debug.Assert(argsField != null);
argsField.SetValue(e, args);
OtherInstanceStarted(null, e);
}
}
}
}
On the Winforms Main:
static void Main()
{
//bool isSingle;
//var mut = new Mutex(true, "MarketFeeder", out isSingle);
var applicationId = new Guid("08f21b4e-86d7-4ddf-abcb-9a72cd2bbd4f");
if (SingleInstanceManager.VerifySingleInstance(applicationId))
{
SingleInstanceManager.OtherInstanceStarted += OnOtherInstanceStarted;
// Start the application
System.Windows.Forms.Application.EnableVisualStyles();
System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(false);
main = new MainForm();
System.Windows.Forms.Application.Run(main);
}
}
Help needed on
Is there a way to communicate via Namedpipe across the users on same machine?, I don't want to go for "Windows service" for my requirement which I feel over kill for my requirement.
Already went though following links but no luck. Also they are too old I feel we have better solution for this in recent times. I hope there are some devs like me who are still working on Windows applications :P
Isolated Named Pipes in Terminal Server Sessions

TestAccelerometer implementation for Window Phone

Problem
My application use accelerometer data via Microsoft.Devices.Sensors.Accelerometer class
Now I wanna write Unit or CodedUI tests, for this reason I need to have a special test implementation of Accelerometer to controlling returned data
In theory I have 3 options:
Create subclass of Accelerometer - impossible because Accelerometer is sealed class
By using reflection replace implementation of Accelerometer at run-time - isn't best option IMHO
Create subclass of SensorBase<AccelerometerReading> - good option
I have decided to go by #1 and implement my TestAccelerometer as child of SensorBase<AccelerometerReading>
And here is I have problem:
`Error CS1729 'SensorBase<AccelerometerReading>' does not contain a constructor that takes 0 arguments`
Error pretty clear I have looked in decompiled code (JetBrains dotPeak tool) and don't found any constructors at all.
Questions
How can I found proper constructor to use in my TestAccelerometer implementation?
Decompiled code
Microsoft.Devices.Sensors.Accelerometer
// Type: Microsoft.Devices.Sensors.Accelerometer
// Assembly: Microsoft.Devices.Sensors, Version=8.0.0.0, Culture=neutral, PublicKeyToken=24eec0d8c86cda1e
// MVID: 81ED89AA-6B11-4B39-BAFA-38D59CBB1E3B
// Assembly location: C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\WindowsPhone\v8.0\Microsoft.Devices.Sensors.dll
using System;
namespace Microsoft.Devices.Sensors
{
/// <summary>
/// Provides Windows Phone applications access to the device’s accelerometer sensor.
/// </summary>
public sealed class Accelerometer : SensorBase<AccelerometerReading>
{
/// <summary>
/// Gets or sets whether the device on which the application is running supports the accelerometer sensor.
/// </summary>
///
/// <returns>
/// true if the device on which the application is running supports the accelerometer sensor; otherwise, false.
/// </returns>
public static bool IsSupported { get; internal set; }
/// <summary>
/// Gets the current state of the accelerometer. The value is a member of the <see cref="T:Microsoft.Devices.Sensors.SensorState"/> enumeration.
/// </summary>
///
/// <returns>
/// Type: <see cref="T:Microsoft.Devices.Sensors.SensorState"/>.
/// </returns>
public SensorState State { get; private set; }
/// <summary>
/// Occurs when new data arrives from the accelerometer. This method is deprecated in the current release. Applications should use the <see cref="E:Microsoft.Devices.Sensors.SensorBase`1.CurrentValueChanged"/> event of the <see cref="T:Microsoft.Devices.Sensors.SensorBase`1"/> class instead.
/// </summary>
[Obsolete("use CurrentValueChanged")]
public event EventHandler<AccelerometerReadingEventArgs> ReadingChanged;
static Accelerometer();
/// <summary>
/// Releases the managed and unmanaged resources used by the <see cref="T:Microsoft.Devices.Sensors.Accelerometer"/>.
/// </summary>
public new void Dispose();
/// <summary>
/// Starts data acquisition from the accelerometer.
/// </summary>
public new void Start();
/// <summary>
/// Stops data acquisition from the accelerometer.
/// </summary>
public new void Stop();
}
}
Microsoft.Devices.Sensors.SensorBase
// Type: Microsoft.Devices.Sensors.SensorBase`1
// Assembly: Microsoft.Devices.Sensors, Version=8.0.0.0, Culture=neutral, PublicKeyToken=24eec0d8c86cda1e
// MVID: 81ED89AA-6B11-4B39-BAFA-38D59CBB1E3B
// Assembly location: C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\WindowsPhone\v8.0\Microsoft.Devices.Sensors.dll
using System;
using System.Security;
namespace Microsoft.Devices.Sensors
{
/// <summary>
/// The base class for all Windows Phone sensor classes.
/// </summary>
/// <typeparam name="TSensorReading">The type of reading returned by the sensor.</typeparam>
public abstract class SensorBase<TSensorReading> : IDisposable where TSensorReading : ISensorReading
{
/// <summary>
/// Gets an object that implements <see cref="T:Microsoft.Devices.Sensors.ISensorReading"/> that contains the current value of the sensor. This object will be one of the following types, depending on which sensor is being referenced: <see cref="T:Microsoft.Devices.Sensors.AccelerometerReading"/>, <see cref="T:Microsoft.Devices.Sensors.CompassReading"/>, <see cref="T:Microsoft.Devices.Sensors.GyroscopeReading"/>, <see cref="T:Microsoft.Devices.Sensors.MotionReading"/>.
/// </summary>
///
/// <returns>
/// An object that implements <see cref="T:Microsoft.Devices.Sensors.ISensorReading"/> that contains the current value of the sensor.
/// </returns>
public TSensorReading CurrentValue { get; }
/// <summary>
/// Gets or sets the preferred time between <see cref="E:Microsoft.Devices.Sensors.SensorBase`1.CurrentValueChanged"/> events.
/// </summary>
///
/// <returns>
/// Type: <see cref="T:System.TimeSpan"/>. The preferred time between CurrentValueChanged events.
/// </returns>
public TimeSpan TimeBetweenUpdates { get; set; }
/// <summary>
/// Gets the validity of the sensor’s data.
/// </summary>
///
/// <returns>
/// Type: <see cref="T:System.Boolean"/>. true if the sensor’s data is valid; otherwise, false.
/// </returns>
public bool IsDataValid { get; }
/// <summary>
/// Occurs when new data arrives from the sensor.
/// </summary>
public event EventHandler<SensorReadingEventArgs<TSensorReading>> CurrentValueChanged;
static SensorBase();
internal SensorBase();
/// <summary>
/// Allows an object to try to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection.
/// </summary>
[SecuritySafeCritical]
~SensorBase();
/// <summary>
/// Releases the managed and unmanaged resources used by the sensor.
/// </summary>
[SecuritySafeCritical]
public void Dispose();
/// <summary>
/// Starts acquisition of data from the sensor.
/// </summary>
public virtual void Start();
/// <summary>
/// Stops acquisition of data from the sensor.
/// </summary>
public virtual void Stop();
}
}
You did find a constructor:
internal SensorBase();
This constructor prevents the SensorBase from having a default public constructor and this class cannot be subclassed from outside its assembly.
Testing it will be complicated. You could redesign the app and use a wrapper/adapter for the Accelerometer just for the puropse of testing or you could check if there's a possibility of mocking a sealed class on Windows Phone.

Plug unplug audio device events

I am trying to get an event when an audio device is plugged or unplugged there are several questions asked for it but I am still not able to get
I was trying to use CoreAudio API I created ImmNotificationClient.cs interface
[Guid("7991EEC9-7E89-4D85-8390-6C703CEC60C0"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IMMNotificationClient
{
/// <summary>
/// Device State Changed
/// </summary>
void OnDeviceStateChanged([MarshalAs(UnmanagedType.LPWStr)] string deviceId, [MarshalAs(UnmanagedType.I4)] EDeviceState newState);
/// <summary>
/// Device Added
/// </summary>
void OnDeviceAdded([MarshalAs(UnmanagedType.LPWStr)] string pwstrDeviceId);
/// <summary>
/// Device Removed
/// </summary>
void OnDeviceRemoved([MarshalAs(UnmanagedType.LPWStr)] string deviceId);
/// <summary>
/// Default Device Changed
/// </summary>
void OnDefaultDeviceChanged(EDataFlow flow, ERole role, [MarshalAs(UnmanagedType.LPWStr)] string defaultDeviceId);
/// <summary>
/// Property Value Changed
/// </summary>
/// <param name="pwstrDeviceId"></param>
/// <param name="key"></param>
void OnPropertyValueChanged([MarshalAs(UnmanagedType.LPWStr)] string pwstrDeviceId, PropertyKey key);
}
I have created CMMNotificationClient.cs class which implements above methods
Now I am not sure How to register the call back to these methods and register for Plug and UnPlug Events
I tried to register it in the IMMDeviceEnumerator
[PreserveSig]
int RegisterEndpointNotificationCallback(IMMNotificationClient pClient);
[PreserveSig]
int UnregisterEndpointNotificationCallback(IMMNotificationClient pClient);
Can you please help on this or can you provide any other solution?
You can use RegisterDeviceNotification Windows API to get notified.
Stackoverflow example
CodeProject example

WCF call to "get" datamember in contract returns null

I have an operation contract in my service contract called
Schedule[] GetScheduleObjects();
I have a datameber in that operation contract called "Tasks" that returns a list of sub objects.
[DataMember()]
public Task[] Tasks
The issues is when the operation contract is called the method executes but the "get" of "Tasks" occurs twice. The first time it contains valid runtime instances, the second time it is null which causes a serialization exception. This happens despite only one call to the service. The binding is a tcp connection using a duplex proxy. Ideas?????
The Datacontract
[DataContract()]
public class Schedule
{
public Schedule(string name)
{
this.Name = name;
}
[DataMember()]
public string Name { get; private set; }
[DataMember()]
public bool Running { get; set; }
/// <summary>
/// Schedule Task is a DataMember object, do not modify
/// </summary>
[DataMember()]
public Task[] Tasks
{
get { return _Tasks.ToArray(); }
}
private List<Task> _Tasks = new List<Task>();
///<summary>
/// Use this property to add objects
///</summary>
public List<Task> ScheduleTasks
{
get { return _Tasks; }
}
}
The service contract
[ServiceContract(CallbackContract = typeof(ISummitDashboardCallbackContract))]
public interface ISchedulerContract : ISummitDashboardContract
{
/// <summary>
/// Sets the named schedule into "run" mode
/// </summary>
/// <param name="scheduleName"></param>
/// <returns></returns>
[OperationContract()]
void StartSchedule(string scheduleName);
/// <summary>
/// Pauses the currently running schedule
/// </summary>
/// <param name="scheduleName"></param>
[OperationContract()]
void PauseSchedule(string scheduleName);
/// <summary>
/// Removes the named schedule from "run" mode
/// </summary>
/// <param name="scheduleName"></param>
/// <returns></returns>
[OperationContract()]
void StopSchedule(string scheduleName);
/// <summary>
/// Flips the "active" state of the task with the named id
/// </summary>
/// <param name="scheduleName"></param>
/// <param name="Id"></param>
[OperationContract()]
void ToggleTaskState(string scheduleName, string Id);
/// <summary>
/// Flips the "active" state of the action with the named id
/// </summary>
/// <param name="scheduleName"></param>
/// <param name="Id"></param>
/// <returns></returns>
[OperationContract()]
void ToggleActionState(string scheduleName, string Id);
/// <summary>
/// Returns the information to build the tree list in the dashboard
/// </summary>
/// <returns></returns>
[OperationContract()]
Schedule[] GetScheduleObjects();
/// <summary>
/// Returns the events of the scheduler
/// </summary>
/// <returns></returns>
[OperationContract()]
SchedulerEvent[] GetSchedulerEvents(int startIndex, int count, int eventLogEntryType);
}
You'll need to add a setter to property Tasks, and you'll also need to increase the visibility of Name to at least protected - WCF will need to use these in order to deserialize objects of this class.
As a secondary issue, if a client generates a proxy (e.g. with Add Service Reference or via SvcUtil.exe), the 'code behind' Tasks (i.e. return _Tasks.ToArray(); which is coupled to ScheduledTasks) will be lost, and the client will instead just get a simple automatic backing property to property Tasks (with the collection class selected during the proxy generation). This second issue won't however happen however if you share type.

What am I doing wrong with my Workflow bookmark pick trigger?

I have a NativeActivity derived activity that I wrote that is to use bookmarks as a trigger for a pick branch. Using something I found on MSDN I tried writing this to trigger the branch. The branch contains activities that fire service callbacks to remote clients via send activities. If I set a delay for the trigger, callbacks fire to the clients successfully. If I use my code activity, the pick branch activities don't fire.
public sealed class UpdateListener : NativeActivity<ClientUpdate>
{
[RequiredArgument]
public InArgument<string> BookmarkName { get; set; }
protected override void Execute(NativeActivityContext context)
{
context.CreateBookmark(BookmarkName.Get(context),
new BookmarkCallback(this.OnResumeBookmark));
}
protected override bool CanInduceIdle
{
get { return true; }
}
public void OnResumeBookmark(NativeActivityContext context, Bookmark bookmark, object obj )
{
Result.Set(context, (ClientUpdate)obj);
}
}
So it takes an arg to set the bookmark name for future bookmark references to execute the trigger. OnResumeBoookmark() takes in a ClientUpdate object that is passed by my application that is hosting the workflowapp. The activity is to return the object so the ClientUpdate can be passed to the workflow and have it sent to the remote clients via the send activity in the pick branch. In theory anyways.
For some reason it seems to be correct but feels wrong. I'm not sure if I should write the Activity in a different way to take care of what I need for my WF service.
I think your intentions would be a bit clearer if you created an extension (that implements IWorkflowInstanceExtension) to perform your action here.
For example:
public sealed class AsyncWorkExtension
: IWorkflowInstanceExtension
{
// only one extension per workflow
private WorkflowInstanceProxy _proxy;
private Bookmark _lastBookmark;
/// <summary>
/// Request the extension does some work for an activity
/// during which the activity will idle the workflow
/// </summary>
/// <param name="toResumeMe"></param>
public void DoWork(Bookmark toResumeMe)
{
_lastBookmark = toResumeMe;
// imagine I kick off some async op here
// when complete system calls WorkCompleted below
// NOTE: you CANNOT block here or you block the WF!
}
/// <summary>
/// Called by the system when long-running work is complete
/// </summary>
/// <param name="result"></param>
internal void WorkCompleted(object result)
{
//NOT good practice! example only
//this leaks resources search APM for details
_proxy.BeginResumeBookmark(_lastBookmark, result, null, null);
}
/// <summary>
/// When implemented, returns any additional extensions
/// the implementing class requires.
/// </summary>
/// <returns>
/// A collection of additional workflow extensions.
/// </returns>
IEnumerable<object> IWorkflowInstanceExtension
.GetAdditionalExtensions()
{
return new object[0];
}
/// <summary>
/// Sets the specified target
/// <see cref="WorkflowInstanceProxy"/>.
/// </summary>
/// <param name="instance">The target workflow instance to set.</param>
void IWorkflowInstanceExtension
.SetInstance(WorkflowInstanceProxy instance)
{
_proxy = instance;
}
}
Within the Activity, you'd use this thusly:
var ext = context.GetExtension<AsyncWorkExtension>();
var bookmark = context.CreateBookmark(BookmarkCallback);
ext.DoWork(bookmark);
return;
This way is much more explicit (instead of using the bookmark name to convey meaning to the "outside" world) and is much easier to extend if, say, you require to send out more information than a bookmark name.
Is there something actually resuming the bookmark here? If not the workflow will wait very patiently and nothing will happen.

Categories