Xamarin Forms C# Live calculating Geo location distance - c#

I'm building a Taxi app and wanted to calculate the distance while the trip is going and update from the driver app side
I used Geolocator for live updates from https://github.com/jamesmontemagno/GeolocatorPlugin, I'm getting random locations and it's not stable on live updates so i changed getting the location after a minute
private async Task StartTrackingAsync(bool tracking)
{
try
{
PermissionStatus hasPermission = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Location);
if (hasPermission != PermissionStatus.Denied)
{
// Permission Granted
// check for req
if (tracking)
{
// Check is listening...
if (CrossGeolocator.Current.IsListening)
{
// Start
CrossGeolocator.Current.PositionChanged += CrossGeolocator_Current_PositionChanged;
CrossGeolocator.Current.PositionError += CrossGeolocator_Current_PositionError;
}
else
{
CrossGeolocator.Current.PositionChanged += CrossGeolocator_Current_PositionChanged;
CrossGeolocator.Current.PositionError += CrossGeolocator_Current_PositionError;
object aType = "Automotive Navigation";
if (await CrossGeolocator.Current.StartListeningAsync(TimeSpan.FromSeconds(5), 50,
true, new ListenerSettings
{
ActivityType = ActivityType.AutomotiveNavigation,
AllowBackgroundUpdates = true,
DeferLocationUpdates = true,
DeferralDistanceMeters = 100,
DeferralTime = TimeSpan.FromSeconds(50),
ListenForSignificantChanges = true,
PauseLocationUpdatesAutomatically = false
}))
{
tracking = true;
}
}
}
else
{
CrossGeolocator.Current.PositionChanged -= CrossGeolocator_Current_PositionChanged;
CrossGeolocator.Current.PositionError -= CrossGeolocator_Current_PositionError;
await CrossGeolocator.Current.StopListeningAsync();
tracking = false;
}
}
else
{
// Permission Denied
await DisplayAlert("Location Error", "Error Getting Location", "OK");
}
}
catch (Exception ex)
{
// Error Accured
await DisplayAlert("Location Error", "Error Getting Location: " + ex.Message, "OK");
}
}
private void CrossGeolocator_Current_PositionError(object sender, PositionErrorEventArgs e)
{
}
private void CrossGeolocator_Current_PositionChanged(object sender, PositionEventArgs e)
{
Device.BeginInvokeOnMainThread(async () =>
{
Plugin.Geolocator.Abstractions.Position position = e.Position;
if (Cposition != e.Position)
{
Cposition = e.Position;
mainmap.MoveToRegion(MapSpan.FromCenterAndRadius(new Xamarin.Forms.Maps.Position(position.Latitude, position.Longitude), Distance.FromMiles(1)).WithZoom(2));
loader.IsVisible = false;
mainmap.IsVisible = true;
local.Lat = position.Latitude;
local.Lng = position.Longitude;
}
});
}
private void DistanceUpdate(bool w = false)
{
Device.StartTimer(new TimeSpan(0, 0, 1), () =>
{
UpdateDistance();
return w;
});
}
private async void UpdateDistance()
{
// Get Trip Location
Models.Location SLocal = Trip.Location;
Xamarin.Essentials.Location startTrip = new Xamarin.Essentials.Location(SLocal.Lat, SLocal.Lng);
try
{
if (local != null)
{
Xamarin.Essentials.Location OnTrip = new Xamarin.Essentials.Location(local.Lat, local.Lng);
double distance = Xamarin.Essentials.Location.CalculateDistance(startTrip, OnTrip, DistanceUnits.Kilometers);
double t = tdistance + distance;
tdistance = Math.Round(t, 2);
if (Trip.Key != null)
{
_firebaseDatabase.UpdateTripDriverLocation(Trip.Key, local);
if (Trip.Status == "Started")
{
_firebaseDatabase.UpdateTripLocation(Trip.Key, local);
}
}
}
}
catch (Exception ex)
{
// Unable to get location
await DisplayAlert(ex.Source, "ERROR: " + ex.Message, "OK");
}
}
I'm not getting the current location but a random location and the distance produces more 5000km in 2 minutes before the driver starts moving

Related

C# Monitoring desktop screen from a Windows service

I have just written the C# Code that is recording the screenshot of the desktop.It works on Winforms but not works in windows service.
My code as below:
public partial class ScreenCapture : ServiceBase
{
bool rec = false;
Rectangle screenSize = Screen.PrimaryScreen.Bounds;
UInt32 frameCount = 0;
VideoFileWriter writer;
int width = SystemInformation.VirtualScreen.Width;
int height = SystemInformation.VirtualScreen.Height;
AForge.Video.ScreenCaptureStream streamVideo;
Stopwatch stopWatch = new Stopwatch();
public ScreenCapture()
{
InitializeComponent();
writer = new VideoFileWriter();
if (!System.Diagnostics.EventLog.SourceExists("MySource"))
{
System.Diagnostics.EventLog.CreateEventSource("MySource", "MyLog");
}
eventLog1.Source = "MySource";
this.CanHandleSessionChangeEvent = true;
}
protected override void OnSessionChange(SessionChangeDescription changeDescription)
{
string folderName = #"C:\LoginLog";
if (changeDescription.Reason == SessionChangeReason.SessionLogon)
{
eventLog1.WriteEntry(changeDescription.SessionId + " User Logon");
if (!Directory.Exists(folderName))
{
Directory.CreateDirectory(folderName);
}
StartRec(folderName);
}
else if (changeDescription.Reason == SessionChangeReason.SessionLogoff)
{
eventLog1.WriteEntry(changeDescription.SessionId + " User Logoff");
rec = false;
}
else if (changeDescription.Reason == SessionChangeReason.SessionLock)
{
eventLog1.WriteEntry(changeDescription.SessionId + " User Lock");
rec = false;
}
else if (changeDescription.Reason == SessionChangeReason.SessionUnlock)
{
eventLog1.WriteEntry(changeDescription.SessionId + " User Unlock");
if (!Directory.Exists(folderName))
{
Directory.CreateDirectory(folderName);
}
StartRec(folderName);
}
base.OnSessionChange(changeDescription);
}
private void StartRec(string path)
{
if (rec == false)
{
rec = true;
frameCount = 0;
string time = DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ssff");
string compName = Environment.UserName;
string fullName = path + "\\" + compName.ToUpper() + "_" + time;
try
{
writer.Open(
fullName + ".mp4",
width,
height,
10,
VideoCodec.MPEG4, 1000000);
}
catch (Exception ex)
{
eventLog1.WriteEntry("Exception StartRec: " + ex.Message);
}
DoJob();
}
}
private void DoJob()
{
try
{
Rectangle screenArea = Rectangle.Empty;
foreach (System.Windows.Forms.Screen screen in
System.Windows.Forms.Screen.AllScreens)
{
screenArea = Rectangle.Union(screenArea, screen.Bounds);
}
streamVideo = new ScreenCaptureStream(screenArea);
streamVideo.NewFrame += new NewFrameEventHandler(video_NewFrame);
streamVideo.Start();
stopWatch.Start();
}
catch (Exception ex)
{
eventLog1.WriteEntry("Exception DoJob: " + ex.Message);
}
}
private void video_NewFrame(object sender, AForge.Video.NewFrameEventArgs eventArgs)
{
try
{
if (rec)
{
frameCount++;
writer.WriteVideoFrame(eventArgs.Frame);
}
else
{
stopWatch.Reset();
Thread.Sleep(500);
streamVideo.SignalToStop();
Thread.Sleep(500);
writer.Close();
}
}
catch (Exception ex)
{
eventLog1.WriteEntry("Exception Video New Frame: " + ex.Message);
}
}
}
And the service can save a .mp4 file, but it cannot open it.I think windows service can not capture desktop screen.
Can anybody help me how to solve this problem?
thanks in advance.
You need to set windows service run under interactive account,
To do so you need to go to properties of service got to logon tab and login by
your windows account.

Different behaviors when instantiated from button or timer in c#

I have a function called getMessages that can be called by a Button click (using the RelayCommand trigger) or that is called in a timer every 15s.
The desired behavior is:
webservice > deserialize answer > system notification > updatelistview > insert localDB
But when the function is called by the timer the updatelistview is not done. Why does this happen if the function is the same and works perfectly in the button command?
CODE:
// Get messages for the logged in user
public async void getMessages()
{
try
{
List<FriendGetMessage> msg = new List<FriendGetMessage>();
var response = await CommunicationWebServices.GetCHAT("users/" + au.idUser + "/get", au.token);
if (response.StatusCode == HttpStatusCode.OK) // If there are messages for me.
{
var aux = await response.Content.ReadAsStringAsync();
IEnumerable<FriendGetMessage> result = JsonConvert.DeserializeObject<IEnumerable<FriendGetMessage>>(aux);
if (result != null)
{
foreach (var m in result)
{
msg.Add(m);
}
//MsgList=msg;
foreach (var f in Friends)
{
if (f.msg == null || f.msg.Count() == 0)
{
f.msg = new ObservableCollection<Messages>();
}
foreach (var mess in msg)
{
if (mess.idUser == f.idUser)
{
Messages mm = new Messages();
mm.received = mess.message;
mm.timestamp = "Received " + mess.serverTimestamp;
mm.align = "Right";
// Add to the friend list.
f.msg.Add(mm);
// Add to Local DB
InsertMessage(null, au.idUser.ToString(), f.idUser, mess.message, mess.serverTimestamp);
var notification = new System.Windows.Forms.NotifyIcon()
{
Visible = true,
Icon = System.Drawing.SystemIcons.Information,
BalloonTipIcon = System.Windows.Forms.ToolTipIcon.Info,
BalloonTipTitle = "New Message from " + f.name,
BalloonTipText = "Message: " + mess.message,
};
// Display for 5 seconds.
notification.ShowBalloonTip(5);
// The notification should be disposed when you don't need it anymore,
// but doing so will immediately close the balloon if it's visible.
notification.Dispose();
}
}
}
counterChat = 1; // resets the counter
}
}
else {
counterChat = counterChat * 2;
}
//var sql = "select * from chat";
//var respo = GetFromDatabase(sql);
OnPropertyChanged("Friends");
}
catch (Exception e)
{
MessageBox.Show("GetMessages: " + e);
Debug.WriteLine("{0} Exception caught.", e);
}
}
CODE TIMER:
public void chatUpdate()
{
_timerChat = new DispatcherTimer(DispatcherPriority.Render);
_timerChat.Interval = TimeSpan.FromSeconds(15);
_timerChat.Tick += new EventHandler(timerchat_Tick);
_timerChat.Start();
}
public void timerchat_Tick(object sender, EventArgs e)
{
if (counterChat != incChat)
{
incChat++;
}
else
{
getMessages();
OnPropertyChanged("Friends");
incChat = 0;
}
}
ADDED - I've also tried this and didn't worked (it seems that is some kind of concurrency problem to the ObservableCollection called Friends (is a friendslist) each friend has an ObservableCollection of messages (is a chat))
public void chatUpdate()
{
_timerChat = new DispatcherTimer(DispatcherPriority.Render);
_timerChat.Interval = TimeSpan.FromSeconds(15);
_timerChat.Tick += new EventHandler(timerchat_Tick);
_timerChat.Start();
}
public async void timerchat_Tick(object sender, EventArgs e)
{
if (counterChat != incChat)
{
incChat++;
}
else
{
Application.Current.Dispatcher.Invoke((Action)async delegate { await getMessages(); });
incChat = 0;
}
}
Best regards,
I think you need to make the timer handler be an async method as follows:
public async void timerchat_Tick(object sender, EventArgs e)
{
if (counterChat != incChat)
{
incChat++;
}
else
{
await getMessages();
OnPropertyChanged("Friends");
incChat = 0;
}
}
This way OnPropertyChanged("Friends") is guaranteed to fire after the work in getMessages is done.
The methods need to change to:
DispatcherTimer _timerChat = new DispatcherTimer(DispatcherPriority.Render);
_timerChat.Interval = TimeSpan.FromSeconds(15);
_timerChat.Tick += new EventHandler(timerchat_Tick);
_timerChat.Start();
public async void timerchat_Tick(object sender, EventArgs e)
{
//...
await getMessages();
//...
}
public async Task getMessages()
{
try
{
// ... your code here
string result = await response.Content.ReadAsStringAsync();
// .... rest of your code
}
catch (Exception e)
{
MessageBox.Show("GetMessages: " + e);
}
}
It is solved. The problem was in my ViewModels I was opening multiple threads and sometimes the right one would update the UI and sometimes no.
Thanks for all the answers.

How to connect/pair devices correctly on wifi direct?

It is my first program on wifi direct so I made a simple program that just discover all nearby devices and then try to connect to one of them the discovery works fine and gets all the devices the problem is in the connection that always fails after using this function WiFiDirectDevice.FromIdAsync() it keeps paring for too long and then it fails always.
I was following the code on this microsoft tutorial: https://channel9.msdn.com/Events/Build/2015/3-98
Here is my code:
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace App7
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
DeviceInformationCollection DevicesFound;
WiFiDirectAdvertisementPublisher pub;
WiFiDirectConnectionListener listener;
CancellationTokenSource m_CancellationTokenSource;
private async void button_Click(object sender, RoutedEventArgs e)
{
String DeviceSelector = WiFiDirectDevice.GetDeviceSelector(WiFiDirectDeviceSelectorType.AssociationEndpoint);
DevicesFound = await DeviceInformation.FindAllAsync(DeviceSelector);
if(DevicesFound.Count>0)
{
connectedDeviceslist.ItemsSource = DevicesFound;
var dialog = new MessageDialog(DevicesFound[0].Name);
await dialog.ShowAsync();
}
}
private async void button1_Click(object sender, RoutedEventArgs e)
{
int selectedIndex = connectedDeviceslist.SelectedIndex;
String deviceID = DevicesFound[selectedIndex].Id;
var selecetedDevice = DevicesFound[selectedIndex];
try
{
WiFiDirectConnectionParameters connectionParams = new WiFiDirectConnectionParameters();
connectionParams.GroupOwnerIntent = Convert.ToInt16("1");
connectionParams.PreferredPairingProcedure = WiFiDirectPairingProcedure.GroupOwnerNegotiation;
m_CancellationTokenSource = new CancellationTokenSource();
var wfdDevice = await WiFiDirectDevice.FromIdAsync(selecetedDevice.Id, connectionParams).AsTask(m_CancellationTokenSource.Token);
var EndpointPairs = wfdDevice.GetConnectionEndpointPairs();
}
catch(Exception ex)
{
await Dispatcher.RunAsync(CoreDispatcherPriority.High, async() =>
{
var dialog = new MessageDialog(ex.Message);
await dialog.ShowAsync();
});
}
}
private void button2_Click(object sender, RoutedEventArgs e)
{
pub = new WiFiDirectAdvertisementPublisher();
pub.Advertisement.ListenStateDiscoverability = WiFiDirectAdvertisementListenStateDiscoverability.Normal;
listener = new WiFiDirectConnectionListener();
listener.ConnectionRequested += OnConnectionRequested;
pub.Start();
}
private async void OnConnectionRequested(WiFiDirectConnectionListener sender, WiFiDirectConnectionRequestedEventArgs args)
{
try
{
var ConnectionRequest = args.GetConnectionRequest();
var tcs = new TaskCompletionSource<bool>();
var dialogTask = tcs.Task;
var messageDialog = new MessageDialog("Connection request received from " + ConnectionRequest.DeviceInformation.Name, "Connection Request");
// Add commands and set their callbacks; both buttons use the same callback function instead of inline event handlers
messageDialog.Commands.Add(new UICommand("Accept", null, 0));
messageDialog.Commands.Add(new UICommand("Decline", null, 1));
// Set the command that will be invoked by default
messageDialog.DefaultCommandIndex = 1;
// Set the command to be invoked when escape is pressed
messageDialog.CancelCommandIndex = 1;
await Dispatcher.RunAsync(CoreDispatcherPriority.High, async () =>
{
// Show the message dialog
var commandChosen = await messageDialog.ShowAsync();
tcs.SetResult((commandChosen.Label == "Accept") ? true : false);
});
var fProceed = await dialogTask;
if (fProceed == true)
{
var tcsWiFiDirectDevice = new TaskCompletionSource<WiFiDirectDevice>();
var wfdDeviceTask = tcsWiFiDirectDevice.Task;
// WriteToOutput("Connecting to " + ConnectionRequest.DeviceInformation.Name + "...");
WiFiDirectConnectionParameters ConnectionParams = new WiFiDirectConnectionParameters();
await Dispatcher.RunAsync(CoreDispatcherPriority.High, async () =>
{
try
{
ConnectionParams.GroupOwnerIntent = 14;
tcsWiFiDirectDevice.SetResult(await WiFiDirectDevice.FromIdAsync(ConnectionRequest.DeviceInformation.Id, ConnectionParams));
}
catch (Exception ex)
{
// WriteToOutput("FromIdAsync task threw an exception: " + ex.ToString());
}
});
WiFiDirectDevice wfdDevice = await wfdDeviceTask;
var EndpointPairs = wfdDevice.GetConnectionEndpointPairs();
/* m_ConnectedDevices.Add("dummy", wfdDevice);
WriteToOutput("Devices connected on L2, listening on IP Address: " + EndpointPairs[0].LocalHostName.ToString() + " Port: " + Globals.strServerPort);
StreamSocketListener listenerSocket = new StreamSocketListener();
listenerSocket.ConnectionReceived += OnSocketConnectionReceived;
await listenerSocket.BindEndpointAsync(EndpointPairs[0].LocalHostName, Globals.strServerPort);*/
}
else
{
/* // Decline the connection request
WriteToOutput("Connection request from " + ConnectionRequest.DeviceInformation.Name + " was declined");
ConnectionRequest.Dispose();*/
}
}
catch (Exception ex)
{
//WriteToOutput("FromIdAsync threw an exception: " + ex.ToString());
}
}
}
}

SerialDevice.LoadAsync block await task

I having a little issue reading data from Nave32 Flight Controller, I'm able to send data to the card using the SerialDevice class but when the LoadAsync Method is call and there is no more data to read the app hung and does not move forward, there is not exception during the execution of the process. I look at the app state and there is a bunch a task block and I'm not sure why. See image below
UPDATE
Firmware source code is here
here is my example code
namespace Apps.Receiver
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
this.dataRecived.Text = DateTime.Now.ToString();
}
private async Task readAsync(SerialDevice serialPort)
{
string data = string.Empty;
using (var dataReaderObject = new DataReader(serialPort.InputStream))
{
try
{
dataReaderObject.InputStreamOptions = InputStreamOptions.None;
var hasData = true;
while (hasData)
{
var bytesRead = await dataReaderObject.LoadAsync(serialPort.DataBits);
if (bytesRead > 0)
data += dataReaderObject.ReadString(bytesRead);
else
hasData = false;
}
}
catch (Exception ex)
{
status.Text = "reading data fail: " + ex.Message;
closeDevice(serialPort);
}
}
dataRecived.Text = data;
}
private async void sendData_Click(object sender, RoutedEventArgs e)
{
var serialPort = await getSerialDevice("COM3");
if (dataToSend.Text.Length != 0)
{
using (var dataWriteObject = new DataWriter(serialPort.OutputStream))
{
try
{
if (dataToSend.Text.Equals("#", StringComparison.CurrentCultureIgnoreCase))
dataWriteObject.WriteString(dataToSend.Text);
else
dataWriteObject.WriteString(dataToSend.Text + "\n");
var bytesWritten = await dataWriteObject.StoreAsync();
if (bytesWritten > 0)
{
status.Text = dataToSend.Text + ", ";
status.Text += "bytes written successfully!";
}
await readAsync(serialPort);
}
catch (Exception ex)
{
status.Text = "writing data fail: " + ex.Message;
}
}
closeDevice(serialPort);
}
else
{
status.Text = "Enter the text you want to write and then click on 'WRITE'";
}
}
private void closeDevice(SerialDevice device)
{
device.Dispose();
device = null;
}
private async Task<SerialDevice> getSerialDevice(string portName)
{
var aqs = SerialDevice.GetDeviceSelector("COM3");
var devices = await DeviceInformation.FindAllAsync(aqs);
if (devices.Count == 0)
throw new Exception("Unablet to connect to device");
var serialPort = await SerialDevice.FromIdAsync(devices[0].Id);
if (serialPort == null)
throw new Exception("Unablet to Open to port " + portName);
serialPort.BaudRate = 115200;
serialPort.DataBits = 8;
return serialPort;
}
}
}
See this example, try if it helps doing it like this:
await reader.LoadAsync(8192);
while (reader.UnconsumedBufferLength > 0)
{
strBuilder.Append(reader.ReadString(reader.UnconsumedBufferLength));
await reader.LoadAsync(8192);
}

Skydrive wp7 App: GetAsync method stopped working

On my windows phone 7 Mango app I use the Microsoft.Live and Microsoft.Live.Controls references to download and upload on Skydrive. Logging in and uploading files works fine but whenever I call the "client.GetAsync("/me/skydrive/files");" on the LiveConnectClient the Callback result is empty just containing the error: "An error occurred while retrieving the resource. Try again later."
I try to retrieve the list of files with this method.
This error suddenly occured without any change on the source code of the app (I think..) which worked perfectly fine for quite a while until recently. At least I didn't change the code section for up- or downloading.
I tried out the "two-step verification" of Skydrive, still the same: can log in but not download.
Also updating the Live refercences to 5.5 didn't change anything.
Here is the code I use. The error occurs in the "getDir_Callback" in the "e" variable.
Scopes (wl.skydrive wl.skydrive_update) and clientId are specified in the SignInButton which triggers "btnSignin_SessionChanged".
private void btnSignin_SessionChanged(object sender, LiveConnectSessionChangedEventArgs e)
{
if (e.Status == LiveConnectSessionStatus.Connected)
{
connected = true;
processing = true;
client = new LiveConnectClient(e.Session);
client.GetCompleted += new EventHandler<LiveOperationCompletedEventArgs>(OnGetCompleted);
client.UploadCompleted += new EventHandler<LiveOperationCompletedEventArgs>(UploadCompleted);
client.DownloadCompleted += new EventHandler<LiveDownloadCompletedEventArgs>(OnDownloadCompleted);
client.DownloadProgressChanged += new EventHandler<LiveDownloadProgressChangedEventArgs>(client_DownloadProgressChanged);
infoTextBlock.Text = "Signed in. Retrieving file IDs...";
client.GetAsync("me");
}
else
{
connected = false;
infoTextBlock.Text = "Not signed into Skydrive.";
client = null;
}
}
private void OnGetCompleted(object sender, LiveOperationCompletedEventArgs e)
{
if (e.Error == null)
{
client.GetCompleted -= new EventHandler<LiveOperationCompletedEventArgs>(OnGetCompleted);
client.GetCompleted += getDir_Callback;
client.GetAsync("/me/skydrive/files");
client_id = (string)e.Result["id"];
if (e.Result.ContainsKey("first_name") && e.Result.ContainsKey("last_name"))
{
if (e.Result["first_name"] != null && e.Result["last_name"] != null)
{
infoTextBlock.Text = "Hello, " +
e.Result["first_name"].ToString() + " " +
e.Result["last_name"].ToString() + "!";
}
}
else
{
infoTextBlock.Text = "Hello, signed-in user!";
}
}
else
{
infoTextBlock.Text = "Error calling API: " +
e.Error.ToString();
}
processing = false;
}
public void getDir_Callback(object s, LiveOperationCompletedEventArgs e)
{
client.GetCompleted -= getDir_Callback;
//filling Dictionary with IDs of every file on SkyDrive
if (e.Result != null)
ParseDir(e);
if (!String.IsNullOrEmpty(e.Error.Message))
infoTextBlock.Text = e.Error.Message;
else
infoTextBlock.Text = "File-IDs loaded";
}
Yo shall use client.GetAsync("me/SkyDrive/files", null) in place of client.GetAsync("me");
This is my code and it works fine.
private void btnSignIn_SessionChanged(object sender, Microsoft.Live.Controls.LiveConnectSessionChangedEventArgs e)
{
try
{
if (e.Session != null && e.Status == LiveConnectSessionStatus.Connected)
{
client = new LiveConnectClient(e.Session);
client.GetCompleted += new EventHandler<LiveOperationCompletedEventArgs>(client_GetCompleted);
client.UploadCompleted += new EventHandler<LiveOperationCompletedEventArgs>(client_UploadCompleted);
client.GetAsync("me/SkyDrive/files", null);
client.DownloadAsync("me/SkyDrive", null);
canUpload = true;
ls = e.Session;
}
else
{
if (client != null)
{
MessageBox.Show("Signed out successfully!");
client.GetCompleted -= client_GetCompleted;
client.UploadCompleted -= client_UploadCompleted;
canUpload = false;
}
else
{
canUpload = false;
}
client = null;
canUpload = false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void client_GetCompleted(object sender, LiveOperationCompletedEventArgs e)
{
try
{
List<System.Object> listItems = new List<object>();
if (e.Result != null)
{
listItems = e.Result["data"] as List<object>;
for (int x = 0; x < listItems.Count(); x++)
{
Dictionary<string, object> file1 = listItems[x] as Dictionary<string, object>;
string fileName = file1["name"].ToString();
if (fileName == lstmeasu[0].Title)
{
folderID = file1["id"].ToString();
folderAlredyPresent = true;
}
}
}
}
catch (Exception)
{
MessageBox.Show("An error occured in getting skydrive folders, please try again later.");
}
}
It miraculously works again without me changing any code. It seems to be resolved on the other end. I have no clue what was wrong.

Categories

Resources