Why is the BLE device not disconnecting? - c#

I am able to pair a Bluetooth skincare device to my PC using a C# app that I wrote.
Definition:
//Device Data
BluetoothLEDevice bluetoothLeDevice;
DeviceData deviceData=new DeviceData();
GattDeviceServicesResult result;
static DeviceInformation device = null;
The handlers that reads devices, implemented in MainForm():
// Query for extra properties you want returned
string[] requestedProperties = { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected" };
DeviceWatcher deviceWatcher =
DeviceInformation.CreateWatcher(
BluetoothLEDevice.GetDeviceSelectorFromPairingState(false),
requestedProperties,
DeviceInformationKind.AssociationEndpoint);
// Register event handlers before starting the watcher.
// Added, Updated and Removed are required to get all nearby devices
deviceWatcher.Added += DeviceWatcher_Added;
deviceWatcher.Updated += DeviceWatcher_Updated;
deviceWatcher.Removed += DeviceWatcher_Removed;
// EnumerationCompleted and Stopped are optional to implement.
deviceWatcher.EnumerationCompleted += DeviceWatcher_EnumerationCompleted;
deviceWatcher.Stopped += DeviceWatcher_Stopped;
// Start the watcher.
deviceWatcher.Start();
The code that pairs the device with a click of a button:
private async void btnPair_Click(object sender, EventArgs e)
{
feedbackTB.AppendText("Waiting for pairing..." + Environment.NewLine);
if (device == null)
{
statusBox.Text = "Please, make sure the device is on, and try again. Uncover the device and it will automatically turn on.";
feedbackTB.AppendText("Timed out." + Environment.NewLine);
Thread.Sleep(200);
}
else
{
try
{
hydrationFqList = new List<int>();
psList = new List<int>();
bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(device.Id);
statusBox.Text = "Attempting to pair with device";
result = await bluetoothLeDevice.GetGattServicesAsync();
if (result.Status == GattCommunicationStatus.Success)
{
statusBox.Text = "Pairing succeeded";
feedbackTB.AppendText("Device paired." + Environment.NewLine);
var services = result.Services;
foreach (var service in services)
{
if (service.Uuid.ToString() == deviceData.devInfoSvc)
{
GattCharacteristicsResult charactiristicResult = await service.GetCharacteristicsAsync();
feedbackTB.AppendText("Skimming device info service... " + Environment.NewLine);
if (charactiristicResult.Status == GattCommunicationStatus.Success)
{
feedbackTB.AppendText("Reading device info... " + Environment.NewLine);
var characteristics = charactiristicResult.Characteristics;
foreach (var characteristic in characteristics)
{
GattCharacteristicProperties properties = characteristic.CharacteristicProperties;
if (properties.HasFlag(GattCharacteristicProperties.Read))
{
GattReadResult rResult = await characteristic.ReadValueAsync();
var reader = DataReader.FromBuffer(rResult.Value);
byte[] input = new byte[reader.UnconsumedBufferLength];
reader.ReadBytes(input);
string data = Encoding.ASCII.GetString(input);
if (characteristic.Uuid.ToString() == deviceData.mfgNameCt)
{
mfgNameTB.Text = data;
}
if (characteristic.Uuid.ToString() == deviceData.modelNumCt)
{
modelNumTB.Text = data;
}
if (characteristic.Uuid.ToString() == deviceData.serialNumCt)
{
serialNumber = data;
snTB.Text = serialNumber;
}
if (characteristic.Uuid.ToString() == deviceData.macAddrCt)
{
macAddress = data;
macAddrTB.Text = macAddress;
}
if (characteristic.Uuid.ToString() == deviceData.hwRevCt)
{
hwRevisionTB.Text = data;
}
if (characteristic.Uuid.ToString() == deviceData.fwRevCt)
{
fwRevisionTB.Text = data;
}
}
statusBox.Text = "Press and hold device against your skin to start scan.";
}
}
}
}
}
else
{
statusBox.Text = "Please, make sure the device is connected, and try again.";
feedbackTB.AppendText("Timed out." + Environment.NewLine);
}
feedbackTB.AppendText("Number of run(s):" + increment + Environment.NewLine);
}
catch (Exception err)
{
ErrorWindow eWindow = new ErrorWindow();
eWindow.label4.Text = err.GetType().ToString();
eWindow.errorDetails.Text = err.Message;
eWindow.ShowDialog();
}
}
}
And this is my newly implemented disconnect button:
private void btnDisconnect _Click(object sender, EventArgs e)
{
bluetoothLeDevice.Dispose();
}
Now we get to the issue.
When the device is on, a blue light is suppose to flash.
When the device is paired to a PC or app, the blue light will stay on.
I expect the device to disconnect when the button is clicked. Upon the click, the light will start flashing again when it's just turned on.
But upon clicking on the button, nothing happened. The device is still stuck connected.
How can I fix this?

Related

BLE - Bluetooth Low Energy - C# Problem with the Gatt services

I'm working on a Project (Console-Application .NET Framework 4.7.2 c#) to find nearby BLE devices and it's working well, the device(The device is just an Arduino with a BLE shield.) is discovered and i was able to read values from it. so the problem is that i wanted to do the same but on another PC (Same Code, Conditions, everything the same). it showed me that the pc is with the device connected but unreachable here on this place of the code :
GattDeviceServicesResult result = await bluetoothLeDevice.GetGattServicesAsync();
So i tried again and again on 3 different PCs and Laptops but it didn't work.
On the pc first i got connected to, it works well without problems. Can someone pls help me and say what is the matter. Here is my Code:
namespace QuickBlueToothLE
{
class Program
{
static public readonly Dictionary<string, DeviceInformation> mDiscoveredDevices = new Dictionary<string, DeviceInformation>();
static DeviceInformation device = null;
public static string HEG_Service_ID = "00001826-0000-1000-8000-00805f9b34fb";
public static DeviceWatcher deviceWatcher = null;
// Abfrage nach zusätzlichen Eigenschaften, die zurückgegeben werden sollen
public static string[] requestedProperties =
{
"System.Devices.Aep.DeviceAddress",
"System.Devices.Aep.IsConnected",
"System.Devices.Aep.Bluetooth.Le.IsConnectable"
};
static async Task Main(string[] args)
{
deviceWatcher = DeviceInformation.CreateWatcher
(BluetoothLEDevice.GetDeviceSelectorFromPairingState(false),
requestedProperties,
DeviceInformationKind.AssociationEndpoint);
// Register event handlers before starting the watcher.
// Added, Updated and Removed are required to get all nearby devices
deviceWatcher.Added += DeviceWatcher_Added;
deviceWatcher.Updated += DeviceWatcher_Updated;
deviceWatcher.Removed += DeviceWatcher_Removed;
// EnumerationCompleted and Stopped are optional to implement.
deviceWatcher.EnumerationCompleted += DeviceWatcher_EnumerationCompletedAsync;
deviceWatcher.Stopped += DeviceWatcher_Stopped;
// Start the watcher.
deviceWatcher.Start();
while (true)
{
if (device == null)
Thread.Sleep(2000);
else
{
Console.WriteLine("Press Any Key to connect to HEG-900725");
Console.ReadKey();
BluetoothLEDevice bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(device.Id);
Console.WriteLine("Attempting to connect with device");
GattDeviceServicesResult result = await bluetoothLeDevice.GetGattServicesAsync();
var services = result.Services;
if (result.Status == GattCommunicationStatus.Success)
{
Console.WriteLine("Connection succeeded" + " "+ bluetoothLeDevice.DeviceInformation.Pairing.IsPaired);
Console.WriteLine(device.Id);
foreach (var service in services)
{
if (service.Uuid.ToString() == HEG_Service_ID)
{
Console.WriteLine("Found Heg Service");
GattCharacteristicsResult charactiristicResult = await service.GetCharacteristicsAsync();
if (charactiristicResult.Status == GattCommunicationStatus.Success)
{
var characteristics = charactiristicResult.Characteristics;
foreach (var characteristic in characteristics)
{
Console.WriteLine("---------------");
GattCharacteristicProperties properties = characteristic.CharacteristicProperties;
Console.WriteLine("CharactesticHandle:"+characteristic.AttributeHandle +"\r\n"+"UUID"+characteristic.Uuid);
if (properties.HasFlag(GattCharacteristicProperties.Notify))
{
Console.WriteLine("Notify poroperty found");
GattCommunicationStatus status =
await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(
GattClientCharacteristicConfigurationDescriptorValue.Notify);
if (status == GattCommunicationStatus.Success)
{
characteristic.ValueChanged += Characteristic_ValueChanged;
// Server has been informed of clients interest.
}
}
}
}
}
}
}
Console.WriteLine("Press Any Key to Exit application");
Console.WriteLine("\r\n" + "Values" + "\r\n");
Console.ReadKey();
foreach (var service in services)
{
service.Dispose();
}
bluetoothLeDevice.Dispose();
bluetoothLeDevice = null;
device = null;
Console.WriteLine(mDiscoveredDevices);
Console.WriteLine(mDiscoveredDevices.Count());
break;
}
}
Console.ReadKey();
deviceWatcher.Stop();
deviceWatcher = null;
}
private static void TXCharacteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
{
byte[] buffer = args.CharacteristicValue.ToArray();
}
private static void Characteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
{
var reader = DataReader.FromBuffer(args.CharacteristicValue);
var flags = reader.ReadByte();
var value = reader.ReadByte();
Console.WriteLine($"{flags} - {value}");
}
private static void DeviceWatcher_Stopped(DeviceWatcher sender, object args)
{
}
private static void DeviceWatcher_EnumerationCompletedAsync(DeviceWatcher sender, object args)
{
}
private static void DeviceWatcher_Removed(DeviceWatcher sender, DeviceInformationUpdate args)
{
}
private static void DeviceWatcher_Updated(DeviceWatcher sender, DeviceInformationUpdate args)
{
//throw new NotImplementedException();
}
private static void DeviceWatcher_Added(DeviceWatcher sender, DeviceInformation args)
{
Console.WriteLine(args.Name);
if (args.Name == "HEG_100053" || args.Name =="Arduino")
{
Console.WriteLine("Found: " + args.Name);
device = args;
bool keyExists = mDiscoveredDevices.ContainsKey(device.Id);
if (!keyExists)
{
mDiscoveredDevices.Add(device.Id, device);
}
}
}
//900725
//|| args.Name == "HEG_100053"
}
}

Multithread using backgroundworker and event handler

I'm developing a sample program to connect multiple device using backgroundworker. Each device connected will be add to the list as new object. After finished connecting all the devices, i wanted to add an event handler for each connected devices. The problem that i'm facing now is the event handler doesn't firing at all. Below are the sample codes.
The Connect click button event :
private void btnConnect_Click(object sender, EventArgs e)
{
using (BackgroundWorker m_oWorker = new BackgroundWorker())
{
m_oWorker.DoWork += delegate (object s, DoWorkEventArgs args)
{
int iIpStart = 0;
int iIpEnd = 0;
string strIp1 = string.Empty;
string strIp2 = string.Empty;
list.Clear();
string[] sIP1 = txtIpStart.Text.Trim().ToString().Split('.');
string[] sIP2 = txtIpEnd.Text.Trim().ToString().Split('.');
iIpStart = Convert.ToInt32(sIP1[3]);
iIpEnd = Convert.ToInt32(sIP2[3]);
strIp1 = sIP1[0] + "." + sIP1[1] + "." + sIP1[2] + ".";
strIp2 = sIP2[0] + "." + sIP2[1] + "." + sIP2[2] + ".";
Ping ping = new Ping();
PingReply reply = null;
int iIncre = 0;
int iVal = (100 / (iIpEnd - iIpStart));
for (int i = iIpStart; i <= iIpEnd; i++)
{
Thread.Sleep(100);
string strIpconnect = strIp1 + i.ToString();
Console.Write("ip address : " + strIpconnect + ", status: ");
reply = ping.Send(strIpconnect);
if (reply.Status.ToString() == "Success")
{
if (ConnectDevice(strIpconnect))
{
strLastDevice = strIpconnect + " Connected";
isconnected = true;
}
else
{
isconnected = false;
}
}
else
{
isconnected = false;
}
m_oWorker.ReportProgress(iIncre);
iIncre = iIncre + iVal;
}
m_oWorker.ReportProgress(100);
};
m_oWorker.ProgressChanged += new ProgressChangedEventHandler(m_oWorker_ProgressChanged);
m_oWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(m_oWorker_RunWorkerCompleted);
m_oWorker.WorkerReportsProgress = true;
m_oWorker.WorkerSupportsCancellation = true;
m_oWorker.RunWorkerAsync();
}
}
ConnectDevice function method. Connected device will be added to the list :
protected bool ConnectDevice(string sIP)
{
try
{
NewSDK sdk = new NewSDK();
if (sdk.Connect() == true)
{
list.Add(new objSDK { sdk = sdk, ipaddress = sIP });
return true;
}
else
{
}
}
catch() {}
return false;
}
the Backgroundworker :
void m_oWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//If it was cancelled midway
if (e.Cancelled)
{
lblStatus.Text = "Task Cancelled.";
}
else if (e.Error != null)
{
lblStatus.Text = "Error while performing background operation.";
}
else
{
lblStatus.Text = "Task Completed...";
btnListen.Enabled = true;
}
}
void m_oWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
//Here you play with the main UI thread
progressBar1.Value = e.ProgressPercentage;
lblStatus.Text = "Processing......" + progressBar1.Value.ToString() + "%";
if (isconnected)
{
listBox2.Items.Add(strLastDevice);
string[] ssplit = sDeviceInfo.Split(';');
foreach (string sword in ssplit)
{
listBox1.Items.Add(sword);
}
}
}
The function to attached event :
private void RegisterEvent()
{
foreach (objSDK obj in list)
{
obj.sdk.OnTransaction += () =>
{
listBox1.Items.Add("ip : " + obj.IP + " transaction");
};
}
}
You have declared m_oWorker as a local variable. I'm guessing this was a mistake ( the m_ prefix should only be used for class member variables)?
Also, you declared it within a using statement, meaning that it that the framework will call Dispose() on it at the end of the using block. Even if you held on to a reference to it (and I don't think you do) it still means its resources will be deallocated, which is probably why it isn't handling any events.
I try another workaround by using thread and task and work perfectly. Thanks for all response

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.

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