I'm developing wp 8 application.
In my application I have Facebook share option.Every thing works correctly.
but problem is first time only post on wall option work . if i again click post on wall button post not working. it show me error In alert Box
Error Occurred :The Remote Server returned an error: NotFound
If i delete the already posted msg in fb wall.
Then I click again the post on wall it's work.
If msg is posted in wall then the code return above error msg in alert.
My Code For post on wall Button
private void BtnPostOnWall_Click(object sender, RoutedEventArgs e)
{
FacebookClient.Instance.PostMessageOnWall(TextToPost, new UploadStringCompletedEventHandler(PostMessageOnWallCompleted));
}
void PostMessageOnWallCompleted(object sender, UploadStringCompletedEventArgs e)
{
if (e.Cancelled)
return;
if (e.Error != null)
{
MessageBox.Show("Error Occurred: " + e.Error.Message);
return;
}
System.Diagnostics.Debug.WriteLine(e.Result);
string result = e.Result;
byte[] data = Encoding.UTF8.GetBytes(result);
MemoryStream memStream = new MemoryStream(data);
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(ResponseData));
ResponseData responseData = (ResponseData)serializer.ReadObject(memStream);
if (responseData.id != null && !responseData.id.Equals(""))
{
// Shared successfully
MessageBox.Show("Message Posted!");
}
else if (responseData.error != null && responseData.error.code == 190)
{
if (responseData.error.error_subcode == 463)
{
// need to get new token
FacebookClient.Instance.ExchangeAccessToken(new UploadStringCompletedEventHandler(ExchangeAccessTokenCompleted));
}
else
{
// need to clear the Access Token
FacebookClient.Instance.AccessToken = "";
SetLoggedInState(false);
}
}
else
{
// Error
}
}
How to resolve this error...
Related
The following works ok:
using Plugin.FilePicker;
using Plugin.FilePicker.Abstractions;
using Xamarin.CommunityToolkit.Core;`
...
private void btnPlaySource_Clicked(object sender, EventArgs e)
{
FileData fileData = await CrossFilePicker.Current.PickFile();
if (fileData == null)
return; // user canceled file picking
mediaElement.Source = MediaSource.FromFile(fileData.FilePath);
mediaElement.Play();
}
But these lines throw an exception with a delay of ~7 secs (it's not immediately thrown):
private void btnPlayURL_Clicked(object sender, EventArgs e)
{
//http://docs.google.com/uc?export=open&id=XXXXXXXXXXXXXXXXXX
var fileURL = GetGDriveFileURL();
mediaElement.Source = MediaSource.FromUri(fileURL);
mediaElement.Play();
}
Java.Lang.RuntimeException: 'setDataSource failed: status = 0x80000000'
What could be the reason of the exception? The URL is 100% working, I tested it on a WPF application's MediaElement and it played fine. I also build the application for Android with Android API level 29 SDK.
<Grid><xct:MediaElement x:Name="mediaElement" Grid.Row="0" AutoPlay="False" ShowsPlaybackControls="True"/>
Some of the problems were solved using Xamarin.Essentials.FilePicker. It allows picking audio from Google Drive if it's connected to the Android device. Although, the problem with URL still remains.
//var fileResult = await App.PickAndShow(Xamarin.Essentials.PickOptions.Default);
//if (fileResult == null) return false;
public static async Task<string> PickAndShow(Xamarin.Essentials.PickOptions options)
{
try {
Xamarin.Essentials.FileResult result =
await Xamarin.Essentials.FilePicker.PickAsync(options);
if (result != null) {
// For certain types of files, like ".mp3"
if (result.FileName.EndsWith("mp3", StringComparison.OrdinalIgnoreCase) ||
result.FileName.EndsWith("wav", StringComparison.OrdinalIgnoreCase))
{
// for debug purposes
bool exists = File.Exists(result.FullPath);
}
}
return result.FullPath;
} catch (Exception ex) {
// The user canceled or something went wrong
}
return null;
}
Im trying to read receiving email from gmail and I did it.
If emails receive one by one it works perfectly.But if emails receive three or four at the same time.I miss at least two of them.
I hope describe my issue properly.
Here is my code for reading;
private void StartReceiving()
{
Task.Run(() =>
{
using (ImapClient client = new ImapClient("imap.gmail.com", 993, txtEmail.Text, txtSifre.Text, AuthMethod.Login, true))
{
if (client.Supports("IDLE") == false)
{
MessageBox.Show("server crash");
return;
}
client.NewMessage += new EventHandler<IdleMessageEventArgs>(OnNewMessage);
while (true) ;
}
});
}
static void OnNewMessage(object sender,IdleMessageEventArgs e)
{
//MessageBox.Show("mesaj geldi");
MailMessage m = e.Client.GetMessage(e.MessageUID, FetchOptions.Normal);
f.Invoke((MethodInvoker)delegate
{
f.txtGelen.AppendText("Body: " + m.Body + "\n");
});
}
What should I do ? Im kinda newbie at this,i have to read at least 4 emails at same time.
I never worked with gmail, but I had a similar problem when I was reading a TCP/IP log file, and it kept sending messages while I was processing.
The way I resolved it was to use a LIST of strings, and then process it in a background worker. Changing a string in place could be an issue in a race situation.
This is cut and pasted out of my code, and modified without checking my syntax, but it goes something like this:
private System.ComponentModel.BackgroundWorker backgroundWorkerReadMail;
private List<string> messagesToBeRead = null;
/****************************************************************
* readPassedMessage(string str)
* Puts message in queue, and calls background worker
****************************************************************/
private void readPassedMessage(string str)
{
string stringToRead = str;
if (messagesToBeRead == null) messagesToBeRead = new List<string>();
messagesToBeRead.Add(stringToRead);
if (backgroundWorkerReadMail != null && backgroundWorkerReadMail.IsBusy == false)
{
backgroundWorkerReadMail.RunWorkerAsync();
}
else if (backgroundWorkerReadMail == null)
{
// need to create it
}
}
private void backgroundWorkerReadMail_DoWork(object passedObj, DoWorkEventArgs e)
{
if (messagesToBeRead == null || messagesToBeRead.Count == 0) return;
if (backgroundWorkerReadMail.CancellationPending)
{
messagesToBeRead.Clear();
e.Cancel = true;
}
else
{
bool messagesLeftToRead = true;
while (messagesLeftToRead)
{
string curString = messagesToBeRead[0];
// < ADD CODE HERE TO DO WHATEVER YOU WANT WITH YOUR MESSAGE > //
messagesToBeRead.RemoveAt(0);
if (messagesToBeRead.Count == 0 || backgroundWorkerVoiceAssist.CancellationPending)
break;
} // while (messagesLeftToRead) end brace
}
}
I am working with the Windows Forms app. It connects to the Flikr website via free API key, searches images that I provide through the textBox and displays the names of the files that correspond to the keyword in the imagesListBox. When I click on the image name in the imagesListBox the image is displayed inside of the pictureBox. Now I am trying to save an image from the pictureBox and I get this error: "non-invocable member PictureBox.ImageLocation cannot be used like a method". Is there another method similar to ImageLocation which I can use to retrieve the image url address? Here is my code for the button which is supposed to save the image:
private void btnSave_Click(object sender, EventArgs e)
{
//method of saving image
try
{
if (pictureBox.Image != null)
{
//5
string filePath = PictureBox.ImageLocation();
string fileName = Path.GetFileName(filePath);
File.Copy(pictureBox.Text, Path.Combine(#"C:\", Path.GetFileName(pictureBox.Text)), true);
MessageBox.Show("The image has been saved to C drive.");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
Searching and uploading images from Flikr:
private async void searchButton_Click(object sender, EventArgs e)
{
// if flickrTask already running, prompt user
if (flickrTask?.Status != TaskStatus.RanToCompletion)
{
var result = MessageBox.Show(
"Cancel the current Flickr search?",
"Are you sure?", MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
// determine whether user wants to cancel prior search
if (result == DialogResult.No)
{
return;
}
else
{
flickrClient.CancelPendingRequests(); // cancel search
}
}
// Flickr's web service URL for searches
var flickrURL = "https://api.flickr.com/services/rest/?method=" +
$"flickr.photos.search&api_key={KEY}&" +
$"tags={inputTextBox.Text.Replace(" ", ",")}" +
"&tag_mode=all&per_page=500&privacy_filter=1";
imagesListBox.DataSource = null; // remove prior data source
imagesListBox.Items.Clear(); // clear imagesListBox
pictureBox.Image = null; // clear pictureBox
imagesListBox.Items.Add("Loading..."); // display Loading...
// invoke Flickr web service to search Flick with user's tags
flickrTask = flickrClient.GetStringAsync(flickrURL);
// await flickrTask then parse results with XDocument and LINQ
XDocument flickrXML = XDocument.Parse(await flickrTask);
// gather information on all photos
var flickrPhotos =
from photo in flickrXML.Descendants("photo")
let id = photo.Attribute("id").Value
let title = photo.Attribute("title").Value
let secret = photo.Attribute("secret").Value
let server = photo.Attribute("server").Value
let farm = photo.Attribute("farm").Value
select new FlickrResult
{
Title = title,
URL = $"https://farm{farm}.staticflickr.com/" +
$"{server}/{id}_{secret}.jpg"
};
// clear imagesListBox
imagesListBox.Items.Clear();
// set ListBox properties only if results were found
if (flickrPhotos.Any())
{
imagesListBox.DataSource = flickrPhotos.ToList();
imagesListBox.DisplayMember = "Title";
}
else // no matches were found
{
imagesListBox.Items.Add("No matches");
}
}
Since it has been asked how I get images inside the pictureBox:
// display selected image
private async void imagesListBox_SelectedIndexChanged(
object sender, EventArgs e)
{
if (imagesListBox.SelectedItem != null)
{
string selectedURL = ((FlickrResult)imagesListBox.SelectedItem).URL;
// use HttpClient to get selected image's bytes asynchronously
byte[] imageBytes = await flickrClient.GetByteArrayAsync(selectedURL);
// display downloaded image in pictureBox
using (var memoryStream = new MemoryStream(imageBytes))
{
pictureBox.Image = Image.FromStream(memoryStream);
}
}
}
Change the line to the following. ImageLocation is a property, not a method.
string filePath = pictureBox.ImageLocation;
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.
I am using Live api to download SkyDrive files.
My code has a download click event which triggers the OnDownloadedCompleted function.
OnDownloadedCompleted function copies the file to "filename".
and calls the DefaultLaunch(), which takes in the "filename" and tries to launch it by the default program in windows phone 8.
When i execute this code (The file downloaded is a OneNote file) OneNote opens and says that the file can't be open.
Can anyone please help me validate this code?
Thanks a lot!
private void btnDownload_Click(object sender, RoutedEventArgs e)
{
if (App.Current.LiveSession == null)
{
infoTextBlock.Text = "You must sign in first.";
}
else
{
LiveConnectClient client = new LiveConnectClient(App.Current.LiveSession);
client.DownloadCompleted += new EventHandler<LiveDownloadCompletedEventArgs>(OnDownloadCompleted);
client.DownloadAsync("file_id");
}
}
The code for OnDownloadCompleted is
void OnDownloadCompleted(object sender, LiveDownloadCompletedEventArgs e)
{
if (e.Result != null)
{
var filestream = File.Create(#"filename");
e.Result.Seek(0, SeekOrigin.Begin);
e.Result.CopyTo(filestream);
filestream.Close();
DefaultLaunch();
e.Result.Close();
}
else
{
infoTextBlock.Text = "Error downloading image: " + e.Error.ToString();
}
}
The code for Default launch function is
async void DefaultLaunch()
{
try
{
string imageFile = #"File.one";
var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(imageFile);
var success = await Windows.System.Launcher.LaunchFileAsync(file);
if (success)
{}
else
{}
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace);
Console.WriteLine(e.ToString());
}
}
try this tutorial.. http://msdn.microsoft.com/en-us/live/ff519582.aspx.. it is given there how to use live sdk in windows 8 platform