WP7 Skydrive API - creating folder doesnt work - c#

I try this tutorial to create new folder on skydrive from my WP7 app.
Here is my code:
private void MSAccountLoginToggleSwitch_Checked_1(object sender, RoutedEventArgs e)
{
try
{
LiveAuthClient auth = new LiveAuthClient("** my id **");
auth.LoginAsync(new string[] { "wl.skydrive_update", "wl.calendars_update" });
auth.LoginCompleted += auth_LoginCompleted;
}
catch (LiveAuthException exception)
{
MessageBox.Show("Error signing in: " + exception.Message);
}
}
private void auth_LoginCompleted(object sender, LoginCompletedEventArgs e)
{
if (e.Status == LiveConnectSessionStatus.Connected)
{
mySession = e.Session;
}
else
{
MSAccountLoginToggleSwitch.IsChecked = false;
}
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
try
{
var folderData = new Dictionary<string, object>();
folderData.Add("some test", "A brand new folder was created");
LiveConnectClient liveClient = new LiveConnectClient(mySession);
liveClient.PostAsync("me/skydrive", folderData);
}
catch (LiveConnectException exception)
{
MessageBox.Show("Error creating folder: " + exception.Message);
}
finally
{
MessageBox.Show("uploded");
}
}
it show me messagebox "uploaded", but when I look on my skydrive that file was not created.
It doesnt show any error message, what Im doing worng?

This line liveClient.PostAsync("me/skydrive", folderData); gives you a Task which you do not wait, you just show MessageBox.Show("uploded"); at the end. I don't think that async / await are supported in WP7, so you will need to handle Task with ContinueWith method:
private void Button_Click_1(object sender, RoutedEventArgs e)
{
var folderData = new Dictionary<string, object>();
folderData.Add("some test", "A brand new folder was created");
LiveConnectClient liveClient = new LiveConnectClient(mySession);
liveClient.PostAsync("me/skydrive", folderData)
.ContinueWith((t) =>
{
if (t.IsFauled)
{
MessageBox.Show("Error creating folder: " + t.Exception.Message);
}
else
{
MessageBox.Show("uploded");
}
}
, TaskScheduler.FromCurrentSynchronizationContext());
}
UPDATED: Code above will work only on WP8, but on WP7 PostAsync is not a method with Task, so to get PostAsync result you need to subscribe to PostCompleted event.

I found problem I have mistake in line:
folderData.Add("some test", "A brand new folder was created");
correct version is:
folderData.Add("name", "some test");

var folderData = new Dictionary<string,object>();
folderData.Add("myfolder ","simple folder ");
client.PostAsync("me/skydrive","{'name': 'myfolder' }");
client.PostCompleted += new EventHandler<LiveOperationCompletedEventArgs> (client_PostCompleted);
void client_PostCompleted(object sender, LiveOperationCompletedEventArgs e)
{
var a = e.RawResult;
}

Related

Trying to get data from firebase but it shows Json error"Could not cast or convert" c#

I am trying to get data from firebase but it shows an error "Could not cast or convert from System.String to System.Collections.Generic.Dictionary`2"
This is my code:
IFirebaseConfig config = new FirebaseConfig()
{
AuthSecret = "Auth",
BasePath = "Path"
};
IFirebaseClient client;
private void Form1_Load(object sender, EventArgs e)
{
try
{
client = new FirebaseClient(config);
if (client != null)
{
MessageBox.Show("OK");
}
}
catch
{
MessageBox.Show("No");
}
LiveCall();
}
async void LiveCall()
{
while (true)
{
await Task.Delay(1000);
FirebaseResponse res = await client.GetAsync(#"GPS/lat");
Dictionary<string, GPS> data = JsonConvert.DeserializeObject<Dictionary<string, GPS>>(res.Body.ToString());
UpdateRTB(data);
}
}
void UpdateRTB(Dictionary<string, GPS> record)
{
label1.Text += record.ElementAt(1).Key + record.ElementAt(1).Value;
}
Can Anybody help me to solve the problem? thanks!

Can't access winforms label after await?

I have a long running method which I made async. I made my button click handler async as well, but when I try to access my label in my button click after the long method is done, it tells me it can't can't access it from another thread. Here is the code:
private void Migrate()
{
for (int i = 2; i <= excelData.GetUpperBound(0); i++)
{
var poco = new ExpandoObject() as IDictionary<string, object>;
foreach (var column in distributionColumnExcelHeaderMappings)
{
if (column.ColumnIndex > 0)
{
var value = excelData[i,column.ColumnIndex]?.ToString();
poco.Add(column.DistributionColumnName.Replace(" ", ""), value);
}
}
pocos.Add(poco);
}
migrationRepository.BulkInsert(insertToTable, "Id", pocos);
}
private async void btnMigrate_Click(object sender, EventArgs e)
{
Task task = new Task(()=> Migrate());
task.Start();
lblStatus.Text = "Migrating data....";
await task;
lblStatus.Text = "Migration Complete";
}
When the button is clicked, I see the status Migrating data..... When that is complete, it throws an error on lblStatus.Text = "Migration Complete". I thought after await, it goes back to the UI thread?
I cleared out most of the code and it still throws the same error. This is a VSTO excel add-in. Could that be part of the problem?
private void Migrate()
{
}
private async void btnMigrate(object sender, EventArgs e)
{
Task.Run(()=>Migrate());
lblStatus.Text = "Done"; //still get error here
}
Try and update your code to the following:
Instead of creating your task and then starting it manually, update it to just await on Task.Run:
private async void btnMigrate_Click(object sender, EventArgs e)
{
lblStatus.Text = "Migrating data....";
await Task.Run(()=> Migrate());
lblStatus.Text = "Migration Complete";
}
Edit:
You can use a helper method that will check to see if the label needs to be invoked before updating.
private async void btnMigrate_Click(object sender, EventArgs e)
{
SetLabelText(lblStatus, "Migrating data....");
await Task.Run(()=> Migrate());
SetLabelText(lblStatus, "Migration complete.");
}
private void SetLabelText(Label label, string text)
{
if (label.InvokeRequired)
{
label.BeginInvoke((MethodInvoker) delegate() {label.Text = text;});
}
else
{
label.Text = text;
}
}

load contacts from telegram to C#

I am using language programming C# and I am making a program that is using Telegram API called TLSharp and I wanna know can I load My contacts from Telegram So I used these codes that I found in stackoverflow but something went wrong
private async void button2_Click(object sender, EventArgs e)
{
try
{
client = new TelegramClient(****, "****");
await client.ConnectAsync();
button2.BackColor = Color.Green;
button1.Enabled = true;
button2.Text = "Connected";
}
catch
{
button2.BackColor = Color.Red;
button1.Enabled = false;
button2.Text = "Disconnected";
}
}
string hash;
private async void button1_Click(object sender, EventArgs e)
{
try
{
hash = await client.SendCodeRequestAsync(textBox1.Text);
panel1.Hide();
panel2.Show();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message,"Error");
}
}
private async void button3_Click(object sender, EventArgs e)
{
try
{
var result = await client.GetContactsAsync();
//find recipient in contacts
var user = result.users.lists.Where(x=>x.GetType()==typeof(TLUser)).Cast<TLUser>();
foreach (var item in user.username)
{
listBox1.Items.Add(item);
}
}
catch
{
}
}
But the problem is here , the list-box shows something which isn't Username and I don't know what is it and the list-box shall show my username of my contacts; It shows only my username like this #username

InnerException = {"Exception from HRESULT: 0x8004231C"}

I am developing an application in Windows Phone Silverlight 8.1 in which I am trying to set a route between current location and a hardcoded destination using this link the code is:
private async void GetCoordinates()
{
Geolocator myGeolocator = new Geolocator();
myGeolocator.DesiredAccuracyInMeters = 50;
Geoposition myposition = null;
try
{
myposition = await myGeolocator.GetGeopositionAsync(TimeSpan.FromMinutes(1),TimeSpan.FromSeconds(50));
Geocoordinate myGeocoordinate = myposition.Coordinate;
GeoCoordinate myGeoCoordinate = CoordinateConverter.ConvertGeocoordinate(myGeocoordinate);
mycoordinates.Add(new GeoCoordinate(myGeoCoordinate.Latitude, myGeoCoordinate.Longitude));
locationmap.Center = myGeoCoordinate;
locationmap.ZoomLevel = 13;
Mygeocodequery = new GeocodeQuery();
Mygeocodequery.SearchTerm = "Seattle, WA";
Mygeocodequery.GeoCoordinate = new GeoCoordinate(myGeoCoordinate.Latitude, myGeoCoordinate.Longitude);
Mygeocodequery.QueryCompleted += Mygeocodequery_Querycompleted;
Mygeocodequery.QueryAsync();
}
catch (UnauthorizedAccessException)
{
MessageBox.Show("Location is disabled in phone settings or capabilities are not checked.");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Mygeocodequery_Querycompleted(object sender, QueryCompletedEventArgs<IList<MapLocation>> e)
{
if(e.Error==null)
{
MyQuery = new RouteQuery();
mycoordinates.Add(e.Result[0].GeoCoordinate);
MyQuery.Waypoints = mycoordinates;
MyQuery.QueryCompleted += MyQuery_QueryCompleted;
MyQuery.QueryAsync();
Mygeocodequery.Dispose();
}
}
private void MyQuery_QueryCompleted(object sender, QueryCompletedEventArgs<Route> e)
{
try
{
**Route MyRoute = e.Result;**
MapRoute MyMapRoute = new MapRoute(MyRoute);
locationmap.AddRoute(MyMapRoute);
MyQuery.Dispose();
}
catch (TargetInvocationException ex)
{
MessageBox.Show(ex.InnerException.Message);
}
}
It sometimes works fine but sometimes I am getting this inner exception as TargetInvocationException Exception from HRESULT: 0x8004231C
On the line highlighted please let me know what should I do?
The Problem is only because I had skipped the step to write the following code in load event of map control
private void locationmap_Loaded(object sender, RoutedEventArgs e)
{
Microsoft.Phone.Maps.MapsSettings.ApplicationContext.ApplicationId = "yourapplicationID";
Microsoft.Phone.Maps.MapsSettings.ApplicationContext.AuthenticationToken = "yourauthenticationtoken";
}
if this code is added it works fine for all the locations.

C# upload file by webclient

I uploaded a file by webclient. But upload success and response link file. But when I go to the file manager I don't have the file in my account. Why ?
This is my code.
private void btnUpload_Click(object sender, EventArgs e)
{
WebClient wc = new WebClient();
wc.Headers.Add("OurSecurityHeader", "encryptedvalue");
wc.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0");
wc.Headers.Add(HttpRequestHeader.Cookie, "__cfduid=d56b9e4ca0801822e9231936c70518ec91397746478931; __utma=259844498.1111893290.1397796877.1397796877.1397802609.2; __utmc=259844498; __utmz=259844498.1397796877.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); login=KimJanParkC1; xfss=g7prlsjg15zl57h4; __zlcid=%7B%22mID%22%3A%22OPdgp3o75YUWIg%22%2C%22sid%22%3A%22140417.91047.473AFH5T%22%7D; __utmb=259844498.17.10.1397802609; sthumb=500x500; _mcnc=1");
wc.UploadProgressChanged += new UploadProgressChangedEventHandler(wc_UploadProgressChanged);
wc.UploadFileCompleted += new UploadFileCompletedEventHandler(UploadFileCallback);
wc.UploadFileAsync(new Uri("http://img102.imagetwist.com/cgi-bin/upload.cgi?upload_id="), "POST", txtPath.Text);
}
void wc_UploadFileCompleted(object sender, UploadFileCompletedEventArgs e)
{
// GET DOWNLOAD LINK
MessageBox.Show("Upload Finished");
}
void wc_UploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
{
pgbStatus.Maximum = (int)e.TotalBytesToSend;
pgbStatus.Value = (int)e.BytesSent;
label6.Text = ((int)e.BytesSent * 100) / (int)e.TotalBytesToSend + "%";
}
public void UploadFileCallback(Object sender, UploadFileCompletedEventArgs e)
{
// GET RESPOND DOWNLOAD LINK
HtmlAgilityPack.HtmlDocument hd = new HtmlAgilityPack.HtmlDocument();
hd.LoadHtml(System.Text.Encoding.UTF8.GetString(e.Result));
txtResult.Text = hd.DocumentNode.InnerHtml;
}
In windows side:
private void uploadButton_Click(object sender, EventArgs e)
{
var openFileDialog = new OpenFileDialog();
var dialogResult = openFileDialog.ShowDialog();
if (dialogResult != DialogResult.OK) return;
Upload(openFileDialog.FileName);
}
private void Upload(string fileName)
{
var client = new WebClient();
client.UploadFileCompleted += new UploadFileCompletedEventHandler(Completed);
client.UploadProgressChanged += new UploadProgressChangedEventHandler(ProgressChanged);
var uri = new Uri("http://www.yoursite.com/UploadFile/");
try
{
client.Headers.Add("fileName", System.IO.Path.GetFileName(fileName));
var data = System.IO.File.ReadAllBytes(fileName);
client.UploadDataAsync(uri, data);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Completed(object sender, UploadFileCompletedEventArgs e)
{
MessageBox.Show(e.Error?.Message ?? "Uploaded Successfully!");
}
private void ProgressChanged(object sender, UploadProgressChangedEventArgs e)
{
progressBar.Value = e.ProgressPercentage;
}
In server side you should use WebApi:
[HttpPost]
public async Task<object> UploadFile()
{
var file = await Request.Content.ReadAsByteArrayAsync();
var fileName = Request.Headers.GetValues("fileName").FirstOrDefault();
var filePath = "/upload/files/";
try
{
File.WriteAllBytes(HttpContext.Current.Server.MapPath(filePath) + fileName , file);
}
catch (Exception ex)
{
// ignored
}
return null;
}

Categories