BackgroundTransferRequest connect external power error - c#

I use BackgroundTransferRequest class to download mp3 files in my wp8 app. Some of my files are over 100mb, so because of that I set transferRequest.TransferPreferences = TransferPreferences.None;. However, transferstatus method still returns me external power message.
If you look at line 12 in code you can see that i set TransferPreferences as None
Here is my code to download mp3 file:
private void download_Tap_1(object sender, System.Windows.Input.GestureEventArgs e)
{
if (transferFileName != null)
{
Uri transferUri = new Uri(Uri.EscapeUriString(transferFileName), UriKind.RelativeOrAbsolute);
BackgroundTransferRequest transferRequest = new BackgroundTransferRequest(transferUri);
transferRequest.Method = "GET";
string downloadFile = transferFileName.Substring(transferFileName.LastIndexOf("/") + 1);
Uri downloadUri = new Uri("shared/transfers/" + downloadFile, UriKind.RelativeOrAbsolute);
transferRequest.DownloadLocation = downloadUri;
transferRequest.Tag = downloadFile;
transferRequest.TransferPreferences = TransferPreferences.None;
try
{
BackgroundTransferService.Add(transferRequest);
}
catch (InvalidOperationException ex)
{
// TBD - update when exceptions are finalized
MessageBox.Show("Unable to add background transfer request. " + ex.Message);
}
catch (Exception e2)
{
MessageBox.Show("Unable to add background transfer request."+e2.ToString());
}
transferRequest.TransferStatusChanged += new EventHandler<BackgroundTransferEventArgs>(transfer_TransferStatusChanged);
transferRequest.TransferProgressChanged += new EventHandler<BackgroundTransferEventArgs>(transfer_TransferProgressChanged);
}
else
MessageBox.Show("select an mp3 file to download");
}
private void ProcessTransfer(BackgroundTransferRequest transfer)
{
switch (transfer.TransferStatus)
{
case TransferStatus.Completed:
if (transfer.StatusCode == 200 || transfer.StatusCode == 206)
{
RemoveTransferRequest(transfer.RequestId);
processresult.Text = "";
download.Visibility = Visibility.Visible;
lnk = new linkname();
URLListBox.ItemsSource = lnk.obj();
using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
{
string filename = transfer.Tag;
if (isoStore.FileExists(filename))
{
isoStore.DeleteFile(filename);
}
isoStore.MoveFile(transfer.DownloadLocation.OriginalString, filename);
}
}
else
{
RemoveTransferRequest(transfer.RequestId);
if (transfer.TransferError != null)
{
MessageBox.Show(transfer.TransferError.ToString());
}
}
break;
case TransferStatus.WaitingForExternalPower:
WaitingForExternalPower = true;
processresult.Text = "Waiting For External Power";
break;
case TransferStatus.WaitingForExternalPowerDueToBatterySaverMode:
WaitingForExternalPowerDueToBatterySaverMode = true;
processresult.Text = "Waiting For External Power Due To Battery Saver Mode";
break;
case TransferStatus.WaitingForNonVoiceBlockingNetwork:
WaitingForNonVoiceBlockingNetwork = true;
processresult.Text = "Waiting For Non Voice Blocking Network";
break;
case TransferStatus.WaitingForWiFi:
WaitingForWiFi = true;
processresult.Text = "Waiting For WiFi";
break;
}
}
private void transfer_TransferStatusChanged(object sender, BackgroundTransferEventArgs e)
{
ProcessTransfer(e.Request);
}

From the Documentation
If the file to be transferred is larger than 100 MB, set the TransferPreferences property of the transfer to None. If you do not, the system will automatically change the transfer settings to this value, meaning that the transfer will only proceed when the phone is connected to external power and has a Wi-Fi connection.

Related

Error HRESULT: 0x80070021 when connecting to scanner

I have the following code for scanning a document using WIA with a Kodak ScanMate i1120
public static Device InitScanner(string DeviceID)
{
var deviceManager = new DeviceManager();
// Create an empty variable to store the scanner instance
DeviceInfo firstScannerAvailable = null;
// Loop through the list of devices
for (int i = 1; i <= deviceManager.DeviceInfos.Count; i++)
{
if (deviceManager.DeviceInfos[i].DeviceID == DeviceID)
{
firstScannerAvailable = deviceManager.DeviceInfos[i];
var device = firstScannerAvailable.Connect();
return _ConnectedScanner;
}
}
return _ConnectedScanner;
}
public void ScanDocument()
{
string _DeviceID = GetDeviceID(Properties.Settings.Default.DefaultDevice);
InitScanner(_DeviceID);
if (_ConnectedScanner == null)
{
MessageBox.Show("Scanner is not turned on or connected");
Lcontinue = false;
return;
}
else
{
try
{
_item = _ConnectedScanner.Items[1] as Item;
SelectDeviceDocumentHandling(_ConnectedScanner, DeviceDocumentHandling.Feeder);
//MessageBox.Show(GetDeviceProperty(_ConnectedScanner, 3078).ToString());
_MyImage = (ImageFile)_ConnectedScanner.Items[1].Transfer();
DocCount++;
}
catch (Exception ex)
{
switch (ex.HResult)
{
case -2145320959:
Lcontinue = false;
MessageBox.Show(ex.Message + Environment.NewLine + "Unknown Error");
return;
case -2145320957:
if (DocCount == 0)
{
Lcontinue = false;
//_WaitForOperator = false;
MessageBox.Show(ex.Message + Environment.NewLine + "There is no paper in the ADF");
return;
}
else
{
Lcontinue = false;
//WaitForOperator = false;
//DocCount = 0;
}
break;
case -2145320954:
if (DocCount == 0)
{
Lcontinue = false;
//_WaitForOperator = false;
MessageBox.Show(ex.Message + Environment.NewLine + "The device is busy, Please retry");
return;
}
else
{
Lcontinue = false;
DocCount = 0;
}
break;
default:
Lcontinue = false;
MessageBox.Show("Error No : " + ex.HResult + Environment.NewLine + Environment.NewLine + ex.ToString());
return;
}
}
}
}
I have two scanners on the system, a Kyocera and the Kodak, but I only want to use the Kodak for this app.
When I try to scan with the Kodak I get error
HRESULT: 0x80070021
System.IO.FileLoadException: `The process cannot access the file because another process has locked a portion of the file.
the error happens on the following line
var device = firstScannerAvailable.Connect();
I have no other scanning applications open so I am unable to figure out what is locking the file.
Can someone see what would be causing the file lock?

How to do proper TCP client-side communication with server in xamarin forms?

I`m trying to see what is wrong with my code for a tcp connection to a server in xamarin forms using the mvvm architecture. The client is connecting but when using streamReader.readLine() i get the following error:
System.IO.IOException: Unable to read data from the transport connection: Operation on non-blocking socket would block.
I´m using xamarin forms and System.Net.Sockets for the TcpClient instance. I´m trying synchronous communication for testing with the server.
I Have a TcpServer program proven to work with other devices. Below is some code to do the communication
The ViewModel of the connection properties page has the following code:
public ICommand TestConnectionCommand { get { return new
RelayCommand(sendMsg); } }
public ICommand ConnectCommand { get; set; }
public void sendMsg()
{
this.Response = new Response();
this.EthernetConn.Port = 9091;
this.EthernetConn.Ip = SelectedDevice.Ip;
if (String.IsNullOrEmpty(EthernetConn.Ip))
{
Application.Current.MainPage.DisplayAlert(Languages.Error, Languages.IpValidation, Languages.Accept);
return;
}
if (String.IsNullOrEmpty(EthernetConn.Timeout))
{
Application.Current.MainPage.DisplayAlert(Languages.Error, Languages.TimeoutValidation, Languages.Accept);
return;
}
this.EthernetConn.Message = "TESTING\n";
tcpService.Initialize(this.ethernetConn);
this.Response.Message = tcpService.sendMessage(this.EthernetConn);
if (this.Response.Message.Contains("FormatException"))
{
this.Response.IsSuccess = false;
Application.Current.MainPage.DisplayAlert(Languages.Error, Languages.FormatValidation, Languages.Accept);
this.IsRunning = false;
this.IsEnabled = true;
return;
}
else if (this.Response.Message.Contains("ArgumentNullException"))
{
this.Response.IsSuccess = false;
Application.Current.MainPage.DisplayAlert(Languages.Error, this.Response.Message, Languages.Accept);
this.IsRunning = false;
this.IsEnabled = true;
return;
}
else if (this.Response.Message.Contains("SocketException"))
{
this.Response.IsSuccess = false;
Application.Current.MainPage.DisplayAlert(Languages.Error, this.Response.Message, Languages.Accept);
this.IsRunning = false;
this.IsEnabled = true;
return;
}
else if (this.Response.Message.Contains("OK"))
{
this.Response.IsSuccess = true;
}
if (this.Response.IsSuccess)
{
Application.Current.MainPage.DisplayAlert(Languages.Success, Languages.ConnEstablished, Languages.Accept);
this.IsRunning = false;
this.IsEnabled = true;
}
else
{
Application.Current.MainPage.DisplayAlert(Languages.Error, Languages.ConnFailed, Languages.Accept);
this.IsRunning = false;
this.IsEnabled = true;
}
}
tcpService is an instance of TCPService, which has the Initialize function to establish connection and the sendMessage function where the error appears to be:
public void Initialize(EthernetConnection eth)
{
client.SendTimeout = Convert.ToInt16(eth.Timeout);
client.ReceiveTimeout = Convert.ToInt16(eth.Timeout);
client.Connect(eth.Ip, eth.Port);
}
public string sendMessage(EthernetConnection eth)
{
string response = String.Empty;
try
{
if (!client.Connected)
{
return null;
}
var writer = new StreamWriter(client.GetStream());
writer.WriteLine(eth.Message);
//Here is where the problem seems to be:
var reader = new StreamReader(client.GetStream());
response = reader.ReadLine();
return response;
}
catch (ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException: {0}", e);
return "ArgumentNullException: " + e;
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
return "SocketException:: " + e;
}
catch (FormatException e)
{
Console.WriteLine("SocketException: {0}", e);
return "FormatException: " + e;
}
}
I would be expecting to read the data in the ReadLine function. Also, I had some printing on the console on the server side if it recieves data and i'm seeing it is not.
Could somebody help me on where could I be wrong? A proven solution is also fine!
Thank you so much!
Whenever you use StreamWriter you need to Flush() the contents of the stream. I'll quote MSDN as the reason becomes quite clear:
Clears all buffers for the current writer and causes any buffered data
to be written to the underlying stream.
You can use it like this:
var writer = new StreamWriter(client.GetStream());
writer.AutoFlush = true;
writer.WriteLine(eth.Message);
writer.Flush();
And there is a simple demo you can check:
https://thuru.net/2012/01/07/simple-clientserver-in-c/

Websphere MQ - Keeping message context and identity when moving from one queue to another in .NET

I have been tasked with writing a custom application in C#.NET to move messages from one queue to another, while keeping all of the context and identity information the same as the original message.
I have tried to decipher the online docs, and have tried every combination of MQC.MQOO_PASS_ALL_CONTEXT and MQOO_SAVE_ALL_CONTEXT in opening queues, and MQC.MQPMO_PASS_ALL_CONTEXT in put calls, to no avail. I have tried setting the MQPutMessageOptions.ContextReference to both the source and the
destination queues, but I continue to get exceptions, either MQRC_CONTEXT_HANDLE_ERROR or MQRC_OPTIONS_ERROR, and I cannot find enough information in the online docs to determine the problem.
I am using runtime version v2.0.50727, Version 7.5.0.1 of the amqmdnet.dll. If anyone knows the correct open and/or put message option settings I need to use, I would appreciate the leg up. Thanks.
***** SECOND UPDATE *****
Here is a very simple gui program to test the classes, and I get the same results:
public partial class frmMain : Form
{
// Simple test - all data hard-coded
string sourceQStr = "PETE.TQ1";
string targetQStr = "PETE.TQ2";
string targetMsgIdStr = "414D5120514D4942584330352020202028ED0155202EB302";
string connName = "localhost";
string connPort = "1414";
MQQueueManager sourceManager;
MQQueueManager targetManager;
MQQueue sourceQueue;
MQQueue targetQueue;
MQMessage msg = new MQMessage();
MQGetMessageOptions gmo = new MQGetMessageOptions();
MQPutMessageOptions pmo = new MQPutMessageOptions();
public frmMain()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void txtPassword_Validating(object sender, CancelEventArgs e)
{
if (txtPassword.Text.Trim() != string.Empty)
{
if (LoginUser())
btnTest.Focus();
else
txtUserId.Focus();
}
}
public void LogoutUser()
{
txtUserId.Text = "";
txtPassword.Text = "";
btnTest.Enabled = false;
}
public bool LoginUser()
{
bool OK = ValidateUserAndPassword();
if (OK)
{
btnTest.Enabled = true;
}
else LogoutUser();
return OK;
}
private bool ValidateUserAndPassword()
{
if ((txtUserId.Text.Trim() == string.Empty) || (txtPassword.Text.Trim() == string.Empty))
return false;
try
{
bool _passwordValid = false;
ContextOptions options = ContextOptions.SimpleBind | ContextOptions.SecureSocketLayer;
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "UP"))
{
_passwordValid = pc.ValidateCredentials
(txtUserId.Text.Trim(), txtPassword.Text.Trim(), options);
}
if (!_passwordValid)
MessageBox.Show("Invalid username / password", "Invalid",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return _passwordValid;
}
catch (PrincipalServerDownException pex)
{
string msg = pex.Message.Insert(pex.Message.IndexOf("server"), "Authentication ");
MessageBox.Show(msg, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
private void btnTest_Click(object sender, EventArgs e)
{
try
{
SetupObjects();
sourceQueue.Get(msg, gmo);
targetQueue.Put(msg, pmo);
sourceManager.Commit();
targetManager.Commit();
MessageBox.Show("Test appears successful - verify with MQ Explorer","OK",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
catch (Exception ex) // MQRC_CONTEXT_HANDLE_ERROR is always thrown
{
MessageBox.Show("Error: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
sourceManager.Backout();
targetManager.Backout();
}
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
/************************************** Utiility methods *****************************************/
private void SetupObjects()
{
// set up objects
string connectName = connName + "(" + connPort + ")";
int ConnOptions = MQC.MQCNO_HANDLE_SHARE_BLOCK;
sourceManager = new MQQueueManager("", ConnOptions, "CHANNEL1", connectName);
targetManager = new MQQueueManager("", ConnOptions, "CHANNEL1", connectName);
MQEnvironment.UserId = txtUserId.Text.Trim();
MQEnvironment.Password = txtPassword.Text.Trim();
int options =
MQC.MQOO_INPUT_SHARED + MQC.MQOO_FAIL_IF_QUIESCING +
MQC.MQOO_SAVE_ALL_CONTEXT + MQC.MQOO_INQUIRE;
sourceQueue = sourceManager.AccessQueue
(sourceQStr, options, sourceManager.Name, null, txtUserId.Text.Trim());
options =
MQC.MQOO_OUTPUT + MQC.MQOO_FAIL_IF_QUIESCING +
MQC.MQOO_PASS_ALL_CONTEXT + MQC.MQOO_INQUIRE;
targetQueue = targetManager.AccessQueue
(targetQStr, options, targetManager.Name, null, txtUserId.Text.Trim());
int i = 0;
try
{
i = sourceQueue.CurrentDepth;
}
catch (Exception ex)
{
MessageBox.Show("Exception: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
gmo.Options = MQC.MQGMO_COMPLETE_MSG + MQC.MQGMO_FAIL_IF_QUIESCING +
MQC.MQGMO_NO_WAIT + MQC.MQGMO_SYNCPOINT;
pmo.Options = MQC.MQPMO_PASS_ALL_CONTEXT +
MQC.MQPMO_SYNCPOINT + MQC.MQPMO_SYNC_RESPONSE;
pmo.ContextReference = sourceQueue;
msg.MessageId = StringToByteArray(targetMsgIdStr);
}
public byte[] StringToByteArray(String hex)
{
hex = hex.Trim();
int NumberChars = hex.Length;
if ((NumberChars % 2) != 0)
{
hex = "0" + hex;
NumberChars++;
}
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
bytes[i / 2] = StringToByte(hex.Substring(i, 2));
return bytes;
}
public byte StringToByte(string hexDigits)
{
if (hexDigits.Length != 2)
return 0;
int high = hexValue(hexDigits[0]);
int low = hexValue(hexDigits[1]);
return (byte)(((high << 4) & 240) | (low & 15));
}
public int hexValue(char c)
{
int retval = 0;
if (c > '9')
retval = ((int)c) - 55;
else
retval = ((int)c) - 48;
return retval;
}
}
The GUI simply prompts for a username and password (which are validated with an LDAP call) and then enables a "test" button which runs the btnTest_Click method. I still get the same exception (MQRC_CONTEXT_HANDLE_ERROR) even thought I have used all the open and get message options specified.
Adding to Morag's answer, here is snippet for moving messages with context. I am also using a SYNC_POINT to ensure the message is removed from source queue after the message is successfully put to the destination queue.
/// <summary>
/// Moves messages from one queue to another with context
/// </summary>
public void moveMessagesWithContext()
{
MQQueueManager qmSource = null;
MQQueueManager qmDestination = null;
MQQueue qSource = null;
MQQueue qDestination = null;
Hashtable htSource = null;
Hashtable htDestination = null;
try
{
htSource = new Hashtable();
htDestination = new Hashtable();
htSource.Add(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_MANAGED);
htSource.Add(MQC.HOST_NAME_PROPERTY, "localhost");
htSource.Add(MQC.PORT_PROPERTY, 2020);
htSource.Add(MQC.CHANNEL_PROPERTY, "A_QM_SVRCONN");
qmSource = new MQQueueManager("A_QM", htSource);
qSource = qmSource.AccessQueue("Q_SOURCE", MQC.MQOO_INPUT_AS_Q_DEF | MQC.MQOO_FAIL_IF_QUIESCING | MQC.MQOO_SAVE_ALL_CONTEXT);
htDestination.Add(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_MANAGED);
htDestination.Add(MQC.HOST_NAME_PROPERTY, "localhost");
htDestination.Add(MQC.PORT_PROPERTY, 3030);
htDestination.Add(MQC.CHANNEL_PROPERTY, "B_QM_SVRCONN");
qmDestination = new MQQueueManager("B_QM", htDestination);
qDestination = qmDestination.AccessQueue("Q_DESTINATION", MQC.MQOO_OUTPUT | MQC.MQOO_FAIL_IF_QUIESCING | MQC.MQOO_PASS_ALL_CONTEXT);
MQMessage msgSource = new MQMessage();
MQGetMessageOptions gmo = new MQGetMessageOptions();
gmo.Options |= MQC.MQGMO_SYNCPOINT;
qSource.Get(msgSource,gmo);
if (msgSource != null)
{
MQMessage msgDestination = new MQMessage();
MQPutMessageOptions pmo = new MQPutMessageOptions();
pmo.ContextReference = qSource;
qDestination.Put(msgSource, pmo);
qmSource.Commit();
}
}
catch (MQException mqEx)
{
qmSource.Backout();
Console.WriteLine(mqEx);
}
catch (Exception otherEx)
{
Console.WriteLine(otherEx);
}
}
The correct options to use to move messages whilst retaining all the context information within them are as follows.
When opening the queue to get messages from, use MQOO_SAVE_ALL_CONTEXT. The context will be saved at get time in the object handle that represents this opened queue.
When opening the queue to put messages to, use MQOO_PASS_ALL_CONTEXT. Then when putting the message, use MQPMO_PASS_ALL_CONTEXT and provide the object handle that contains the context.
Receiving return code MQRC_CONTEXT_HANDLE_ERROR means that you didn't use MQOO_SAVE_ALL_CONTEXT on the first open but then tried to use the object handle on the put. It could also mean that it's just not a correct reference to the first queue. In the MQ API it's an object handle (MQHOBJ) whereas in .Net it's the MQQueue (see MQPutMessageOptions .NET class).
Receiving return code MQRC_OPTIONS_ERROR means that you mixed and matched the options too much.

BackgroundTransfer cannot move files

I am having problem downloading files using Background transfer. After completion of download when moving file, it gives you an exception Operation not permitted
void addTransferRequest(string fileName)
{
if (string.IsNullOrEmpty(fileName))
return;
string filePathToDownload = string.Empty;
filePathToDownload = activeReciter.DownloadURL;
filePathToDownload += fileName;
Uri transferUri = new Uri(Uri.EscapeUriString(filePathToDownload),
UriKind.RelativeOrAbsolute);
BackgroundTransferRequest transferRequest = new
BackgroundTransferRequest(transferUri);
transferRequest.Method = "GET";
transferRequest.TransferPreferences = TransferPreferences.AllowBattery;
Uri downloadUri = new Uri(DataSource.TEMPDOWNLOADLOCATION + fileName,
UriKind.RelativeOrAbsolute);
transferRequest.DownloadLocation = downloadUri;
transferRequest.Tag = fileName;
transferRequest.TransferStatusChanged +=
new EventHandler<BackgroundTransferEventArgs>
(transfer_TransferStatusChanged);
transferRequest.TransferProgressChanged += new
EventHandler<BackgroundTransferEventArgs>(transfer_TransferProgressChanged);
try
{
BackgroundTransferService.Add(transferRequest);
chapterFileNames.Dequeue();
}
catch (InvalidOperationException)
{
}
catch (Exception)
{
}
}
void transfer_TransferStatusChanged(object sender, BackgroundTransferEventArgs e)
{
ProcessTransfer(e.Request);
}
void transfer_TransferProgressChanged(object sender, BackgroundTransferEventArgs e)
{
}
private void ProcessTransfer(BackgroundTransferRequest transfer)
{
switch (transfer.TransferStatus)
{
case TransferStatus.Completed:
if (transfer.StatusCode == 200 || transfer.StatusCode == 206)
{
using (IsolatedStorageFile isoStore =
IsolatedStorageFile.GetUserStoreForApplication())
{
try
{
string filename = transfer.Tag;
string folderPath = string.Format(#"{0}{1}\{2}\",
DataSource.DOWNLOADLOCATION, activeReciter.ReciterID, chapter.ChapterID);
string fileFullPath = folderPath + filename;
if (!isoStore.DirectoryExists(Path.GetDirectoryName(folderPath)))
isoStore.CreateDirectory(Path.GetDirectoryName(folderPath));
if (isoStore.FileExists(fileFullPath))
isoStore.DeleteFile(fileFullPath);
isoStore.MoveFile(transfer.DownloadLocation.OriginalString, fileFullPath);
//Excpetion is thrown here
RemoveTransferRequest(transfer.RequestId);
}
catch (Exception ex)
{
MessageBox.Show("Error Occured: " + ex.Message + transfer.Tag, "Error",
MessageBoxButton.OK);
return;
}
}
}
break;
}
}
When moving file, it throws exception, I don't know what is wrong with moving (this happens on some of the files not all files).
From the MSDN Page, under File System Restrictions section:
You can create any additional directory structure you choose
underneath the root “/shared/transfers” directory, and you can copy or
move files after the transfer is complete to ensure that the
background transfer service does not modify the files, but attempting
to initiate a transfer using a path outside of the “/shared/transfers”
directory will throw an exception.
Make sure you are not trying to move your file outside from the /Shared/Transfers folder.

Exception while tracking location in Windows Phone 8

When I try to track location it works perfectly but when i add service reference to it it throws an exception
when I try the same program without adding location only add service reference it works perfectly
My code is here below while copy from How to continuously track the phone's location for Windows Phone 8
public partial class MainPage : PhoneApplicationPage
{
Geolocator geolocator = null;
bool tracking = false;
ServiceReference2.GetPositionClient client = new ServiceReference2.GetPositionClient();
// Constructor
public MainPage()
{
InitializeComponent();
// Sample code to localize the ApplicationBar
//BuildLocalizedApplicationBar();
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
if (IsolatedStorageSettings.ApplicationSettings.Contains("LocationConsent"))
{
// User has opted in or out of Location
return;
}
else
{
MessageBoxResult result =
MessageBox.Show("This app accesses your phone's location. Is that ok?",
"Location",
MessageBoxButton.OKCancel);
if (result == MessageBoxResult.OK)
{
IsolatedStorageSettings.ApplicationSettings["LocationConsent"] = true;
}
else
{
IsolatedStorageSettings.ApplicationSettings["LocationConsent"] = false;
}
IsolatedStorageSettings.ApplicationSettings.Save();
}
}
private void TrackLocation_Click(object sender, RoutedEventArgs e)
{
if ((bool)IsolatedStorageSettings.ApplicationSettings["LocationConsent"] != true)
{
// The user has opted out of Location.
return;
}
if (!tracking)
{
geolocator = new Geolocator();
geolocator.DesiredAccuracy = PositionAccuracy.High;
geolocator.MovementThreshold = 100; // The units are meters.
geolocator.StatusChanged += geolocator_StatusChanged;
geolocator.PositionChanged += geolocator_PositionChanged;
tracking = true;
TrackLocationButton.Content = "stop tracking";
}
else
{
geolocator.PositionChanged -= geolocator_PositionChanged;
geolocator.StatusChanged -= geolocator_StatusChanged;
geolocator = null;
tracking = false;
TrackLocationButton.Content = "track location";
StatusTextBlock.Text = "stopped";
}
}
void geolocator_StatusChanged(Geolocator sender, StatusChangedEventArgs args)
{
string status = "";
switch (args.Status)
{
case PositionStatus.Disabled:
// the application does not have the right capability or the location master switch is off
status = "location is disabled in phone settings";
break;
case PositionStatus.Initializing:
// the geolocator started the tracking operation
status = "initializing";
break;
case PositionStatus.NoData:
// the location service was not able to acquire the location
status = "no data";
break;
case PositionStatus.Ready:
// the location service is generating geopositions as specified by the tracking parameters
status = "ready";
break;
case PositionStatus.NotAvailable:
status = "not available";
// not used in WindowsPhone, Windows desktop uses this value to signal that there is no hardware capable to acquire location information
break;
case PositionStatus.NotInitialized:
// the initial state of the geolocator, once the tracking operation is stopped by the user the geolocator moves back to this state
break;
}
Dispatcher.BeginInvoke(() =>
{
StatusTextBlock.Text = status;
});
}
void geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
{
client.getPosCompleted += new EventHandler<ServiceReference2.getPosCompletedEventArgs>(sendData);
client.getPosAsync(11,11);
Dispatcher.BeginInvoke(() =>
{
LatitudeTextBlock.Text = args.Position.Coordinate.Latitude.ToString("0.00");
LongitudeTextBlock.Text = args.Position.Coordinate.Longitude.ToString("0.00");
});
}
public void sendData(object sender, ServiceReference2.getPosCompletedEventArgs e)
{
dd.Text = e.Result;
}
}
you have
client.getPosCompleted += new EventHandler<ServiceReference2.getPosCompletedEventArgs>(sendData);
but you haven't given Client any values anywhere else, I assume that you are getting a null Reference exception, and that this is why.
It just resolved it , just the fault of setting of IIS because mobile and pc are on different network so the communication is not possible .i just the forward the port in router setting –

Categories