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 –
Related
I launch a program located on one of my file servers. After launching the program it shows as an Open file in Computer Management.
Is there a way I can close this open file while my program runs so it doesn't show up in Computer Management?
My code is below. I'd be happy to take suggestions on improving my program, but I'm really just looking for a solution to stop all these Open Files from appearing.
Program.cs -- starts the program, handles logic to launch my application
using System;
using System.Windows.Forms;
using System.Diagnostics;
namespace IT_TaskbarApp
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
string programName = "TEG System Helper";
//Process[] proc = Process.GetProcessesByName(programName);
if (Process.GetProcessesByName(programName).Length == 1)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Primary());
}
else
{
foreach (Process p in Process.GetProcessesByName(programName))
{
if (Process.GetCurrentProcess().Id != p.Id)
{
p.CloseMainWindow();
p.Close();
p.Kill();
p.Dispose();
}
}
Main();
}
}
}
}
Primary.cs -- creates an icon in the system icons which I can use to send notifications and easily access utilities within our organization
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Windows.Forms;
namespace IT_TaskbarApp
{
public partial class Primary : Form
{
private NotifyIcon notifyIcon;
private ContextMenu contextMenu;
private MenuItem[] menuItem = new MenuItem[8];
private IContainer components;
//private Boolean SendNotices = true;
private DateTime startTime = DateTime.Now;
private DateTime currentTime;
private Icon tegroupIcon = new Icon(Assembly.GetExecutingAssembly().GetManifestResourceStream("IT_TaskbarApp.Src.tegroup.ico"));
private string prevNotification = "";
private bool isRunning = true;
private BackgroundWorker bgNotify = new BackgroundWorker();
private const string programName = "TEG System Helper";
public Primary()
{
this.FormClosing += Primary_FormClosing; //remove ghost icon in taskbar
ForeColor = Color.Blue;
BackColor = Color.Green;
components = new Container();
contextMenu = new ContextMenu();
for (int i = 0; i < menuItem.Length; i++)
{
menuItem[i] = new MenuItem();
menuItem[i].Index = i;
menuItem[i].Click += new EventHandler(LoadProcess);
}
menuItem[0].Text = programName;
menuItem[1].Text = "Knowledge Base";
menuItem[2].Text = "Policies";
menuItem[3].Text = "Feedback";
menuItem[4].Text = "Global Shop Search";
menuItem[5].Text = "-";
menuItem[6].Text = "Submit Ticket";
menuItem[7].Text = "Send Email";
//initialize contextMenu
contextMenu.MenuItems.AddRange(menuItem);
// Create the NotifyIcon.
notifyIcon = new NotifyIcon(components)
{
Icon = tegroupIcon,
BalloonTipIcon = new ToolTipIcon(),
ContextMenu = contextMenu, //the menu when right clicked
Text = programName,
Visible = true,
BalloonTipTitle = programName,
};
notifyIcon.DoubleClick += new EventHandler(Icon_DoubleClick);
InitializeComponent();
bgNotify.WorkerSupportsCancellation = true;
bgNotify.WorkerReportsProgress = true;
bgNotify.DoWork += NotifyUser;
bgNotify.ProgressChanged += SendNotice;
//bgNotify.RunWorkerCompleted += BgNotify_RunWorkerCompleted; //enable this to perform an action when the thread dies
bgNotify.RunWorkerAsync();
//Thread tNotify = new Thread();
}
#region SupportedFunctions
private void NotifyUser(object Sender, EventArgs e)
{
Console.WriteLine("enter");
while (isRunning)
{
currentTime = DateTime.Now;
#region DisplayCurrentTime
if (currentTime.Hour < 10 || currentTime.Minute < 10)
{
if (currentTime.Hour < 10)
{
if (currentTime.Minute < 10)
{
Console.WriteLine("0{0}:0{1}", currentTime.Hour, currentTime.Minute);
}
else
{
Console.WriteLine("0{0}:{1}", currentTime.Hour, currentTime.Minute);
}
}
else
{
if (currentTime.Minute < 10)
{
Console.WriteLine("{0}:0{1}", currentTime.Hour, currentTime.Minute);
}
}
}
else
{
Console.WriteLine("{0}:{1}", currentTime.Hour, currentTime.Minute);
}
#endregion
FileStream fs = new FileStream("\\\\te-admin\\public\\TaskbarNotices.txt", FileMode.Open);
StreamReader sr = new StreamReader(fs);
string noticeText = sr.ReadToEnd();
sr.Close();
fs.Close();
if (noticeText != "" && noticeText != prevNotification)
{
prevNotification = noticeText;
bgNotify.ReportProgress(1);
}
else
{
bgNotify.ReportProgress(2);
}
Console.WriteLine("Inner Text: {0} TOF: {1}", noticeText, noticeText != "");
Thread.Sleep(10000);
}
}
private void SendNotice(object Sender, ProgressChangedEventArgs e)
{
if (e.ProgressPercentage == 1)
{
Console.WriteLine("notification sent");
this.notifyIcon.BalloonTipText = prevNotification;
this.notifyIcon.ShowBalloonTip(1500);
}
}
private void LoadProcess(object Sender, EventArgs e)
{
if (Sender is MenuItem)
{
MenuItem tempMenu = Sender as MenuItem;
string ProgramTag = "http://";
switch (tempMenu.Index)
{
case 0: //home page
ProgramTag += "teg";
break;
case 1: //docviewer
ProgramTag += "teg/docViewer";
break;
case 2: //policies
ProgramTag += "teg/Policies";
break;
case 3: //feedback
ProgramTag += "teg/Feedback";
break;
case 4: //inventory search
ProgramTag = "http://searchglobalshop/inventory/index.aspx";
break;
case 6: //submit ticket
ProgramTag = "https://timberlandgroup.on.spiceworks.com/portal/tickets";
break;
case 7: //send email
string sendto = "admin#tewinch.com";
string emailSubject = "Assistance Request";
string emailBody = "";
string mailto = string.Format("mailto:{0}?Subject={1}&Body={2}", sendto, emailSubject, emailBody);
ProgramTag = Uri.EscapeUriString(mailto);
break;
}
/*
Try to launch the choice the user made with the default processing method.
Should the default method fail we try to control how the process is run.
We open internet explorer and then we show them what to do otherwise.
*/
#region LaunchSelectedProcess
try
{
if (ProgramTag != "" && ProgramTag != "http://")
Process.Start(ProgramTag);
}
catch (System.ComponentModel.Win32Exception)
{
try
{
if (ProgramTag.StartsWith("http://") || ProgramTag.StartsWith("https://"))
Process.Start("iexplore.exe", ProgramTag);
}
catch (System.ComponentModel.Win32Exception)
{
Process.Start("control.exe", "/name Microsoft.DefaultPrograms");
string message = "";
if (tempMenu.Index <= 6)
{
message = "You must have a default browser set\n\tClick [Set Default Program]\n";
if (Environment.OSVersion.ToString().Contains("NT 10.")) //windows 10
{
message += "\tUnder [Web Browser] Edge is currently set as default\n\tClick on Microsoft Edge\n\tSelect the browser you use";
}
else //windows 7 -- "NT 6.1")
{
message += "Select the browser you use\n\tClick [Set this program as default]";
}
}
else
{
if (Environment.OSVersion.ToString().Contains("NT 10.")) //windows 10
{
message += "Please setup a default email application";
}
}
message += "\n\nIf this issue persists please contact your Administrator.\nPhone: 519-537-6262\nEmail: admin#tewinch.com";
MessageBox.Show(message, "Application Warning", MessageBoxButtons.OK, MessageBoxIcon.Information);
//if ( == DialogResult.OK)
}
}
#endregion
}
}
private void Icon_DoubleClick(object Sender, EventArgs e)
{
Process.Start("http://teg");
}
#endregion
#region BuiltFunctions
private void Primary_FormClosing(object sender, FormClosingEventArgs e)
{
notifyIcon.Icon = null;
notifyIcon.Dispose();
isRunning = false;
Dispose(true);
}
private void InitializeComponent()
{
this.SuspendLayout();
//
// Primary
//
this.Icon = tegroupIcon;
this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None;
this.CausesValidation = false;
this.ClientSize = new System.Drawing.Size(120, 23);
this.ControlBox = false;
this.Enabled = false;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "Primary";
this.Opacity = 0D;
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.WindowState = System.Windows.Forms.FormWindowState.Minimized;
this.ResumeLayout(false);
}
protected override void Dispose(bool disposing)
{
// Clean up any components being used.
if (disposing)
if (components != null)
components.Dispose();
base.Dispose(disposing);
}
#endregion
}
}
Instead of cancelling the program on start up, I kill the other running instances of the program. The idea is that if any issues arise with the program I just launch another instance and resolve the issues. Right now not much can go wrong but we will be developing this program to complete many more tasks in the future.
The only area I can see which would keep a file open is when I pull an Embedded Resource tegroup.ico I was looking to see if I missed something while opening this, but I couldn't see a way to close the ManifestResourceStream after reading it in.
Any tips/suggestions would be wonderful but again, I really just want to know if there's a way I can close these Open Files
Example below
Open File after app launch
I might be trying to solve something which is a known result of using Application.Run() if this is the case then please suggest alternatives I can use. My other ideas would be loading the program into memory and launching it locally, using the .exe on the server as a starting point for this method though.
I believe that Windows doesn't load an entire executable into ram. It isn't just about files from the resource section of a PE file. Portions of the exe are only loaded when referenced and even after loading everything there is to load, Windows will maintain an open file handle until the process closes. Trying to close that handle yourself is a bad idea.
c/c++ allow a "SWAPFILE" flag to be specified that tells windows to put the whole thing into the page file but I don't know how you would do that with c# and I don't know if that would even stop windows from keeping the handle open anyways (I doubt it).
If this is truly important, iffin' I were your exe... I would:
Check a mutex for an existing running instance, exit if exist
Check where I was running from.
If running from temp, set a mutex that I am running and just run.
If not running from temp, copy myself to %temp%, start that copy, and exit.
Good luck.
Good Evening,
I’m doing some troubleshooting on the beginning of my home automation system. I am trying to toggle a relay using a Raspberry PI 3 and Windows IOT in C#. I’ve been playing with the code and I can see the relay toggle once or twice, but then the app crashes. I’m an IOT Noob, so is there something wrong with this code? (Variable names are defined elsewhere and the weird variable names I have below are for my WIP project... I prefer troubleshooting in English)....
private void BtnTempFan_Click(object sender, RoutedEventArgs e)
{
if (BtnTempFan.IsChecked == true)
{
TogglePin(TempFan, TempFan_PIN, BtnTempFan, GpioPinValue.High);
}
else
{
TempFan.Dispose();
}
}
private void TogglePin(GpioPin PinName, int PinNumber, ToggleButton Name, GpioPinValue value)
{
int pinnumber = PinNumber;
GpioPinValue pinvalue;
var gpio = GpioController.GetDefault();
PinName = gpio.OpenPin(pinnumber);
if (gpio == null)
{
PinName = null;
LblError.Text = "We can't find the controller on the device" + PinName;
LblError.Visibility = Visibility.Visible;
return;
}
if (PinName == null)
{
LblError.Text = "We can't find the pin on the device. Pin number " + PinNumber + "does not exist";
LblError.Visibility = Visibility.Visible;
return;
}
if (Name.IsChecked == true)
{
pinvalue = value;
PinName.Write(pinvalue);
PinName.SetDriveMode(GpioPinDriveMode.Output);
}
You don't say what the exception is. However, I believe you are supposed open a GPIO pin only once per app:
var gpio = GpioController.GetDefault();
PinName = gpio.OpenPin(pinnumber);
You have it in a method which is called once per button click. By opening the pin more than once, you are encountering that the pin is already open, and I believe this is what throws an exception and crashes the app.
In my code, I handle pin states in a "driver" class, and have a method called Connect which I call once when starting the application. For example:
public async Task Connect()
{
var gpioController = await GpioController.GetDefaultAsync();
try
{
_openPin = gpioController.OpenPin(_doorMotorOpenPin);
_closePin = gpioController.OpenPin(_doorMotorClosePin);
}
}
This encapsulates the 2 pins: _openPin and _closePin into a class that I can manage the lifecycle of.
Codekaizen is correct. I separated out opening the pin into a method that only gets called once and problem solved.
private void BtnTempFan_Click(object sender, RoutedEventArgs e)
{
if (BtnTempFan.IsChecked == false)
{
TogglePin(TempFan, TempFan_PIN, BtnTempFan, GpioPinValue.High);
}
if (BtnTempFan.IsChecked == true)
{
TogglePin(TempFan, TempFan_PIN, BtnTempFan, GpioPinValue.Low);
}
}
private void InitializePins()
{
var gpio = GpioController.GetDefault();
// Show an error if there is no GPIO controller
if (gpio == null)
{
TempFan = null;
LblError.Text = "We can't find the controller on the device";
LblError.Visibility = Visibility.Visible;
return;
}
TempFan = gpio.OpenPin(TempFan_PIN);
TempFan.SetDriveMode(GpioPinDriveMode.Output);
}
private void TogglePin(GpioPin PinName, int PinNumber, ToggleButton Name, GpioPinValue value)
{
int pinnumber = PinNumber;
GpioPinValue pinvalue;
pinvalue = value;
PinName.Write(pinvalue);
}
I try activate a progressbar, while the app is searching for the location (after pressing a button)
how can i solve it the best way?
the best would somehow to get an if else in there, wheater i got (the rigth) data from the geolocator and check that.
private async void Ellipse_Tap (object sender, System.Windows.Input.GestureEventArgs e)
{
Geolocator geolocator = new Geolocator();
//Set his accuracy in Meters
geolocator.DesiredAccuracyInMeters = 50;
try
{
//The await guarantee the calls to be returned on the thread from which they were called
//Since it is call directly from the UI thread, the code is able to access and modify the UI directly when the call returns.
Geoposition geoposition = await geolocator.GetGeopositionAsync(
maximumAge: TimeSpan.FromMinutes(5),
timeout: TimeSpan.FromSeconds(10)
);
//Relativer Nullpunkt
delta_y = geoposition.Coordinate.Latitude - y;
delta_x = geoposition.Coordinate.Longitude - x;
Path.Visibility = Visibility.Visible;
}
//If an error is catch 2 are the main causes: the first is that you forgot to includ ID_CAP_LOCATION in your app manifest.
//The second is that the user doesn't turned on the Location Services
catch (Exception ex)
{
if ((uint)ex.HResult == 0x80004004)
{
MessageBox.Show("Location is disabled in phone settings.");
return;
//Application.Current.Terminate();
}
//else
{
// something else happened during the acquisition of the location
}
}
}
Assuming you are using the ProgressIndicator in the SystemTry, Add the following to the OnNavigatedTo Method
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
SystemTray.ProgressIndicator = new ProgressIndicator();
}
Then create this method to set the ProgressIndicator.
private void DisplayProgressIndicator(bool isvisible, string message = "")
{
SystemTray.ProgressIndicator.Text = message;
SystemTray.ProgressIndicator.IsIndeterminate = isvisible;
SystemTray.ProgressIndicator.IsVisible = isvisible;
}
Then use the method created in the Eclips_Tap method.
private async void Ellipse_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
Geolocator geolocator = new Geolocator();
geolocator.DesiredAccuracyInMeters = 50;
try
{
DisplayProgressIndicator(true, "Finding current location..."); // < SET THE PROGRESS INDICATOR
Geoposition geoposition = await geolocator.GetGeopositionAsync(
maximumAge: TimeSpan.FromMinutes(5),
timeout: TimeSpan.FromSeconds(10)
);
delta_y = geoposition.Coordinate.Latitude - y;
delta_x = geoposition.Coordinate.Longitude - x;
Path.Visibility = Visibility.Visible;
DisplayProgressIndicator(false); // << UNSET PROGRESS INDICATOR
}
catch (Exception ex)
{
if ((uint)ex.HResult == 0x80004004)
{
MessageBox.Show("Location is disabled in phone settings.");
return;
}
}
}
Hope this helps..
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.
I started Windows Phone programming with this example from Microsoft:
http://code.msdn.microsoft.com/wpapps/Hybrid-Web-App-75b7ef74/view/SourceCode
The app only displays the browser and load a URL.
Now I want to load an other URL directly from a .txt file.
For example: http://www.test.de/appurl.txt and then I want to load the URL in the Windows Phone App.
--> For example: http://anotherserver.de/index.html?mobileApp
My problem is, that the URL have to load synchronous and not asynchronous. I implement a AutoResetEvent, but it don´t work...
Hope somebody can help me, thx!
Here is my Code:
public partial class MainPage : PhoneApplicationPage
{
// URL zur WebApp
// TODO: URL muss aus diesem TEXT-File ausgelesen werden!
private string _appURL = "http://www.test.de/appurl.txt";
public string _homeURL = "";
//private string _homeURL = "http://anotherserver.de/index.html?mobileApp";
// URL zur Registrierung von Angeboten
private string _registrationURL = "http://anotherserver.de/index.html?bereich=registrierung&mobileApp";
// Secondary tile data
//private Uri _currentURL;
//private Uri _tileImageURL;
//private string _pageTitle = "Shop ";
// Serialize URL into IsoStorage on deactivation for Fast App Resume
private Uri _deactivatedURL;
private IsolatedStorageSettings _userSettings = IsolatedStorageSettings.ApplicationSettings;
// To indicate when we're navigating to a new page.
private ProgressIndicator _progressIndicator;
// Constructor
public MainPage()
{
InitializeComponent();
//Read the URL from a txt file and set the _homeURL
ReadFile(_appURL);
// Setup the progress indicator
_progressIndicator = new ProgressIndicator();
_progressIndicator.IsIndeterminate = true;
_progressIndicator.IsVisible = false;
SystemTray.SetProgressIndicator(this, _progressIndicator);
// Event handler for the hardware back key
BackKeyPress += MainPage_BackKeyPress;
// Fast app resume events
PhoneApplicationService.Current.Deactivated += Current_Deactivated;
PhoneApplicationService.Current.Closing += Current_Closing;
}
//AutoResetEvent are = new AutoResetEvent(false);
public void ReadFile(string address)
{
var webClient = new WebClient();
webClient.OpenReadAsync(new Uri(address));
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
// lock the thread until web call is completed
//are.WaitOne();
//finally call the NotifyComplete method to end the background agent
//NotifyComplete();
}
void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
try
{
using (var reader = new StreamReader(e.Result))
{
string downloaded = reader.ReadToEnd();
Debug.WriteLine("downloaded= " + downloaded);
_homeURL = downloaded;
//work = false;
}
}
catch
{
Debug.WriteLine("Please check your data connection");
MessageBox.Show("Please check your data connection");
}
//signals locked thread that can now proceed
//are.Set();
}
#region App Navigation Events
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
// Browser event handlers
Browser.Navigating += Browser_Navigating;
Browser.Navigated += Browser_Navigated;
Browser.NavigationFailed += Browser_NavigationFailed;
Browser.IsScriptEnabled = true;
// Try to get the URL stored for fast app resume.
try
{
_deactivatedURL = (Uri)(_userSettings["deactivatedURL"]);
}
catch (System.Collections.Generic.KeyNotFoundException keyNotFound)
{
Debug.WriteLine(keyNotFound.Message);
}
// Were we started from a pinned tile?
if (NavigationContext.QueryString.ContainsKey("StartURL"))
{
// Navigate to the pinned page.
Browser.Navigate(new Uri(NavigationContext.QueryString["StartURL"], UriKind.RelativeOrAbsolute));
}
else if ((_deactivatedURL != null) && (e.NavigationMode != NavigationMode.Reset))
{
// If there is a stored URL from our last
// session being deactivated, navigate there
if (Browser.Source != _deactivatedURL)
{
Browser.Navigate(_deactivatedURL);
}
}
else
{
// Not launched from a pinned tile...
// No stored URL from the last time the app was deactivated...
// So, just navigate to the home page
Browser.Navigate(new Uri(_homeURL, UriKind.RelativeOrAbsolute));
}
}
....
My problem is, that the URL have to load synchronous and not asynchronous
No you can't do it synchronously, but using async/await you can pretend it.
For this, You can use a method something like this (you can even write it as an extension method)
await Navigate(webBrowser1, "http://stackoverflow.com");
DoSomethingAfterNavigationCompleted();
Task Navigate(WebBrowser wb,string url)
{
var tcs = new TaskCompletionSource<object>();
WebBrowserDocumentCompletedEventHandler documentCompleted = null;
documentCompleted = (o, s) =>
{
wb.DocumentCompleted -= documentCompleted;
tcs.TrySetResult(null);
};
wb.DocumentCompleted += documentCompleted;
wb.Navigate(url);
return tcs.Task;
}