System.Device.Location.GeoCoordinateWatcher.Position.Location.Speed always is NaN - c#

I'm making a simple app for my WP8.1 device, which will be track my maximum speed. I'm using System.Device.Location.GeoCoordinateWatcher for this. I can detect my position, but speed always is NaN. And I don't understand, why. What is wrong? Thanks for any help or info. It is my full code below:
namespace SpeedTracker
{
public partial class MainPage : PhoneApplicationPage
{
GeoCoordinateWatcher watcher;
double maxSpeed = 0.0;
public MainPage()
{
InitializeComponent();
}
private void StartTrackingBtn_Click(object sender, RoutedEventArgs e)
{
this.watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default);
this.watcher.MovementThreshold = 10;
this.watcher.StatusChanged += new EventHandler<GeoPositionStatusChangedEventArgs>(watcher_StatusChanged);
this.watcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(watcher_PositionChanged);
this.watcher.Start();
}
private void StopTrackingBtn_Click(object sender, RoutedEventArgs e)
{
this.watcher.StatusChanged -= new EventHandler<GeoPositionStatusChangedEventArgs>(watcher_StatusChanged);
this.watcher.PositionChanged -= new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(watcher_PositionChanged);
this.watcher.Stop();
}
private void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
{
if (this.watcher.Position.Location.IsUnknown != true)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
this.maxSpeed = Math.Max(this.maxSpeed, e.Position.Location.Speed);
this.SpeedValueTxblck.Text = this.maxSpeed.ToString();
});
}
else
{
this.SpeedValueTxblck.Text = "Please wait while your prosition is determined...";
}
}
private void watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
{
switch (e.Status)
{
case GeoPositionStatus.Disabled:
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
this.SpeedValueTxblck.Text = "Location Service is not enabled on the device";
});
break;
case GeoPositionStatus.NoData:
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
this.SpeedValueTxblck.Text = "The Location Service is working, but it cannot get location data";
});
break;
default:
break;
}
}
private void GetLocationCourseAndSpeed()
{
this.watcher.TryStart(true, TimeSpan.FromMilliseconds(1000));
if (watcher.Position.Location.IsUnknown != true)
{
GeoCoordinate coord = watcher.Position.Location;
this.maxSpeed = Math.Max(this.maxSpeed, coord.Speed);
this.SpeedValueTxblck.Text = this.maxSpeed.ToString();
}
else
{
this.SpeedValueTxblck.Text = "Unknown";
}
}
}
}

I don't believe that there is an issue with your code. I am doing a similar function on a device that has WiFi, Cellular and GPS installed. It appears that cellular is the fastest to lock in and does not ever provide any speed data. However, when I disable cell and WiFi, I get speed data from the GPS sensor just fine. If you have dedicated GPS, I would try doing the same thing. If not, you may need it to get what you are looking for.

Related

Event Handler Fires Twice When Plugging/Unplugging USB Serial Port

I am writing a program which is supposed to detect when a USB serial device is plugged in and then log on to the new com port. The code below works wonderfully, but I have noticed in debugging the code and stepping through it that the event handler "DetectChange" fires twice. I'm not sure that this is normal, or an action of the debugger.
In any case, the code works, but I am new at event handling and I would like to make sure that I am not going to cause any issues as I add more code to actually read and write from the serial port.
(I got some of this code from stackoverflow, but I have misplaced my paper with names for attribution. If you see your code below, my heartfelt thanks.)
using System;
using System.IO.Ports;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Management;
using System.Threading;
namespace SerialTest
{
public partial class Form1 : Form
{
SerialMethods serialMethods = new SerialMethods();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
loadCmdBox();
}
private void CmdBoxPort_SelectedIndexChanged(object sender, EventArgs e)
{
handleComPort();
}
private void handleComPort()
{
// Set the right port for the selected item.
// The portname is based on the "COMx" part of the string (SelectedItem)
string item = CmdBoxPort.SelectedItem.ToString();
// Search for the expression "(COM" in the "selectedItem" string
if (item.Contains("(COM"))
{
// Get the index number where "(COM" starts in the string
int indexOfCom = item.IndexOf("(COM");
// Set PortName to COMx based on the expression in the "selectedItem" string
// It automatically gets the correct length of the COMx expression to make sure
// that also a COM10, COM11 and so on is working properly.
string PortName = item.Substring(indexOfCom + 1, item.Length - indexOfCom - 2);
if (serialMethods._serialPort.IsOpen)
{
serialMethods._serialPort.Close();
serialMethods.Connect(PortName);
label5.Text = "Active Port: " + PortName;
}
else
{
serialMethods.Connect(PortName);
label5.Text = PortName;
}
}
else
return;
}
private void loadCmdBox()
{
// Get all serial (COM)-ports you can see in the devicemanager
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\cimv2",
"SELECT * FROM Win32_PnPEntity WHERE ClassGuid=\"{4d36e978-e325-11ce-bfc1-08002be10318}\"");
// Sort the items in the combobox
CmdBoxPort.Sorted = true;
// Add all available (COM)-ports to the combobox
foreach (System.Management.ManagementObject queryObj in searcher.Get().Cast<ManagementObject>())
{
CmdBoxPort.Items.Add(queryObj["Caption"]);
}
SerialPortService.PortsChanged += (sender1, changedArgs) => DetectChange(changedArgs.EventType);
label2.Text = "";
label3.Text = "";
label4.Text = "";
}
protected Task<Task> getSerPorts()
{
CmdBoxPort.Text = "";
CmdBoxPort.Update();
if (!String.IsNullOrEmpty(CmdBoxPort.Text))
{
handleComPort();
return Task.FromResult(Task.CompletedTask);
}
else
{
loadCmdBox();
return Task.FromResult(Task.CompletedTask);
}
}
private void ExitButton_Click(object sender, EventArgs e)
{
SerialPortService.CleanUp();
this.Close();
}
private void RefreshButton_Click(object sender, EventArgs e)
{
refresh();
}
protected Task<Task> refresh()
{
label2.Text = "";
label3.Text = "";
label4.Text = "";
CmdBoxPort.Items.Clear();
getSerPorts();
return Task.FromResult(Task.CompletedTask);
}
protected virtual void DetectChange(EventType changedArgs)
{
if (changedArgs == EventType.Insertion)
{
try
{
Task tr = (Task)Invoke(new Action( () => { getSerPorts(); }));
Task rr = (Task)Invoke(new Action(() => { refresh(); }));
}
catch (Exception ex) { MessageBox.Show("Exception at insertion invoke method " + ex, "Exception", MessageBoxButtons.OK); }
}
else if (changedArgs == EventType.Removal)
{
try
{
Task tr = (Task)Invoke(new Action( () => { getSerPorts(); }));
Task rr = (Task)Invoke(new Action(() => { refresh(); }));
}
catch (Exception ex) { MessageBox.Show("Exception at removal invoke method " + ex, "Exception", MessageBoxButtons.OK); }
}
return;
}
}
public static class SerialPortService
{
private static SerialPort _serialPort;
private static string[] _serialPorts;
private static ManagementEventWatcher arrival;
private static ManagementEventWatcher removal;
private static readonly SerialMethods SD = new SerialMethods();
static SerialPortService()
{
_serialPorts = SerialPort.GetPortNames();
MonitorDeviceChanges();
}
public static void CleanUp()
{
arrival.Stop();
removal.Stop();
}
public static event EventHandler<PortsChangedArgs> PortsChanged;
private static void MonitorDeviceChanges()
{
try
{
var deviceArrivalQuery = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2");
var deviceRemovalQuery = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 3");
arrival = new ManagementEventWatcher(deviceArrivalQuery);
removal = new ManagementEventWatcher(deviceRemovalQuery);
arrival.EventArrived += (o, args) => RaisePortsChangedIfNecessary(EventType.Insertion);
removal.EventArrived += (sender, eventArgs) => RaisePortsChangedIfNecessary(EventType.Removal);
// Start listening for events
arrival.Start();
removal.Start();
}
catch (ManagementException err)
{
MessageBox.Show("Management exception = " + err, "Info", MessageBoxButtons.OK);
}
}
private static void RaisePortsChangedIfNecessary(EventType eventType)
{
lock (_serialPorts)
{
var availableSerialPorts = SerialPort.GetPortNames();
if (eventType == EventType.Insertion)
{
var added = availableSerialPorts.Except(_serialPorts).ToArray();
_serialPorts = availableSerialPorts;
PortsChanged.Raise(null, new PortsChangedArgs(eventType, added));
}
else if (eventType == EventType.Removal)
{
var removed = _serialPorts.Except(availableSerialPorts).ToArray();
_serialPorts = availableSerialPorts;
PortsChanged.Raise(null, new PortsChangedArgs(eventType, removed));
}
}
}
public static void Raise<T>(this EventHandler<T> handler, object sender, T args) where T : EventArgs
{
handler?.Invoke(sender, args);
}
}
public enum EventType
{
Insertion,
Removal,
}
public class PortsChangedArgs : EventArgs
{
private readonly EventType _eventType;
private readonly string[] _serialPorts;
public PortsChangedArgs(EventType eventType, string[] serialPorts)
{
_eventType = eventType;
_serialPorts = serialPorts;
}
public string[] SerialPorts => _serialPorts;
public EventType EventType => _eventType;
}
}
Just took a short look at this. It seems like getSerPorts() will always execute loadCmdBox() (CmdBoxPort.Text = ""; ... if (!String.IsNullOrEmpty(CmdBoxPort.Text))) that will attach a new event handler (previous attached event handlers will not be removed by attaching a new one).
You should either remove the existing event handler befor attaching a new one or only attach the event handler once.

Unity MobAd Rewarded Video is not functioning

i have got a strange issue. I've implemented an ad code to the my game and when my player dies, im asking that the player would watch the ad and reborn. When i build and install the apk to my phone, in first play everything works very well. After second attemp, my rewarderAdd.OnAdRewarded function is not working at all. Im controlling the ad state in the game and in second play, i can see that the reward system is not functionning. here is my code
void Start()
{
adState = 0;
gameOverScript = GameObject.Find("GameOver").GetComponent<GameOverCode>();
kingSCript = GameObject.FindGameObjectWithTag("Player").GetComponent<RedKing>();
isCompleted = false;
RequestRewardedVideo();
this.rewardedAd.OnAdRewarded += RewardPlayer;
// this.rewardedAd.OnAdClosed += PlayerClosed;
}
public void RequestRewardedVideo()
{
rewardedAd = RewardBasedVideoAd.Instance;
// Create an empty ad request.
AdRequest request = new AdRequest.Builder().Build();
// Load the rewarded ad with the request.
this.rewardedAd.LoadAd(request,rewarderID);
if(rewardedAd.IsLoaded() == true)
{
adState = 5;
}
}
private void RewardPlayer(object sender, EventArgs e)
{
isCompleted = true;
adState = 1;
Reward();
}
private void PlayerClosed(object sender, EventArgs e)
{
if(adState != 1)
{
adState = -1;
}
}
public void Reward()
{
adState = 1;
kingSCript.Reborn();
}
public void ShowVideoRewardAd()
{
if (this.rewardedAd.IsLoaded())
{
adState = 2;
isLoaded = true;
this.rewardedAd.Show();
}
else
{
isLoaded = false;
}
}
Why the ad state is not working in second attemp? Every time i re-upload the scene so every code should work as like as the first time but its not working at all!
the solution is use -= functions for all of the methods. check this script out
void Start()
{
gameOverScript = GameObject.Find("GameOver").GetComponent<GameOverCode>();
kingScript = GameObject.FindGameObjectWithTag("Player").GetComponent<RedKing>();
adState = 0;
rewardedID = "ca-app-pub-3940256099942544/5224354917";
rewardedAd = RewardBasedVideoAd.Instance;
isAdLoaded = false;
RequestRewardedAd();
}
void Update()
{
Debug.Log(adState);
if (rewardedAd.IsLoaded())
{
isAdLoaded = true;
Debug.Log("burda");
}
if(adState == 1)
{
kingScript.Reborn();
}
if(adState == -1)
{
gameOverScript.FinishTheGame();
}
}
public void RequestRewardedAd()
{
AdRequest request = AdRequestBuild();
rewardedAd.LoadAd(request, rewardedID);
rewardedAd.OnAdLoaded += this.HandleOnRewardedAdLoaded;
rewardedAd.OnAdRewarded += this.HandleOnAdRewarded;
rewardedAd.OnAdClosed += this.HandleOnRewardedAdClosed;
}
public void HandleOnRewardedAdLoaded(object sender, EventArgs args)
{
Debug.Log("loaded");
adState = 3;
}
public void HandleOnAdRewarded(object sender, EventArgs args)
{
adState = 1;
}
public void HandleOnRewardedAdClosed(object sender, EventArgs args)
{
rewardedAd.OnAdLoaded -= this.HandleOnRewardedAdLoaded;
rewardedAd.OnAdRewarded -= this.HandleOnAdRewarded;
rewardedAd.OnAdClosed -= this.HandleOnRewardedAdClosed;
if(adState != 1)
{
playerAdCount = PlayerPrefs.GetInt("PlayerDontWatchTheAds");
playerAdCount++;
PlayerPrefs.SetInt("PlayerDontWatchTheAds", playerAdCount);
adState = -1;
}
}
public void ShowRewardAd()
{
if (rewardedAd.IsLoaded())
{
rewardedAd.Show();
}
}
AdRequest AdRequestBuild()
{
return new AdRequest.Builder().Build();
}

Getting media player state in windows phone 7

I have amended my code in App.xaml.cs
But i have an error at "this.ApplicationLifetimeObjects.Add(new XNAAsyncDispatcher(TimeSpan.FromMilliseconds(50)));" (Placed at end of my App.xaml.cs)
The error is
"System.TimeSpan.FromMilliseconds(double) is a method but is used like a type"
System.Windows.Application.ApplicationLifetimeObjects is a property but is used like a type
Identifier expected
Invalid token '(' in a class, struct or interface member declaration
Method must have a return type
Below is the whole piece of my App.xaml.cs
namespace Alarm_Clock
{
public class GlobalData
{
public BitmapImage bitmapImage;
}
public partial class App : Application
{
public static GlobalData globalData;
public class XNAAsyncDispatcher : IApplicationService
{
private readonly DispatcherTimer _frameworkDispatcherTimer;
public XNAAsyncDispatcher(TimeSpan dispatchInterval)
{
_frameworkDispatcherTimer = new DispatcherTimer();
_frameworkDispatcherTimer.Tick += frameworkDispatcherTimer_Tick;
_frameworkDispatcherTimer.Interval = dispatchInterval;
}
void IApplicationService.StartService(ApplicationServiceContext context) { _frameworkDispatcherTimer.Start(); }
void IApplicationService.StopService() { _frameworkDispatcherTimer.Stop(); }
void frameworkDispatcherTimer_Tick(object sender, EventArgs e) { FrameworkDispatcher.Update(); }
}
public static string imagePath
{
//get { return "PhotoNote_{0:yyyy-MM-dd_hh-mm-ss-tt}.jpg"; }
get;
set;
}
/// <summary>
/// Provides easy access to the root frame of the Phone Application.
/// </summary>
/// <returns>The root frame of the Phone Application.</returns>
public PhoneApplicationFrame RootFrame { get; private set; }
//Global variables for the WriteableBitmap objects used throughout the application.
public static WriteableBitmap CapturedImage;
/// <summary>
/// Constructor for the Application object.
/// </summary>
public App()
{
globalData = new GlobalData();
globalData.bitmapImage = new BitmapImage();
// Global handler for uncaught exceptions.
UnhandledException += Application_UnhandledException;
// Show graphics profiling information while debugging.
if (System.Diagnostics.Debugger.IsAttached)
{
// Display the current frame rate counters.
Application.Current.Host.Settings.EnableFrameRateCounter = true;
// Show the areas of the app that are being redrawn in each frame.
//Application.Current.Host.Settings.EnableRedrawRegions = true;
// Enable non-production analysis visualization mode,
// which shows areas of a page that are being GPU accelerated with a colored overlay.
//Application.Current.Host.Settings.EnableCacheVisualization = true;
}
// Standard Silverlight initialization
InitializeComponent();
// Phone-specific initialization
InitializePhoneApplication();
}
// Code to execute when the application is launching (eg, from Start)
// This code will not execute when the application is reactivated
private void Application_Launching(object sender, LaunchingEventArgs e)
{
}
// Code to execute when the application is activated (brought to foreground)
// This code will not execute when the application is first launched
private void Application_Activated(object sender, ActivatedEventArgs e)
{
}
// Code to execute when the application is deactivated (sent to background)
// This code will not execute when the application is closing
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
}
// Code to execute when the application is closing (eg, user hit Back)
// This code will not execute when the application is deactivated
private void Application_Closing(object sender, ClosingEventArgs e)
{
}
// Code to execute if a navigation fails
private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
// A navigation has failed; break into the debugger
System.Diagnostics.Debugger.Break();
}
}
// Code to execute on Unhandled Exceptions
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
// An unhandled exception has occurred; break into the debugger
System.Diagnostics.Debugger.Break();
}
}
#region Phone application initialization
// Avoid double-initialization
private bool phoneApplicationInitialized = false;
// Do not add any additional code to this method
private void InitializePhoneApplication()
{
if (phoneApplicationInitialized)
return;
// Create the frame but don't set it as RootVisual yet; this allows the splash
// screen to remain active until the application is ready to render.
RootFrame = new PhoneApplicationFrame();
RootFrame.Navigated += CompleteInitializePhoneApplication;
// Handle navigation failures
RootFrame.NavigationFailed += RootFrame_NavigationFailed;
// Ensure we don't initialize again
phoneApplicationInitialized = true;
}
// Do not add any additional code to this method
private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e)
{
// Set the root visual to allow the application to render
if (RootVisual != RootFrame)
RootVisual = RootFrame;
// Remove this handler since it is no longer needed
RootFrame.Navigated -= CompleteInitializePhoneApplication;
}
#endregion
this.ApplicationLifetimeObjects.Add(new XNAAsyncDispatcher(TimeSpan.FromMilliseconds(50)));
}
}
The pause just dont work in my code below.
This is my whole piece of code:
namespace Alarm_Clock
{
public partial class AlarmRing : PhoneApplicationPage
{
int songSelectedIndex;
public AlarmRing()
{
InitializeComponent();
SupportedOrientations = SupportedPageOrientation.Portrait;
//Get the DateTime.Now and place it into "timeTxtBlock" text block
timeTxtBlock.Text = DateTime.Now.ToShortTimeString();
//Read from Isolated storage queSetting.txt for the number of question to answer by the user
//Read from Isolated storage music.txt for the selected music to play when the alarm ring
var isoFile = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication();
try
{
StreamReader readFile = new StreamReader(new IsolatedStorageFileStream("SettingFolder\\music.txt", FileMode.Open, myStore));
songSelectedIndex = Convert.ToInt16(readFile.ReadLine());
readFile.Close();
}
catch (Exception)
{
//If the user did not select the music to be played when the alarm ring it will play the first music by default
songSelectedIndex = 0;
}
using (var ml = new MediaLibrary())
{
//Play the music using media player from the song collection
FrameworkDispatcher.Update();
MediaPlayer.MediaStateChanged += new EventHandler<EventArgs>(MediaPlayer_MediaStateChanged);
MediaPlayer.Play(ml.Songs[songSelectedIndex]);
MediaPlayer.IsRepeating = true;
MediaPlayer.IsMuted = false;
MediaPlayer.IsShuffled = false;
MediaPlayer.IsVisualizationEnabled = false;
}
//Load code
loadtime();
}
static void MediaPlayer_MediaStateChanged(object sender, EventArgs e)
{
if (MediaPlayer.State == MediaState.Paused)
{
MediaPlayer.Resume();
}
}
void loadtime()
{
ringingAlarm.Begin();
//Get the DateTime.Now
String timeNow = DateTime.Now.ToShortTimeString();
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
foreach (string labels in storage.GetFileNames("*"))
{
XElement _xml;
IsolatedStorageFileStream location = new IsolatedStorageFileStream(labels, System.IO.FileMode.Open, storage);
System.IO.StreamReader file = new System.IO.StreamReader(location);
_xml = XElement.Parse(file.ReadToEnd());
if (_xml.Name.LocalName != null)
{
XAttribute time = _xml.Attribute("time");
//Get the day of the week
String dayOfWeek = DateTime.Now.DayOfWeek.ToString("F");
if (timeNow == time.Value.ToString())
{
//"textBlock2" text block will display the label of the alarm
textBlock2.Text = labels;
}
}
file.Dispose();
location.Dispose();
}
}
}
string settingQues;
string settingQuesPassToGame;
string format;
string format1;
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
//Try get the value of number of question to be answered by the user that is pass over from setClockPage.xaml
if (NavigationContext.QueryString.TryGetValue("settingQues", out settingQues))
settingQuesPassToGame = settingQues;
//Try get the format that is passed over
if (NavigationContext.QueryString.TryGetValue("format", out format))
format1 = format;
}
//Display a pop up message box with instruction
//And navigate to "Start.xaml"
private void gameBtn_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("To dismiss alarm" + System.Environment.NewLine + "- Answer selected IQ question" + System.Environment.NewLine + "- With all correct answer");
NavigationService.Navigate(new Uri("/Start.xaml?ringingAlarmTitle=" + textBlock2.Text + "&ringingAlarmTime=" + timeTxtBlock.Text + "&format1=" + format1, UriKind.Relative));
}
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
e.Cancel = true;
}
public Visibility visible { get; set; }
}
}
When I place MediaPlayer.MediaStateChanged += new EventHandler<EventArgs>(MediaPlayer_MediaStateChanged); at the constructor there is an error.
The error is MediaPlayer.MediaStateChanged += new EventHandler<EventArgs>(MediaPlayer_MediaStateChanged) is a method but is use like a type.
I have changed my code but it still dosent work
static void MediaPlayer_MediaStateChanged(object sender, EventArgs e)
{
if (MediaPlayer.State == MediaState.Paused)
{
MediaPlayer.Resume();
}
}
You have to dispatch XNA Events manual in Windows Phone 7 Apps:
public class XNAAsyncDispatcher : IApplicationService
{
private readonly DispatcherTimer _frameworkDispatcherTimer;
public XNAAsyncDispatcher(TimeSpan dispatchInterval)
{
_frameworkDispatcherTimer = new DispatcherTimer();
_frameworkDispatcherTimer.Tick += frameworkDispatcherTimer_Tick;
_frameworkDispatcherTimer.Interval = dispatchInterval;
}
void IApplicationService.StartService(ApplicationServiceContext context) { _frameworkDispatcherTimer.Start(); }
void IApplicationService.StopService() { _frameworkDispatcherTimer.Stop(); }
void frameworkDispatcherTimer_Tick(object sender, EventArgs e) { FrameworkDispatcher.Update(); }
}
Add this to the end of your public App()
public App()
{
// Other stuff
// End
this.ApplicationLifetimeObjects.Add(new XNAAsyncDispatcher(TimeSpan.FromMilliseconds(50)));
}
Complete Guide: http://msdn.microsoft.com/library/ff842408.aspx

C# Sql Server "loading window"

This is my first post here, but I've using this site regularly to help me with my own app's, and I should say that this site has been a great help to me, so thanks to everyone.
Now my question:
I'm developing my first software app that exchanges data between a sql server and the app itself. It's beeing developed in C#. Saving or retreiving data from the sql server database is no problem.
What I want is a way to inform the user of the delay between the local machine (where the app is installed) and the server. I can make some animations or simply display some text messages. What I need help with is how to create the code that activates/fires/runs when that server communication time is running.
If you can't understand the idea, picture a video game. When it's loading (in some games) you can see the loading screen before the game starts. I need some code that displays that "loading window" when the the app is downloading or uploading data from/to the server.
I would appreciate any code example or web site recommendation.
PS: Sorry for the extensive text, but I want to make sure everyone understand so I don't have to repeat it again :P
How do I implement a progress bar in C#?
How to create a smooth progress bar in Visual C#
ProgressBar Class
I have developed a simple PleaseWait class 2 years ago, but I didn't update this class, It works very well, have look hope this will give you an idea to implement your logic.
public partial class frmWait : Form
{
public frmWait()
{
InitializeComponent();
}
bool _isMoving = false;
int _moveStart_x = 0;
int _moveStart_y = 0;
private void tmrProgress_Tick(object sender, EventArgs e)
{
if (barProgress.Value == barProgress.Maximum)
barProgress.Value = barProgress.Minimum;
else
barProgress.Value += 1;
}
private void btnCancel_Click(object sender, EventArgs e)
{
Close();
PleaseWait.Abort();
}
protected override CreateParams CreateParams
{
get
{
System.Windows.Forms.CreateParams p = base.CreateParams;
p.ClassStyle += 0x20000;
p.ExStyle += 0x8000000;
return p;
}
}
protected override void WndProc(ref Message m)
{
const int WM_NCHITTEST = 132;
base.WndProc(ref m);
switch (m.Msg)
{
case WM_NCHITTEST:
if (m.Result.ToInt32() == 1)
m.Result = new IntPtr(2);
break;
}
}
private void panelEx1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
_isMoving = true;
_moveStart_x = e.X;
_moveStart_y = e.Y;
}
}
private void panelEx1_MouseUp(object sender, MouseEventArgs e)
{
_isMoving = false;
}
private void pnlContainer_MouseMove(object sender, MouseEventArgs e)
{
if (_isMoving)
this.Location = new Point(Location.X + e.X - _moveStart_x, Location.Y + e.Y - _moveStart_y);
}
}
public class PleaseWait
{
#region Static Operations
private static Boolean _isAborted = false;
private static Boolean _isVisible = false;
private static frmWait _waitForm;
private static String _waitingState = "";
private static Boolean _autoClose = false;
private static Boolean _cancelable = false;
private static System.Threading.Thread _waiterThred;
public delegate void CancelButtonPressed();
public static event CancelButtonPressed OnCancel;
public static Boolean AutoClose
{
get { return PleaseWait._autoClose; }
set { PleaseWait._autoClose = value; }
}
public static string WaitingState
{
get { return PleaseWait._waitingState; }
set { PleaseWait._waitingState = value; }
}
public static bool IsVisible
{
get { return _isVisible; }
internal set { _isVisible = value; }
}
public static void ShowPleaseWait()
{
ShowPleaseWait("", _autoClose, false);
}
public static void ShowPleaseWait(string waitingState)
{
ShowPleaseWait(waitingState, _autoClose, false);
}
public static void ShowPleaseWait(bool autoClose)
{
ShowPleaseWait("", autoClose, false);
}
public static void ShowPleaseWait(string waitingState, bool autoClose, bool cancelable)
{
if (_waiterThred != null)
{
if (_isVisible)
{
// the please wait it woking, just continue and apply the changes
_waitingState = waitingState;
_autoClose = autoClose;
_cancelable = cancelable;
return;
}
else
{
_waiterThred.Abort();
_waiterThred = null;
}
}
_waitingState = waitingState;
_autoClose = autoClose;
_cancelable = cancelable;
_isAborted = false;
_isVisible = false;
if (_autoClose)
Application.Idle += new EventHandler(Application_Idle);
_waiterThred = new System.Threading.Thread(DisplayWaitingForm);
_waiterThred.IsBackground = true;
_waiterThred.Name = "Please Wait....";
_waiterThred.Start();
Application.DoEvents();
}
public static void Abort()
{
_isAborted = true;
}
private static void Application_Idle(object sender, EventArgs e)
{
if (_autoClose)
_isAborted = true;
}
private static void DisplayWaitingForm()
{
if (_waitForm != null)
{
if (!_waitForm.IsDisposed)
_waitForm.Dispose();
_waitForm = null;
_isVisible = false;
}
try
{
if (_isAborted)
return;
_waitForm = new frmWait();
if (_cancelable)
{
_waitForm.btnCancel.Enabled = true;
_waitForm.btnCancel.Click += new EventHandler(btnCancel_Click);
}
try
{
_isVisible = true;
_waitForm.Show();
_waitForm.Focus();
while (!_isAborted)
{
System.Threading.Thread.Sleep(15);
_waitForm.lblMessage.Text = _waitingState;
Application.DoEvents();
_waitForm.lblMessage.Text = _waitingState;
}
_isVisible = false;
}
finally
{
FreeWaitingForm();
}
}
finally
{
_isVisible = false;
}
}
static void btnCancel_Click(object sender, EventArgs e)
{
if (_waitForm.InvokeRequired)
{
_waitForm.BeginInvoke(new EventHandler(btnCancel_Click), new object[] { e });
}
else
{
if (OnCancel != null)
OnCancel.Invoke();
}
}
private static void FreeWaitingForm()
{
_waitingState = "";
_isVisible = false;
if (_waitForm == null)
{
return;
}
_waitForm.Hide();
if (!_waitForm.IsDisposed)
_waitForm.Dispose();
_waitForm = null;
}
#endregion
}
use like following code :
PleaseWait.ShowPleaseWait("Please wait", true, false);
// If second param is true then it will close the form automatically.
// If third param is true the it will expose a cancel button, so you can cancel your Asynchronous operations.
I didn't insert design code, you can understand by looking at code.
hope this help.
First let me thank you for your replies.
Toby your answer got me thinking about thread monitoring my sql connections but it was a bit tricky and confusing since the app is still in develop and will use a lot more connections.
S.Amani answer it wasn't quite what I want, but thanks to that I found a easier way. I created a form (could be anything else), placed a label saying: Saving To Data Base, took out the top bar, defined location and defined it's parent to be disabled when shown and enabled when closed. The following code is what I put inside my DataBaseInteractionClass
private Wait myCustomWaitDialog = new Wait(); // My Waiting form
private void SaveToDatabase(myObjectToSave obj) // Method called to save data do DB
{
// Create the connections and queries
(...)
// This is what I did
// Show Waiting Form
myCustomWaitDialog.Show();
// Instanciate the command that will carry the query and to DB
SqlCommand command = new SqlCommand(Queries.GetData(code), conn);
// This is important
//Create event that will fire when the command completes
command.StatementCompleted += new StatementCompletedEventHandler(command_StatementCompleted);
// Execute the transaction
SqlDataReader reader = command.ExecuteReader();
// Rest of the code (validations, close connections, try/catch, etc
(...)
}
void command_StatementCompleted(object sender, StatementCompletedEventArgs e)
{
// This is the method that closes my Waiting Dialog
myCustomWaitDialog.CloseDialog();
myCustomWaitDialog.Dispose();
}
It's not quite what I want yet, but is the best solution that I found so far. For now it will do :)
Anyway, thanks for the replies and I hope this helps someone else.

How to use a thread in a playback function

I want to playback a sound file in two or three external sound cards at the same time and I think that using threads is the solution but I really didn't know how to use it in the playback code.
This is the event makes on button play:
public partial class PlaybackForm : Form
{
IWavePlayer waveOut;
string fileName = null;
WaveStream mainOutputStream;
WaveChannel32 volumeStream;
int _deviceNum;
int _deviceNum1;
Thread t1;
Thread t2;
public PlaybackForm(int deviceNum,int deviceNum1)
{
InitializeComponent();
_deviceNum = deviceNum;
_deviceNum1 = deviceNum1;
}
private void buttonPlay_Click(object sender, EventArgs e)
{
if (waveOut != null)
{
if (waveOut.PlaybackState == PlaybackState.Playing)
{
return;
}
else if (waveOut.PlaybackState == PlaybackState.Paused)
{
waveOut.Play();
return;
}
}
// we are in a stopped state
// TODO: only re-initialise if necessary
if (String.IsNullOrEmpty(fileName))
{
toolStripButtonOpenFile_Click(sender, e);
}
if (String.IsNullOrEmpty(fileName))
{
return;
}
try
{
CreateWaveOut();
}
catch (Exception driverCreateException)
{
MessageBox.Show(String.Format("{0}", driverCreateException.Message));
return;
}
mainOutputStream = CreateInputStream(fileName);
trackBarPosition.Maximum = (int)mainOutputStream.TotalTime.TotalSeconds;
labelTotalTime.Text = String.Format("{0:00}:{1:00}", (int)mainOutputStream.TotalTime.TotalMinutes,
mainOutputStream.TotalTime.Seconds);
trackBarPosition.TickFrequency = trackBarPosition.Maximum / 30;
try
{
waveOut.Init(mainOutputStream);
}
catch (Exception initException)
{
MessageBox.Show(String.Format("{0}", initException.Message), "Error Initializing Output");
return;
}
// not doing Volume on IWavePlayer any more
volumeStream.Volume = volumeSlider1.Volume;
waveOut.Play();
}
And this is how to create the waveout:
private void CreateWaveOut()
{
CloseWaveOut();
int latency = (int)comboBoxLatency.SelectedItem;
//if (radioButtonWaveOut.Checked)
{
//WaveCallbackInfo callbackInfo = checkBoxWaveOutWindow.Checked ?
WaveCallbackInfo callbackInfo = WaveCallbackInfo.FunctionCallback();
// WaveCallbackInfo callbackInfo = WaveCallbackInfo.FunctionCallback();
// WaveCallbackInfo.NewWindow(): WaveCallbackInfo.FunctionCallback();
WaveOut outputDevice = new WaveOut(callbackInfo);
outputDevice.DesiredLatency = latency;
outputDevice.DeviceNumber = _deviceNum;
waveOut = outputDevice;
}
}
I declared two deviceNum but until now I can playsound only in one device,that's why I want to use thread.
Can you help me please
Thank you in advance
Do something like that:
using System.Threading;
...
private void buttonPlay_Click(object sender, EventArgs e)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(this.PlaySound), 1);
ThreadPool.QueueUserWorkItem(new WaitCallback(this.PlaySound), 2);
}
private void PlaySound(object obj)
{
int deviceNumber = (int)obj;
// Do the stuff you used to do in buttonPlay_Click
WaveOut myWaveOut = CreateWaveOut(deviceNumber);
...
}
private WaveOut CreateWaveOut(int deviceNumber)
{
...
WaveOut outputDevice = new WaveOut(callbackInfo);
outputDevice.DesiredLatency = latency;
outputDevice.DeviceNumber = _deviceNum;
return outputDevice;
}

Categories