I am currently working on an Enterprise Architect addin, and i really need to use some custom hotkeys for user preference. It is working correctly by using functionality from this article: https://community.sparxsystems.com/community-resources/805-triggering-add-in-functionality-with-custom-hotkeys-in-enterprise-architect , but with this way of using custom hotkeys Enterprise Architect is constantly using one core of the processor massively -> if i remove the addin dll, and delete the key from the registry this problem disappears, and i am sure now that the custom hotkey functionality causes it.
Can anyone help me by offering another way of using custom hotkeys in an enterprise architect addin? Searching for another solution for a long time now, but haven't achieved any progress in it yet.
Tamas
EDIT... FOUND THE SOLUTION: modify InvisibleHotKeyForm.cs and Hotkey.cs
InvisibleHotKeyForm.cs modification:
delete "worker_DoWork" method and
public partial class InvisibleHotKeyForm : Form
{
private const double Button_MilliSec = 10.0;
private readonly IEnumerable<Hotkey> _hotkeys;
private readonly int _thisProcessId;
private int _lastActiveProcessId;
private readonly BackgroundWorker _worker;
private System.Timers.Timer Timer_Button;
public InvisibleHotKeyForm(IEnumerable<Hotkey> hotkeys)
{
InitializeComponent();
this._thisProcessId = Process.GetCurrentProcess().Id;
this._worker = new BackgroundWorker();
this.Timer_Init(10.0);
this._hotkeys = hotkeys;
this._lastActiveProcessId = this._thisProcessId;
Closing += (sender, eventArgs) => ((List<Hotkey>)_hotkeys).ForEach(key => key.Dispose());
}
private void Timer_Init(double Millisec)
{
this.Timer_Button = new System.Timers.Timer();
this.Timer_Button.Elapsed += new ElapsedEventHandler(OnTimedEvent);
this.Timer_Button.Interval = Millisec;
this.Timer_Button.Enabled = true;
}
private void OnTimedEvent(object sender, ElapsedEventArgs e)
{
int id = ActiveProcess.GetActiveProcess().Id;
if (this._lastActiveProcessId == id)
return;
if (this._thisProcessId == id)
{
this.BeginInvoke((Delegate)new MethodInvoker(RegisterHotKeys));
}
else if (this._thisProcessId != id)
{
this.BeginInvoke((Delegate)new MethodInvoker(UnregisterHotKeys));
}
this._lastActiveProcessId = id;
}
.
.
.
and Hotkey.cs modification:
public class Hotkey : IDisposable
{
public const int WM_HOTKEY_MSG_ID = 786;
private Keys Key { get; set; }
private Modifiers Modifiers { get; set; }
public HotkeyHandler Handler { get; private set; }
private int Id { get; set; }
private IWin32Window _registeredWindow;
private bool _registered;
public Hotkey(Keys key, Modifiers modifiers, HotkeyHandler handler)
{
this._registeredWindow = (IWin32Window)null;
this._registered = false;
this.Key = key;
this.Modifiers = modifiers;
this.Handler = handler;
Id = GetHashCode();
}
.
.
.
Related
I'm trying to build my first xamarin app, which I'm building using forms. One of the features of the app is sending users locations and have to do that even if the app is in the background. So I came across James Montemagno's GeolocatorPlugin, which promised to do just that.
As the documentation was not that clear on how to implement his plugin in the background I looked through the projects closed issues and found a guy which gave an example of a simple case of using the plugin with a service. (https://github.com/jamesmontemagno/GeolocatorPlugin/issues/272)
I've adopted the code and created the service. The service are using an interface to start the service and now my problem is how to make use of the interface to make the service run.
In my shared project I put the interface and the viewmodel and in xamarin.android project I put the service.
The interface - IGeolocationBackgroundService:
public interface IGeolocationBackgroundService {
void StartService();
void StartTracking();
}
The viewmodel - GeolocatorPageViewModel:
public class GeolocatorPageViewModel
{
public Position _currentUserPosition { get; set; }
public string CoordinatesString { get; set; }
public List<string> userPositions { get; set; }
public ICommand StartTrackingCommand => new Command(async () =>
{
if (CrossGeolocator.Current.IsListening)
{
await CrossGeolocator.Current.StopListeningAsync();
}
CrossGeolocator.Current.DesiredAccuracy = 25;
CrossGeolocator.Current.PositionChanged += Geolocator_PositionChanged;
await CrossGeolocator.Current.StartListeningAsync(
TimeSpan.FromSeconds(3), 5);
});
private void Geolocator_PositionChanged(object sender, PositionEventArgs e)
{
var position = e.Position;
_currentUserPosition = position;
var positionString = $"Latitude: {position.Latitude}, Longitude: {position.Longitude}";
CoordinatesString = positionString;
Device.BeginInvokeOnMainThread(() => CoordinatesString = positionString);
userPositions.Add(positionString);
Debug.WriteLine($"Position changed event. User position: {CoordinatesString}");
}
}
The service - GeolocationService:
[assembly: Xamarin.Forms.Dependency(typeof(GeolocationService))]
namespace MyApp.Droid.Services
{
[Service]
public class GeolocationService : Service, IGeolocationBackgroundService
{
Context context;
private static readonly string CHANNEL_ID = "geolocationServiceChannel";
public GeolocatorPageViewModel ViewModel { get; private set; }
public override IBinder OnBind(Intent intent)
{
return null;
}
public GeolocationService(Context context)
{
this.context = context;
CreateNotificationChannel();
}
private void CreateNotificationChannel()
{
NotificationChannel serviceChannel = new NotificationChannel(CHANNEL_ID,
"GeolocationService", Android.App.NotificationImportance.Default);
NotificationManager manager = context.GetSystemService(Context.NotificationService) as NotificationManager;
manager.CreateNotificationChannel(serviceChannel);
}
//[return: GeneratedEnum]
public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
{
var newIntent = new Intent(this, typeof(MainActivity));
newIntent.AddFlags(ActivityFlags.ClearTop);
newIntent.AddFlags(ActivityFlags.SingleTop);
var pendingIntent = PendingIntent.GetActivity(this, 0, newIntent, 0);
var builder = new Notification.Builder(this, CHANNEL_ID);
var notification = builder.SetContentIntent(pendingIntent)
.SetSmallIcon(Resource.Drawable.ic_media_play_light)
.SetAutoCancel(false)
.SetTicker("Locator is recording")
.SetContentTitle("GeolocationService")
.SetContentText("Geolocator is recording for position changes.")
.Build();
StartForeground(112, notification);
//ViewModel = new GeolocatorPageViewModel();
return StartCommandResult.Sticky;
}
public void StartService()
=> context.StartService(new Intent(context, typeof(GeolocationService)));
public void StartTracking()
{
ViewModel = new GeolocatorPageViewModel();
ViewModel.StartTrackingCommand.Execute(null);
}
}
}
So be clear, I need to start the service and I'm not used to interfaces, so how do I call the interface?
use DependencyService to get a reference to your service and then start it
var svc = DependencyService.Get<IGeolocationBackgroundService>();
svc.StartService();
svc.StartTracking();
We use the Xamarin.Forms WebView to display content of a certain object, but this content won't be displayed in the WebView until we rotate the Device twice.
The .xmal-File Code:
<WebView x:Name="WebView" HeightRequest="{Binding Height}" WidthRequest="{Binding Width}">
<WebView.Source>
<HtmlWebViewSource Html="{Binding Code}"/>
</WebView.Source>
</WebView>
And the ModelView:
private double _height;
private double _width;
public ICommand ItemTappedCommand { get; private set; }
public string SearchBarLabelText { get; private set; }
public object LastTappedItem { get; set; }
public int ColumnCount { get; private set; } = 2;
public string CodeName { get; private set; }
public string CodeContent { get; private set; }
public string Code { get; private set; }
public double Height
{
get => _height;
private set
{
if (_height == value)
return;
_height = value;
OnPropertyChanged(nameof(Height));
}
}
public double Width
{
get => _width;
private set
{
if (_width == value)
return;
_width = value;
OnPropertyChanged(nameof(Width));
}
}
public ErrorcodeDetailPageViewModel(Errorcode code)
{
Device.Info.PropertyChanged += DevicePropertyChanged;
DevicePropertyChanged(null, null);
Code = code.Content;
CodeName = code.Label;
CodeContent = code.Content;
}
private void DevicePropertyChanged(object sender, PropertyChangedEventArgs e)
{
switch (Device.Info.CurrentOrientation)
{
case DeviceOrientation.Portrait:
Height = Device.Info.PixelScreenSize.Height - 150; // 120 is the Height of the ControlTemplate used on this Page + the top row on uwp; only required in portrait mode
Width = Device.Info.PixelScreenSize.Width;
break;
case DeviceOrientation.Landscape:
Height = Device.Info.PixelScreenSize.Height - 50;
Width = Device.Info.PixelScreenSize.Width;
break;
}
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
So, als already described, if we rotate the Device twice the content will be displayed, otherwise it won't. I think the problem is related to our bindings...
I should mention that we have some kind ob banner/headline on top of the WebView.
Code should also have a backing notification so that the view is aware of when its value changes.
Like
private string code;
public string Code {
get => code;
private set {
if (code == value)
return;
code = value;
OnPropertyChanged(nameof(Code));
}
}
If you walk through the step of why you have to turn twice, you will see that is why you have to do that.
When the value is first set it is blank.
On first turn the value is set by the event handler not since no notification is sent to the view it is not visibly changed.
On second turn the value is already set and when the view redraws, the value is shown in the view.
PRISM 6.2 / EntityFramework 6.3.1 / StockTrader UI / UnityContainer
I acutally having a project with PRISM 5.0.0 and want to update to PRISM 6.2. The project runs fine on 5.0.0, but when I'm updating to 6.2 I got the following problem with the InteractionRequest.
When I navigate to a view/viewmodel with Notifications for the first time, everything works and I can handle the InteractionRequests as usual. If I navigate back and navigate to the view again with a new object, the InteractionsRequest raised the notification twice. (...navigating back and go to again -> raised three times and so on).
In some reasons, the message "This Visual is not connected to a PresentationSource" will occur.
I figure out, that the _invocationCount and _invocationList on the InteractionRequest will not be set to "0"/"null" with PRISM 6.2. So, i think the InteractionRequest will call the notification more than one time. Attached, are screenshots from PRISM 5 and PRISM 6.2.
How can I handle this and solve the problem. In my opinion, it's not a big thing but I actually spent a lot of time to find a solution. Thanks...
PRISM 5.0.0 - working fine
PRISM 6.2 - issue
2017.02.22 Added Sourccode. Software is used to handle devices in datacenters. I deleted all unnecessary sourcecode, but with these files the problem still occur. Perhaps this is a try to find my issue....
Rackmodule.cs
-> Initialize Module Rack
public class RackModule : IModule
{
private readonly IRegionManager _regionManager;
private readonly IUnityContainer _container;
public RackModule(IRegionManager regionManager, IUnityContainer container)
{
_regionManager = regionManager;
_container = container;
}
public void Initialize()
{
_container.RegisterType<IRackViewModel, RackViewModel>(new ContainerControlledLifetimeManager());
_container.RegisterType<IRackToolbarViewModel, RackToolbarViewModel>(new ContainerControlledLifetimeManager());
_container.RegisterType<IRackStatusbarViewModel, RackStatusbarViewModel>(new ContainerControlledLifetimeManager());
_container.RegisterType<IRackSummaryViewModel, RackSummaryViewModel>(new ContainerControlledLifetimeManager());
_container.RegisterType<IGeneralDataViewModel, GeneralDataViewModel>(new ContainerControlledLifetimeManager());
_container.RegisterType<IPlanDataViewModel, PlanDataViewModel>(new ContainerControlledLifetimeManager());
_container.RegisterType<IRackDataViewModel, RackDataViewModel>(new ContainerControlledLifetimeManager());
_container.RegisterType<Object, GeneralDataView>(typeof(GeneralDataView).FullName);
IRegion region = this._regionManager.Regions["MainRegion"];
var rackView = _container.Resolve<RackView>();
region.Add(rackView, "RackView");
region.Activate(rackView);
IRegion toolbarregion = this._regionManager.Regions["RackToolbarRegion"];
var toolbarView = _container.Resolve<RackToolbarView>();
toolbarregion.Add(toolbarView, "RackToolbarView");
toolbarregion.Activate(toolbarView);
IRegion statusbarregion = this._regionManager.Regions["RackStatusbarRegion"];
var statusbarView = _container.Resolve<RackStatusbarView>();
statusbarregion.Add(statusbarView, "RackStatusbarView");
statusbarregion.Activate(statusbarView);
_container.RegisterType<Object, RackSummaryView>(typeof(RackSummaryView).FullName);
_regionManager.RequestNavigate(RegionNames.RackContentRegion, typeof(RackSummaryView).FullName);
}
}
RackSummaryViewModel.cs
-> Overview of racks. Go to RackDataView, when click on object
public class RackSummaryViewModel : BindableBase, IRackSummaryViewModel
{
private readonly IRegionManager _regionManager;
private readonly IEventAggregator _eventAggregator;
private readonly IUnityContainer _container;
public DelegateCommand<SearchEventArgs> OnSearch { get; private set; }
public DelegateCommand AdvancedRackSearchCommand { get; private set; }
public InteractionRequest<AdvancedRackSearchNotification> AdvancedSearchRequest { get; private set; }
private ObservableCollection<RackSummaryEntry> _racks;
public ObservableCollection<RackSummaryEntry> Racks
{
get { return _racks; }
private set {SetProperty(ref _racks, value);}
}
private RackSummaryEntry _currentRack;
public RackSummaryEntry CurrentRack
{
get { return _currentRack; }
set
{
if (SetProperty(ref _currentRack, value))
{
if (_currentRack != null)
{
var parameters = new NavigationParameters();
parameters.Add("RackID", _currentRack.PrimaryKey.ToString(GuidNumericFormatSpecifier));
_container.RegisterType<Object, RackDataView>(typeof(RackDataView).FullName);
_regionManager.RequestNavigate(RegionNames.RackContentRegion, new Uri(typeof(RackDataView).FullName + parameters, UriKind.Relative));
}
}
}
}
private const string GuidNumericFormatSpecifier = "N";
public RackSummaryViewModel(IEventAggregator eventAggregator, IRegionManager regionManager, IUnityContainer container)
{
_regionManager = regionManager;
_eventAggregator = eventAggregator;
_container = container;
ISessionFactory factory = new SessionFactory();
container.RegisterType<IRepository, Repository>(new InjectionConstructor(factory.CurrentUoW));
IUnitOfWork unitOfWork = factory.CurrentUoW;
IRepository localrepository = new Repository(unitOfWork);
var query = localrepository.GetList<DMS.Domain.Domain.Rack>();
Racks = new ObservableCollection<RackSummaryEntry>(query
.Select(x => new RackSummaryEntry
{
PrimaryKey = x.PrimaryKey,
Country = x.Location.Address.Country,
City = x.Location.Address.City,
Street = x.Location.Address.Street,
Building = x.Location.BuildingName,
RoomName = x.Location.RoomName,
RackName = x.RackName,
RackHeight = x.RackHeight
}).ToList());
}
}
RackDataViewModel.cs
-> Only Button "Save" und "Go Back"
public class RackDataViewModel : BindableBase, IRackDataViewModel, INavigationAware, IRegionMemberLifetime
{
private IRegionNavigationJournal _navigationJournal;
private readonly IRegionManager _regionManager;
private readonly IUnityContainer _container;
private readonly IEventAggregator _eventAggregator;
public DelegateCommand GoBackCommand { get; private set; }
public DelegateCommand SaveCommand { get; private set; }
public InteractionRequest<INotification> SaveNotificationRequest { get; private set; }
private const string RackIdKey = "RackID";
private const string EType = "EditType";
private const string GuidNumericFormatSpecifier = "N";
public DMS.Domain.Domain.Rack rack;
// [InjectionConstructor] check if necessary
public RackDataViewModel(IRegionManager regionManager, IRegionNavigationJournal navigationJournal, IUnityContainer container, IEventAggregator eventAggregator, ILoggerFactory logFactory)
{
_regionManager = regionManager;
_navigationJournal = navigationJournal;
_container = container;
_eventAggregator = eventAggregator;
GoBackCommand = new DelegateCommand(OnGoBackExecute);
SaveCommand = new DelegateCommand(OnSaveExecute);
SaveNotificationRequest = new InteractionRequest<INotification>();
}
private void OnGoBackExecute()
{
if (_navigationJournal != null)
{
while (_navigationJournal.CanGoBack)
_navigationJournal.GoBack();
_regionManager.Regions.Remove(RegionNames.RackGeneralDataRegion);
}
}
private void OnSaveExecute()
{
SaveNotificationRequest.Raise(new Notification { Content = "Save changes submitted", Title = "Save changes" });
}
public bool KeepAlive
{
get { return false; }
}
private Guid? GetRequestedRackId(NavigationContext navigationContext)
{
var rack = navigationContext.Parameters[RackIdKey];
Guid rackId;
if (rack != null)
{
if (rack is Guid)
rackId = (Guid)rack;
else
rackId = Guid.Parse(rack.ToString());
return rackId;
}
return null;
}
bool INavigationAware.IsNavigationTarget(NavigationContext navigationContext)
{
var type = navigationContext.Parameters[EType];
if (rack == null || ((string)type) == "New")
return true;
var requestedRackId = GetRequestedRackId(navigationContext);
return requestedRackId.HasValue && requestedRackId.Value == rack.PrimaryKey;
}
void INavigationAware.OnNavigatedFrom(NavigationContext navigationContext)
{
}
void INavigationAware.OnNavigatedTo(NavigationContext navigationContext)
{
Guid? rackId;
NavigationParameters parameters = new NavigationParameters();
string key = navigationContext.Parameters[RackIdKey].ToString();
rackId = GetRequestedRackId(navigationContext);
parameters = navigationContext.Parameters;
_regionManager.RequestNavigate(RegionNames.RackGeneralDataRegion, new Uri(typeof(GeneralDataView).FullName + parameters, UriKind.Relative));
_navigationJournal = navigationContext.NavigationService.Journal;
}
}
GeneralDataViewModel.cs
-> Is in region of RackDataView with the data of the racks
public class GeneralDataViewModel : BindableBase, IGeneralDataViewModel, INavigationAware
{
private IRegionNavigationJournal _navigationJournal;
private readonly IRegionManager _regionManager;
private readonly IRepository _repository;
private const string RackIdKey = "RackID";
public DMS.Domain.Domain.Rack Rack { get; set; }
public List<Location> Locations { get; set; }
public GeneralDataViewModel(IRegionManager regionManager, IRepository repository)
{
_regionManager = regionManager;
_repository = repository;
}
private Guid? GetRequestedRackId(NavigationContext navigationContext)
{
var rack = navigationContext.Parameters[RackIdKey];
Guid rackId;
if (rack != null)
{
if (rack is Guid)
rackId = (Guid)rack;
else
rackId = Guid.Parse(rack.ToString());
return rackId;
}
return null;
}
bool INavigationAware.IsNavigationTarget(NavigationContext navigationContext)
{
if (Rack == null)
return true;
var requestedRackId = GetRequestedRackId(navigationContext);
return requestedRackId.HasValue && requestedRackId.Value == Rack.PrimaryKey;
}
void INavigationAware.OnNavigatedFrom(NavigationContext navigationContext)
{
// Intentionally not implemented.
}
void INavigationAware.OnNavigatedTo(NavigationContext navigationContext)
{
var rackId = GetRequestedRackId(navigationContext);
Rack = _repository.GetEntity<DMS.Domain.Domain.Rack>(rackId);
_navigationJournal = navigationContext.NavigationService.Journal;
}
}
I'm trying to see how it would be possible to chain together x number of ObservableCollections.CollectionChanged event, exposed as a N level depth object tree to a single parent level CollectionChanged event that consumers can listen to? Essentially I want to funnel or bubble all child CollectionChanged events up to the top most parent. A number of solution I've noticed that tackle similar issues make an assumption of a fixed number of levels, say 2 deep. I idea is to support any level of depth.
Originally I had hoped I could just pass the instance of the FieldInfos to the child constructors and attach directly to the handler. However i get an error stating the "Event 'CollectionChanged' can only appear on the left hand side of+= or -=.
Thanks,
public class FieldInfos
{
public event NotifyCollectionChangedEventHandler CollectionChanged;
private ObservableCollection<Field> _fields;
public ObservableCollection<Field> Fields => _fields ?? (_fields = new ObservableCollection<Field>());
}
public class Field
{
public string Name;
private ObservableCollection<FieldInstance> _instances;
public ObservableCollection<FieldInstance> Instances => _instances ?? (_instances = new ObservableCollection<FieldInstance>());
}
public class FieldInstance
{
public string Id { get; set; }
}
The simplest approach is subclass the original ObservableCollection<T>.
You'd need at least one interface to avoid covariance problems. You can also have your own classes to implement the INotifyDescendantsChanged interface.
public interface INotifyDescendantsChanged
{
event NotifyCollectionChangedEventHandler DescendantsChanged;
}
public class ObservableBubbleCollection<T> : ObservableCollection<T>, INotifyDescendantsChanged
{
public event NotifyCollectionChangedEventHandler DescendantsChanged;
protected virtual void OnDescendantsChanged(object sender, NotifyCollectionChangedEventArgs e)
{
NotifyCollectionChangedEventHandler handler = DescendantsChanged;
if (handler != null)
handler(sender, e);
}
private readonly Func<T, INotifyDescendantsChanged> childSelector;
public ObservableBubbleCollection() { }
public ObservableBubbleCollection(Func<T, INotifyDescendantsChanged> childSelector)
{
this.childSelector = childSelector;
}
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
base.OnCollectionChanged(e);
OnDescendantsChanged(this, e);
if (childSelector == null)
return;
if (e.NewItems != null)
foreach (var item in e.NewItems.Cast<T>())
childSelector(item).DescendantsChanged += OnDescendantsChanged;
if (e.OldItems != null)
foreach (var item in e.OldItems.Cast<T>())
childSelector(item).DescendantsChanged -= OnDescendantsChanged;
}
}
To use it, replace instances of ObservableCollection and pass a selector to the collection.
public class FieldInfos
{
private ObservableBubbleCollection<Field> _fields;
public ObservableBubbleCollection<Field> Fields => _fields ?? (_fields = new ObservableBubbleCollection<Field>(fi => fi.Instances));
}
public class Field
{
public string Name;
private ObservableBubbleCollection<FieldInstance> _instances;
public ObservableBubbleCollection<FieldInstance> Instances => _instances ?? (_instances = new ObservableBubbleCollection<FieldInstance>());
}
public class FieldInstance
{
public string Id { get; set; }
}
static class Program
{
static void Main(string[] args)
{
var fi = new FieldInfos();
fi.Fields.DescendantsChanged += (sender, e) =>
{
Console.WriteLine("Change from {0}", sender.GetType());
};
var field = new Field();
fi.Fields.Add(field);
field.Instances.Add(new FieldInstance());
Console.ReadLine();
}
}
I'd like to be able to simulate the compass sensor when running a Windows Phone 7.1 in the emulator.
At this stage I don't particularly care what data the compass returns. Just that I can run against something when using the emulator to test the code in question.
I'm aware that I could deploy to my dev unlocked phone to test compass functionality but I've found the connection via the Zune software to drop out frequently.
Update
I've looked into creating my own wrapper class that could simulate the compass when running a debug build and the compass isn't otherwise supported.
The Microsoft.Devices.Sensors.CompassReading struct has me a bit stumpted. Because it is a struct where the properties can only be set internally I can't inherit from it to provide my own values back. I looked at using reflection to brute force some values in but Silverlight doesn't appear to allow it.
as you already noticed I had a similar problem. when I mocked the compass sensor, I also had difficulties because you cannot inherite from the existing classes and write your own logic. Therefore I wrote my own compass interface which is the only compass functionality used by my application. Then there are two implementations, one wrapper to the WP7 compass functionalities and my mock compass.
I can show you some code, but not before weekend as I'm not at my delevopment machine atm.
Edit:
You already got it but for other people who have the same problem I'll add my code. As I already said, I wrote an interface and two implementations, one for the phone and a mock implementation.
Compass Interface
public interface ICompass
{
#region Methods
void Start();
void Stop();
#endregion
#region Properties
CompassData CurrentValue { get; }
bool IsDataValid { get; }
TimeSpan TimeBetweenUpdates { get; set; }
#endregion
#region Events
event EventHandler<CalibrationEventArgs> Calibrate;
event EventHandler<CompassDataChangedEventArgs> CurrentValueChanged;
#endregion
}
Used data classes and event args
public class CompassData
{
public CompassData(double headingAccurancy, double magneticHeading, Vector3 magnetometerReading, DateTimeOffset timestamp, double trueHeading)
{
HeadingAccuracy = headingAccurancy;
MagneticHeading = magneticHeading;
MagnetometerReading = magnetometerReading;
Timestamp = timestamp;
TrueHeading = trueHeading;
}
public CompassData(CompassReading compassReading)
{
HeadingAccuracy = compassReading.HeadingAccuracy;
MagneticHeading = compassReading.MagneticHeading;
MagnetometerReading = compassReading.MagnetometerReading;
Timestamp = compassReading.Timestamp;
TrueHeading = compassReading.TrueHeading;
}
#region Properties
public double HeadingAccuracy { get; private set; }
public double MagneticHeading { get; private set; }
public Vector3 MagnetometerReading { get; private set; }
public DateTimeOffset Timestamp { get; private set; }
public double TrueHeading { get; private set; }
#endregion
}
public class CompassDataChangedEventArgs : EventArgs
{
public CompassDataChangedEventArgs(CompassData compassData)
{
CompassData = compassData;
}
public CompassData CompassData { get; private set; }
}
WP7 implementation
public class DeviceCompass : ICompass
{
private Compass _compass;
#region Implementation of ICompass
public void Start()
{
if(_compass == null)
{
_compass = new Compass {TimeBetweenUpdates = TimeBetweenUpdates};
// get TimeBetweenUpdates because the device could have change it to another value
TimeBetweenUpdates = _compass.TimeBetweenUpdates;
// attach to events
_compass.CurrentValueChanged += CompassCurrentValueChanged;
_compass.Calibrate += CompassCalibrate;
}
_compass.Start();
}
public void Stop()
{
if(_compass != null)
{
_compass.Stop();
}
}
public CompassData CurrentValue
{
get { return _compass != null ? new CompassData(_compass.CurrentValue) : default(CompassData); }
}
public bool IsDataValid
{
get { return _compass != null ? _compass.IsDataValid : false; }
}
public TimeSpan TimeBetweenUpdates { get; set; }
public event EventHandler<CalibrationEventArgs> Calibrate;
public event EventHandler<CompassDataChangedEventArgs> CurrentValueChanged;
#endregion
#region Private methods
private void CompassCalibrate(object sender, CalibrationEventArgs e)
{
EventHandler<CalibrationEventArgs> calibrate = Calibrate;
if (calibrate != null)
{
calibrate(sender, e);
}
}
private void CompassCurrentValueChanged(object sender, SensorReadingEventArgs<CompassReading> e)
{
EventHandler<CompassDataChangedEventArgs> currentValueChanged = CurrentValueChanged;
if (currentValueChanged != null)
{
currentValueChanged(sender, new CompassDataChangedEventArgs(new CompassData(e.SensorReading)));
}
}
#endregion
}
Mock implementation
public class MockCompass : ICompass
{
private readonly Timer _timer;
private CompassData _currentValue;
private bool _isDataValid;
private TimeSpan _timeBetweenUpdates;
private bool _isStarted;
private readonly Random _random;
public MockCompass()
{
_random = new Random();
_timer = new Timer(TimerEllapsed, null, Timeout.Infinite, Timeout.Infinite);
_timeBetweenUpdates = new TimeSpan();
_currentValue = new CompassData(0, 0, new Vector3(), new DateTimeOffset(), 0);
}
#region Implementation of ICompass
public void Start()
{
_timer.Change(0, (int)TimeBetweenUpdates.TotalMilliseconds);
_isStarted = true;
}
public void Stop()
{
_isStarted = false;
_timer.Change(Timeout.Infinite, Timeout.Infinite);
_isDataValid = false;
}
public CompassData CurrentValue
{
get { return _currentValue; }
}
public bool IsDataValid
{
get { return _isDataValid; }
}
public TimeSpan TimeBetweenUpdates
{
get { return _timeBetweenUpdates; }
set
{
_timeBetweenUpdates = value;
if (_isStarted)
{
_timer.Change(0, (int) TimeBetweenUpdates.TotalMilliseconds);
}
}
}
public event EventHandler<CalibrationEventArgs> Calibrate;
public event EventHandler<CompassDataChangedEventArgs> CurrentValueChanged;
#endregion
#region Private methods
private void TimerEllapsed(object state)
{
_currentValue = new CompassData(_random.NextDouble()*5,
(_currentValue.MagneticHeading + 0.1)%360,
_currentValue.MagnetometerReading,
new DateTimeOffset(DateTime.UtcNow),
(_currentValue.TrueHeading + 0.1)%360);
_isDataValid = true;
EventHandler<CompassDataChangedEventArgs> currentValueChanged = CurrentValueChanged;
if(currentValueChanged != null)
{
currentValueChanged(this, new CompassDataChangedEventArgs(_currentValue));
}
}
#endregion
}