ReverseGeocodeQuery giving error - windows-phone-8

ReverseGeocodeQuery is giving error
1.in "GeoCoordinate(47.60887, -122.34094); " method must have a return type
2.in "reverseGeocode.GeoCoordinate line " reverseGeocode is a field but its used like a type..
ReverseGeocodeQuery reverseGeocode = new ReverseGeocodeQuery();
reverseGeocode.GeoCoordinate = new GeoCoordinate(47.60887, -122.34094);
reverseGeocode.QueryCompleted += reverseGeocode_QueryCompleted;
reverseGeocode.QueryAsync();
void reverseGeocode_QueryCompleted(objectsender,QueryCompletedEventArgs<IList<MapLocation>> e)
{
MapAddress geoAddress = e.Result[0].Information.Address;
}
i used namespace-- using Microsoft.Phone.Maps.Services;
how to rectify this errors..

GOT THE ANSWER
GeoCoordinateWatcher myLocationWatcher;
private GeoCoordinate MyCoordinate = null;
private async void GetCurrentCoordinate()
{
Geolocator geolocator = new Geolocator();
geolocator.DesiredAccuracy = PositionAccuracy.High;
try
{
Geoposition currentPosition = await geolocator.GetGeopositionAsync(TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(10));
_accuracy = currentPosition.Coordinate.Accuracy;
MyCoordinate = new GeoCoordinate(currentPosition.Coordinate.Latitude, currentPosition.Coordinate.Longitude);
if (MyReverseGeocodeQuery == null || !MyReverseGeocodeQuery.IsBusy)
{
MyReverseGeocodeQuery = new ReverseGeocodeQuery();
MyReverseGeocodeQuery.GeoCoordinate = new GeoCoordinate(MyCoordinate.Latitude, MyCoordinate.Longitude);
LongitudeTextBlock.Text = MyCoordinate.Longitude.ToString();
LatitudeTextBlock.Text = MyCoordinate.Latitude.ToString();
MyReverseGeocodeQuery.QueryCompleted += ReverseGeocodeQuery_QueryCompleted;
MyReverseGeocodeQuery.QueryAsync();
}
}
catch (Exception ex)
{
// ...
}
}
public void ReverseGeocodeQuery_QueryCompleted(object sender, QueryCompletedEventArgs<IList<MapLocation>> e)
{
if (e.Error == null)
{
if (e.Result.Count > 0)
{
MapAddress address = e.Result[0].Information.Address;
labelResults.Text = "Current Location: " + address.City + ", " + address.State;
}
}
}
public void Button_Click(object sender, RoutedEventArgs e)
{
GetCurrentCoordinate();
}

Related

How to get Address from Lat Long

Hello i am creating App for iOS and Android. The issue i want to fix that on the load on page i want to display the map with the address. I can get Lat Long successfully but i cannot getting address that i want to display on a label. Below is my code that i am using.
using Plugin.Geolocator;
using Xamarin.Forms.Maps;
private Position _position;
// Map map;
double Lat, Long;
string address = "";
public TestPage()
{
NavigationPage.SetHasNavigationBar(this, false);
InitializeComponent();
GetPosition();
if (_position != null)
{
Lat = _position.Latitude;
Long = _position.Longitude;
}
//Task<String> str = GetAddress();
map.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(Lat, Long), Distance.FromMiles(1)));
var position = new Position(Lat, Long);
var pin = new Pin
{
Type = PinType.Place,
Position = position,
Label = ""
};
map.Pins.Add(pin);
var zoomLevel = 17.83;
var latlongdegrees = 360 / (Math.Pow(2, zoomLevel));
map.MoveToRegion(new MapSpan(position, latlongdegrees, latlongdegrees));
LabelTime.Text = DateTime.Now.ToString("hh:mm tt") + " " + DateTime.Now.ToString("MM/dd/yyyy");
string recentAddress = address; // trying to get adderss for location
}
GetPosition()
public async void GetPosition()
{
Plugin.Geolocator.Abstractions.Position position = null;
try
{
var locator = CrossGeolocator.Current;
locator.DesiredAccuracy = 100.0;
position = await locator.GetLastKnownLocationAsync();
if (position != null)
{
_position = new Position(position.Latitude, position.Longitude);
//got a cahched position, so let's use it.
return;
}
if (!locator.IsGeolocationAvailable || !locator.IsGeolocationEnabled)
{
//not available or enabled
return;
}
position = await locator.GetPositionAsync(TimeSpan.FromSeconds(10), null, true);
}
catch (Exception ex)
{
// error(ex.Message, Convert.ToString(ex.InnerException), ex.Source, ex.StackTrace);
}
_position = new Position(position.Latitude, position.Longitude);
if (position == null)
return;
}
GetAddress()
public async Task<String> GetAddress()
{
// string Addrsss = "";
try
{
Geocoder geoCoder = new Geocoder();
if (_position != null)
{
var possibleAddresses = await geoCoder.GetAddressesForPositionAsync(_position);
await Task.Delay(2000);
foreach (var a in possibleAddresses)
{
address += a + "\n";
}
}
return address;
}
catch (Exception ex)
{
throw;
}
}
I also try to get the current address on OnAppearing()
protected override void OnAppearing()
{
this.Appearing += TestPage_Appearing; //Subscribe to event
base.OnAppearing();
}
protected async void TestPage_Appearing(object sender, EventArgs args)
{
GetPosition();
address= await GetAddress();
string a = address;
this.Appearing -= TestPage_Appearing; //Unsubscribe
}
You can get placemark address using Xamarin.Essentials as below,
protected async override void OnAppearing()
{
await GetAddress();
}
private async Task GetAddress()
{
var lat = 47.673988;
var lon = -122.121513;
var placemarks = await Geocoding.GetPlacemarksAsync(lat, lon);
var placemark = placemarks?.FirstOrDefault();
if (placemark != null)
{
var geocodeAddress =
$"AdminArea: {placemark.AdminArea}\n" +
$"CountryCode: {placemark.CountryCode}\n" +
$"CountryName: {placemark.CountryName}\n" +
$"FeatureName: {placemark.FeatureName}\n" +
$"Locality: {placemark.Locality}\n" +
$"PostalCode: {placemark.PostalCode}\n" +
$"SubAdminArea: {placemark.SubAdminArea}\n" +
$"SubLocality: {placemark.SubLocality}\n" +
$"SubThoroughfare: {placemark.SubThoroughfare}\n" +
$"Thoroughfare: {placemark.Thoroughfare}\n";
Console.WriteLine(geocodeAddress);
}
}
refer this link for in depth details
Also this one for detailed implementation

How to get url of uploaded file to google drive in android using Drive API?

I need to get the link of the video that I upload it to google drive so that I can open the video in the web browser, I can upload a video file to google drive and can get also the file ID using the following code:
private void UploadFile(final DriveId driveId)
{
Drive.DriveApi.newDriveContents(mGoogleApiClient).setResultCallback(new ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(#NonNull DriveApi.DriveContentsResult driveContentsResult)
{
if (!driveContentsResult.getStatus().isSuccess())
{
Log.e(TAG, "Error while trying to create new file contents");
return;
}
OutputStream outputStream = driveContentsResult.getDriveContents().getOutputStream();
Toast.makeText(context, "Uploading to drive....", Toast.LENGTH_LONG).show();
final File theFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/VideoFiles/testVideo.mkv");
try
{
FileInputStream fileInputStream = new FileInputStream(theFile);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1)
{
outputStream.write(buffer, 0, bytesRead);
}
} catch (IOException e1)
{
Log.i(TAG, "Unable to write file contents.");
}
MetadataChangeSet changeSet = new MetadataChangeSet.Builder().setTitle(theFile.getName()).setMimeType("video/mkv").setStarred(false).build();
DriveFolder folder = driveId.asDriveFolder();
folder.createFile(mGoogleApiClient, changeSet, driveContentsResult.getDriveContents()).setResultCallback(new ResultCallback<DriveFolder.DriveFileResult>() {
#Override
public void onResult(#NonNull DriveFolder.DriveFileResult driveFileResult)
{
if (!driveFileResult.getStatus().isSuccess())
{
Log.e(TAG, "Error while trying to create the file");
return;
}
Log.v(TAG, "Created a file: " + driveFileResult.getDriveFile().getDriveId());
}
});
}
});
}
I tried to get the video url using the following code:
DriveFile file = Drive.DriveApi.getFile(googleApiClient,driveId);
DriveResource.MetadataResult mdRslt = file.getMetadata(googleApiClient).await();
if (mdRslt != null && mdRslt.getStatus().isSuccess()) {
String link = mdRslt.getMetadata().getWebContentLink();
Log.d("LINK", link);
}
But then I got "Cannot resolve symbol 'googleApiClient'
Any suggestion please?
Ok, I found the solution, first I have to get the completed file ID by using the change events listener, then we can add "drive.google.com/open?id=" to the file ID, so the complate url will be drive.google.com/open?id=FileID.
here is my answer:
public class Uploader extends Activity implements ConnectionCallbacks,OnConnectionFailedListener{
private static final String TAG = "Google Drive Activity";
private static final int REQUEST_CODE_RESOLUTION = 1;
private static final int REQUEST_CODE_OPENER = 2;
private GoogleApiClient mGoogleApiClient;
public DriveFile file;
private String FOLDER_NAME = "GD_VideoFile";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onResume()
{
super.onResume();
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
mGoogleApiClient.connect();
}
#Override
protected void onStop()
{
super.onStop();
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
super.onPause();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult result)
{
Log.i(TAG, "GoogleApiClient connection failed: " + result.toString());
if (!result.hasResolution()) {
GoogleApiAvailability.getInstance().getErrorDialog(this, result.getErrorCode(), 0).show();
return;
}
try {
result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
} catch (SendIntentException e) {
Log.e(TAG, "Exception while starting resolution activity", e);
}
}
#Override
public void onConnected(Bundle connectionHint)
{
Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_LONG).show();
if (mGoogleApiClient != null)
{
check_folder_exists();
} else
{
Log.e(TAG, "Could not connect to google drive manager");
}
}
#Override
public void onConnectionSuspended(int cause)
{
Log.i(TAG, "GoogleApiClient connection suspended");
}
#Override
protected void onActivityResult(final int requestCode,
final int resultCode, final Intent data)
{
switch (requestCode)
{
case REQUEST_CODE_OPENER:
if (resultCode == RESULT_OK)
{
DriveId mFileId = data.getParcelableExtra(
OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID);
Log.e("file id", mFileId.getResourceId() + "");
String url = "https://drive.google.com/open?id="+ mFileId.getResourceId();
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
break;
default:
super.onActivityResult(requestCode, resultCode, data);
break;
}
}
private void check_folder_exists()
{
Query query = new Query.Builder().addFilter(Filters.and(Filters.eq(SearchableField.TITLE, FOLDER_NAME), Filters.eq(SearchableField.TRASHED, false))).build();
Drive.DriveApi.query(mGoogleApiClient, query).setResultCallback(new ResultCallback<DriveApi.MetadataBufferResult>() {
#Override
public void onResult(#NonNull DriveApi.MetadataBufferResult result)
{
if (!result.getStatus().isSuccess())
{
Log.e(TAG, "Cannot create folder in the root.");
} else
{
boolean isFound = false;
for (Metadata m : result.getMetadataBuffer())
{
if (m.getTitle().equals(FOLDER_NAME)) {
Log.e(TAG, "Folder exists");
isFound = true;
DriveId driveId = m.getDriveId();
UploadFile(driveId);
break;
}
}
if (!isFound)
{
Log.i(TAG, "Folder not found; creating it.");
MetadataChangeSet changeSet = new MetadataChangeSet.Builder().setTitle(FOLDER_NAME).build();
Drive.DriveApi.getRootFolder(mGoogleApiClient)
.createFolder(mGoogleApiClient, changeSet)
.setResultCallback(new ResultCallback<DriveFolder.DriveFolderResult>() {
#Override
public void onResult(#NonNull DriveFolder.DriveFolderResult result)
{
if (!result.getStatus().isSuccess())
{
Log.e(TAG, "Error while trying to create the folder");
} else {
Log.i(TAG, "Created a folder");
DriveId driveId = result.getDriveFolder().getDriveId();
UploadFile(driveId);
}
}
});
}
}
}
});
}
private void UploadFile(final DriveId driveId)
{
Drive.DriveApi.newDriveContents(mGoogleApiClient).setResultCallback(new ResultCallback<DriveApi.DriveContentsResult>()
{
#Override
public void onResult(#NonNull DriveApi.DriveContentsResult driveContentsResult)
{
if (!driveContentsResult.getStatus().isSuccess())
{
Log.e(TAG, "U AR A MORON! Error while trying to create new file contents");
return;
}
OutputStream outputStream = driveContentsResult.getDriveContents().getOutputStream();
Toast.makeText(Uploader.this, "Uploading to drive....", Toast.LENGTH_LONG).show();
final File theFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyMobile_Videos/a.mov");
try
{
FileInputStream fileInputStream = new FileInputStream(theFile);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1)
{
outputStream.write(buffer, 0, bytesRead);
}
} catch (IOException e1)
{
Log.i(TAG, "Unable to write file contents.");
}
MetadataChangeSet changeSet = new MetadataChangeSet.Builder().setTitle(theFile.getName()).setMimeType("video/mov").setStarred(false).build();
DriveFolder folder = driveId.asDriveFolder();
folder.createFile(mGoogleApiClient, changeSet, driveContentsResult.getDriveContents()).setResultCallback(new ResultCallback<DriveFolder.DriveFileResult>()
{
#Override
public void onResult(#NonNull DriveFolder.DriveFileResult driveFileResult)
{
if (!driveFileResult.getStatus().isSuccess())
{
Log.e(TAG, "Error while trying to create the file");
return;
}
Toast.makeText(Uploader.this, "Created a file: " + driveFileResult.getDriveFile().getDriveId(), Toast.LENGTH_LONG).show();
String Folder_Id = driveId.getResourceId();
System.out.println("The folder id: " +Folder_Id);
//This is to get the file id from the listener
DriveId File_Uncompleted_Id = driveFileResult.getDriveFile().getDriveId();
DriveFile file = Drive.DriveApi.getFile(mGoogleApiClient, File_Uncompleted_Id);
file.addChangeListener(mGoogleApiClient, changeListener);
}
//A listener to handle file change events.
final private ChangeListener changeListener = new ChangeListener()
{
#Override
public void onChange(ChangeEvent event)
{
String File_Completed_Id = event.getDriveId().getResourceId();
System.out.println("The uploaded file id: " +File_Completed_Id);
System.out.println("File URL: https://drive.google.com/open?id=" +File_Completed_Id);
}
};
}
);
}
}
);
}
}

How to detect If AdRotator V2.1 is showing an Ad or an error occurred

I want to update my UI based on the scenario when an Ad is being shown or an error occurred. I am using AdRotator v2.1. Looking at the source code it seems that the control would collapse if it could not serve an ad from various provider, and the IsAdRotatorEnabled would be set to false. But that property does not trigger an notification change. How can i detect if no ads are being shown?
Enabled="{Binding AreAdsEnabled,Mode=TwoWay,FallbackValue=true,UpdateSourceTrigger=PropertyChanged}"
This is hack i am currently using. Its quite brittle. Its looking at log message for strings to detect if an error has occurred.
public class BaseAdControl
{
public AdRotatorControl CurrentAdRotatorControl { get; set; }
private UserControl userControlWrapper;
public BaseAdControl(AdRotatorControl MyAdRotatorControl, UserControl userControlWrapper)
{
// TODO: Complete member initialization
this.CurrentAdRotatorControl = MyAdRotatorControl;
this.userControlWrapper = userControlWrapper;
MyAdRotatorControl.PlatformAdProviderComponents.Add(AdRotator.Model.AdType.PubCenter, typeof(Microsoft.Advertising.WinRT.UI.AdControl));
MyAdRotatorControl.PlatformAdProviderComponents.Add(AdRotator.Model.AdType.AdDuplex, typeof(AdDuplex.Universal.Controls.Win.XAML.AdControl));
MyAdRotatorControl.Loaded += MyAdRotatorControl_Loaded;
MyAdRotatorControl.Unloaded += MyAdRotatorControl_Unloaded;
}
#region Public Properties
#endregion Public Properties
#region Public Methods
public virtual void adDuplex_AdLoadingError(object sender, AdDuplex.Universal.Win.WinRT.Models.AdLoadingErrorEventArgs e)
{
AdDuplex.Universal.Controls.Win.XAML.AdControl adCtrl = sender as AdDuplex.Universal.Controls.Win.XAML.AdControl;
adCtrl.AdLoadingError -= adDuplex_AdLoadingError;
Utilities.logger.LogDebug(e.Error.Message);
this.userControlWrapper.Visibility = Visibility.Collapsed;
Utilities.logger.LogDebug("Updated Visibility to: " + this.userControlWrapper.Visibility);
}
public virtual async void Logger(string message)
{
Utilities.logger.LogDebug("AdRotator: " + message);
if (string.Equals(message, "No Ads available", StringComparison.CurrentCultureIgnoreCase))
{
this.userControlWrapper.Visibility = Visibility.Collapsed;
Utilities.logger.LogDebug("Updated Visibility to: " + this.userControlWrapper.Visibility);
}
else if (message.Contains("Ad created for provider"))
{
var cont = CurrentAdRotatorControl as Control;
Object adType = null;
if (cont != null)
{
await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
() =>
{
Border border = VisualTreeHelper.GetChild(CurrentAdRotatorControl, 0) as Border;
if (border != null)
{
adType = border.Child;
}
});
if (adType != null)
{
if (adType is Microsoft.Advertising.WinRT.UI.AdControl)
{
var pubsub = adType as Microsoft.Advertising.WinRT.UI.AdControl;
if (pubsub != null)
pubsub.ErrorOccurred += pubsub_ErrorOccurred;
}
else if (adType is AdDuplex.Universal.Controls.Win.XAML.AdControl)
{
var adDuplex = adType as AdDuplex.Universal.Controls.Win.XAML.AdControl;
if (adDuplex != null)
adDuplex.AdLoadingError += adDuplex_AdLoadingError;
}
else if (adType is SomaAd)
{
var smato = adType as SomaAd;
if (smato != null)
smato.GetAdError += smato_GetAdError;
}
}
}
this.userControlWrapper.Visibility = Utilities.AreAdsEnabled ? Visibility.Visible : Visibility.Collapsed;
Utilities.logger.LogDebug("Updated Visibility to: "+this.userControlWrapper.Visibility);
}
}
public virtual void MyAdRotatorControl_Loaded(object sender, RoutedEventArgs e)
{
AdRotatorControl.Log += Logger;
}
public virtual void MyAdRotatorControl_Unloaded(object sender, RoutedEventArgs e)
{
AdRotatorControl.Log -= Logger;
}
public virtual void pubsub_ErrorOccurred(object sender, Microsoft.Advertising.WinRT.UI.AdErrorEventArgs e)
{
Microsoft.Advertising.WinRT.UI.AdControl adCtrl = sender as Microsoft.Advertising.WinRT.UI.AdControl;
adCtrl.ErrorOccurred -= pubsub_ErrorOccurred;
Utilities.logger.LogDebug(e.Error + " ," + e.ErrorCode);
this.userControlWrapper.Visibility = Visibility.Collapsed;
Utilities.logger.LogDebug("Updated Visibility to: " + this.userControlWrapper.Visibility);
}
public virtual void smato_GetAdError(object sender, string ErrorCode, string ErrorDescription)
{
SomaAd adCtrl = sender as SomaAd;
adCtrl.GetAdError -= smato_GetAdError;
Utilities.logger.LogDebug(ErrorDescription + " ," + ErrorCode);
this.userControlWrapper.Visibility = Visibility.Collapsed;
Utilities.logger.LogDebug("Updated Visibility to: " + this.userControlWrapper.Visibility);
}
#endregion Public Methods
}

WP8 issue with html agility pack

This is the function I used to get the string content from the website ..the problem is when executed first I cannot get the string content (App.Data2 = userprofile.InnerText;) since it skips to the next line (App.savecontent(App.Data2);) so that I get an empty string. If I recall the function I could get the string. Is there any possibility to solve this issue I need the string value first time automatically
This is my Page.cs code :
namespace Project_Future1
{
public partial class Page1 : PhoneApplicationPage
{
public Page1()
{
InitializeComponent();
{
string url = "http://www.astrosage.com/horoscope/daily-";
HtmlWeb.LoadAsync(url + App.Data + "-horoscope.asp", DownLoad);
}
data();
App.loadContent();
change2();
}
public void change2()
{
try
{
Util.LiveTile.UpdateLiveTile(App.Data2);
}
catch (Exception)
{
}
}
public void DownLoad(object sender, HtmlDocumentLoadCompleted e)
{
if (e.Error == null)
{
HtmlDocument doc = e.Document;
if (doc != null)
{
var userprofile = doc.DocumentNode.SelectSingleNode("//div[#class = 'ui-large-content']");
App.Data2 = userprofile.InnerText;
App.savecontent(App.Data2);
}
}
}
private void data()
{
SelectedSign.Text = App.Data;
SSContent.Text = App.Data2;
}
private void Refresh_click(object sender, EventArgs e)
{
SSContent.Text = App.Data2;
}
private void Fb_Click(object sender, EventArgs e)
{
NavigationService.Navigate(new Uri("/FB.xaml", UriKind.Relative));
}
}
}
this is my App.Xaml.cs File :
public static void savecontent(string save)
{
try
{
if (!string.IsNullOrEmpty(appFileName1))
{
IsolatedStorageFile oIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
oIsolatedStorage.CreateDirectory(appFolder1);
StreamWriter writeFile = new StreamWriter(new IsolatedStorageFileStream(appFolder1 + "\\" + appFileName1, FileMode.OpenOrCreate, oIsolatedStorage));
writeFile.WriteLine(save);
writeFile.Close();
}
}
catch (Exception)
{
throw;
}
}
this is my code to load the content from the storage :
public static void loadContent()
{
IsolatedStorageFile oIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
if (oIsolatedStorage.DirectoryExists(appFolder1))
{
IsolatedStorageFileStream fileStream = oIsolatedStorage.OpenFile(appFolder1 + "\\" + appFileName1, FileMode.Open, FileAccess.Read);
using (StreamReader reader = new StreamReader(fileStream))
{
App.Data2 = reader.ReadLine();
reader.Close();
}
}
}

Waiting and Return a result with DownloadStringAsync WP8

I do a webrequest with DownloadStringAsync() but I need to return the result only when the DownloadStringCompleted event has been called. After the downloadasync-method, I need to wait for the result and then I could return it in a string property. So I implemented a while(Result == "") but I don't know what to do there. I already tried Thread.sleep(500) but it seems the download never gets completed. And the code remains in the while forever.
string Result = "";
public String Query(DataRequestParam dataRequestParam)
{
try
{
WebClient web = new WebClient();
if (!string.IsNullOrEmpty(dataRequestParam.AuthentificationLogin))
{
System.Net.NetworkCredential account = new NetworkCredential(dataRequestParam.AuthentificationLogin, dataRequestParam.AuthentificationPassword);
web.Credentials = account;
}
web.DownloadStringCompleted += OnDownloadStringCompleted;
web.DownloadStringAsync(dataRequestParam.TargetUri);
while (Result == "")
{
//What am i supposed to do here ?
}
return Result;
}
catch(WebException we)
{
MessageBox.Show(we.Message);
return null;
}
}
private void OnDownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
{
//Error treating
}
else
{
Result = e.Result;
}
}
UI CODE
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
if (e.NavigationMode != NavigationMode.Back)
{
ServerFunctions.SetUserProfil(User.UserLogin,User.UserPassword);
this.listBoxGetDocsLibs.Clear();
List<BdeskDocLib> list = new List<BdeskDocLib>();
try
{
//HERE THE START OF THE DOWNLOAD
ServerFunctions.GetDocLibs(true);
}
catch (Exception ex)
{
//error
}
foreach (BdeskDocLib docLib in list)
{
this.listBoxGetDocsLibs.Add(docLib);
}
}
}
the ServerFunction static class
public static List<BdeskDocLib> GetDocLibs(bool onlyDocLibPerso)
{
string xmlContent = GetXml(URL_GETDOCLIBS);
List<BdeskDocLib> result = BdeskDocLib.GetListFromXml(xmlContent, onlyDocLibPerso);
return result;
}
private static String GetXml(string partialUrl)
{
string url = GenerateUrl(partialUrl);
DataRequestParam dataRequestParam = new DataRequestParam();
dataRequestParam.TargetUri = new Uri(url);
dataRequestParam.UserAgent = "BSynchro";
dataRequestParam.AuthentificationLogin = userLogin;
dataRequestParam.AuthentificationPassword = userPwd;
//HERE I START THE QUERY method
// NEED QUERY RETURNS A STRING or Task<String>
DataRequest requesteur = new DataRequest();
xmlResult=requesteur.Query(dataRequestParam);
if (CheckErrorConnexion(xmlResult) == false)
{
throw new Exception("Erreur du login ou mot de passe");
}
return xmlResult;
}
There is nothing good in blocking main UI (unless you really need to). But if you want to wait for your result you can make some use of async-await and TaskCompletitionSource - you can find more about on this blog and how to use TCS in this answer:
public static Task<string> myDownloadString(DataRequestParam dataRequestParam)
{
var tcs = new TaskCompletionSource<string>();
var web = new WebClient();
if (!string.IsNullOrEmpty(dataRequestParam.AuthentificationLogin))
{
System.Net.NetworkCredential account = new NetworkCredential(dataRequestParam.AuthentificationLogin, dataRequestParam.AuthentificationPassword);
web.Credentials = account;
}
web.DownloadStringCompleted += (s, e) =>
{
if (e.Error != null) tcs.TrySetException(e.Error);
else if (e.Cancelled) tcs.TrySetCanceled();
else tcs.TrySetResult(e.Result);
};
web.DownloadStringAsync(dataRequestParam.TargetUri);
return tcs.Task;
}
public async Task<string> Query(DataRequestParam dataRequestParam)
{
string Result = "";
try
{
Result = await myDownloadString(dataRequestParam);
}
catch (WebException we)
{
MessageBox.Show(we.Message);
return null;
}
return Result;
}
(I've not tried this code, there maight be some mistakes, but it should work)
Basing on this code you can also extend your WebClient with awaitable version of download string.