I'm using HttpClient to POST a user created string to a server API and get the result. Previously I used a TextBox to allow the user to enter the string but I wanted pretty colours so I tried to replace the TextBox with a RichEditBox but failed miserably. When using the TextBox everything worked fine but when using the RichEditBox I get an "Access denied" message. I get the text from the RichEditBox with the Document.GetText method. I can get it to work by either inserting a static string in the place where I get the text or in the place where I send the string into a FormUrlEncodedContent. The string is edited before and after adding the text from the RichEditBox, and sent to another method.
TL:DR: Sending a string from a TextBox with a HttpClient using POST works but not when replacing the TextBox with a RichEditBox.
Here's the full error message:
System.UnauthorizedAccessException: 'Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))'
Does anyone have a solution or an explanation to why this is happening?
Edit
Code sample:
private async void RichEditBox_KeyUp(object sender, KeyRoutedEventArgs e)
{
if (e.Key == VirtualKey.Enter)
{
await RunCode(); //The error points to this line
}
}
private async void RunCode()
{
string code = CodeBefore;
foreach (RichEditBox tb in editStack.Children) //If I comment out the foreach loop I don't get any errors
{
if (tb.Tag.ToString() == "input")
{
tb.Document.GetText(Windows.UI.Text.TextGetOptions.None, out string thisLine);
code += thisLine;
}
}
code += CodeAfter;
await RunCSharp(code);
}
private async Task<Code> RunCSharp(string code)
{
Code re = new Code();
using (HttpClient client = new HttpClient())
{
FormUrlEncodedContent content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("LanguageChoiceWrapper", "1"),
new KeyValuePair<string, string>("Program", code), //If I replace code with a string I don't get any errors
new KeyValuePair<string, string>("ShowWarnings", "false")
});
try
{
HttpResponseMessage msg = await client.PostAsync("http://mywebaddress.com/run", content);
re = JsonConvert.DeserializeObject<Code>(await msg.Content.ReadAsStringAsync());
}
catch { }
}
return re;
}
Related
So I'm trying to list the files in my S3 bucket to my winform in visual studio c#
static async Task ListingObjectAsync()
{
try
{
ListObjectsV2Request request = new ListObjectsV2Request
{
BucketName = bucketName
};
ListObjectsV2Response response;
do
{
response = await s3Client.ListObjectsV2Async(request);
foreach (S3Object entry in response.S3Objects)
{
string file = entry.Key;
ListViewItem item = new ListViewItem(file);
listView1.Items.Add(item);
}
} while (response.IsTruncated);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
But it says that "an object reference is required for a non static field"
Any tips on how to list files from S3 bucket to listview, datagrid or other forms?
Thank you!
P.S. I'm new to stack overflow so I'm sorry if my question format is wrong
remove the static from your method declaration:
async Task ListingObjectAsync(){...}
you cannot access instance variables from a static method
I just started using the open-source library called IMAPX to interact with my IMAP mailbox. I am following this article on CodeProject. I can login properly and retrieve the email folders. But the problem is, the article seems to be incomplete which is leaving me in the middle of the road. Firstly the Retrieving Email Folder's part didn't work. I had to do a workaround.Now, I am trying to download the emails of a folder.The article, regarding this issue, has only a few line of code:
private void foldersList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var item = foldersList.SelectedItem as EmailFolder;
if(item != null)
{
// Load the folder for its messages.
loadFolder(item.Title);
}
}
private void loadFolder(string name)
{
ContentFrame.Content = new FolderMessagesPage(name);
}
The article doesn't explain anything about FolderMessagesPage . So, I made a test page named FolderMessagesPage. I literally have no idea what to put in that page. Can anybody please guide me?
Unfortunately now I'm having some problems in accessing the article on Code Project, but if you need to retrieve the emails, you can start with the following sample code which retrieves the emails from the Inbox folder. I think that might work for you as well.
private static readonly ImapClient _client = new ImapX.ImapClient(ServerImapName, ImapPort, ImapProtocol, false);
if (!_client.Connect())
{
throw new Exception("Error on conncting to the Email server.");
}
if (!_client.Login(User, Password))
{
throw new Exception("Impossible to login to the Email server.");
}
public static List<string> GetInboxEmails()
{
var lstInEmails = new List<string>();
// select the inbox folder
Folder inbox = _client.Folders.Inbox;
if (inbox.Exists > 0)
{
var arrMsg = inbox.Search("ALL", ImapX.Enums.MessageFetchMode.Full);
foreach (var msg in arrMsg)
{
var subject = msg.Subject;
var mailBody = msg.Body.HasHtml ? msg.Body.Html : msg.Body.Text;
lstInEmails.Add(string.Concat(subject, " - ", mailBody );
}
}
return lstInEmails;
}
Hope it helps.
Good bytes.
I need all the text in the body for incoming email.
I tried:
var mesage = GetMessage(service, "me", 1);
Console.WriteLine(mesage.Snippet);
public static Message GetMessage(GmailService service, String userId, String messageId)
{
try
{
return service.Users.Messages.Get(userId, messageId).Execute();
}
catch (Exception e)
{
Console.WriteLine("An error occurred: " + e.Message);
}
return null;
}
But I am getting just snippet as shown in the screenshot.
Incoming mail to me:
Result:
Looking at the documentation, Message.Snippet only returns a short part of the message text. You should instead use Message.Raw, or more appropriately, Message.Payload.Body?
var message = GetMessage(service, "me", 1);
Console.WriteLine(message.Raw);
Console.WriteLine(message.Payload.Body.Data);
You should try both out and see what works best for what you're trying to do.
To get message.Raw you need to pass a parameter, as stated in the docs:
Returned in messages.get and drafts.get responses when the format=RAW parameter is supplied.
If none of those things work, you could try iterating over the parts of the message to find your data:
foreach (var part in message.Payload.Parts)
{
byte[] data = Convert.FromBase64String(part.Body.Data);
string decodedString = Encoding.UTF8.GetString(data);
Console.WriteLine(decodedString);
}
Hopefully an easy question for you all but I'm really struggling.
I've only recently started programming and have just had an app certified to the WP7 app store but noticed a bug myself that i would like to fix before making the app public.
Basically I have a search box where the user enters a chemical name and a webservice returns an image and its molecular weight. What i would like to do is cancel the webclient if the user navigates away from the page before the download is completed or if a new search is made before the previous is completed (this currently crashes the app as I believe you can only have one request at a time??)
private void searchCactus()
{
WebClient imgClient = new WebClient();
imgClient.OpenReadCompleted += new OpenReadCompletedEventHandler(imgClient_OpenReadCompleted);
WebClient mwClient = new WebClient();
mwClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(mwClient_DownloadStringCompleted);
if (DeviceNetworkInformation.IsNetworkAvailable == false)
{
MessageBox.Show("No network found, please check network availability and try again");
}
else if (compoundSearchBox.Text.Contains("?"))
{
MessageBox.Show("\"?\" Not Permitted");
return;
}
else if (compoundSearchBox.Text != "")
{
progBar1.IsIndeterminate = true;
string imageuri = "http://cactus.nci.nih.gov/chemical/structure/" + compoundSearchBox.Text + "/image?format=png&width=300&height=300";
string mwURI = "http://cactus.nci.nih.gov/chemical/structure/" + compoundSearchBox.Text + "/mw";
imgClient.OpenReadAsync(new Uri(#imageuri), imgClient);
mwClient.DownloadStringAsync(new Uri(#mwURI), mwClient);
// //lower keyboard
this.Focus();
}
else MessageBox.Show("Enter Search Query");
}
I tried implementing the following button but it does not work
private void buttonCancel_Click(object sender, RoutedEventArgs e)
{
imgClient.CancelAsync();
mwClient.CancelAsync();
}
as "the name 'mwClient' does not exist in the current context"
I would be very grateful if anybody could provide some guidance
Just put the two clients into fields in your class.
I am creating an application for a company that will fill form in windows application and a post request will be sent to the server to sign up the user.
In order to send a POST request i used curl
private void post_data(string url, string data)
{
Curl.GlobalInit((int)CURLinitFlag.CURL_GLOBAL_ALL);
Easy e = new Easy();
Easy.WriteFunction wf = MyWriteFunction;
e.SetOpt(CURLoption.CURLOPT_URL, url);
e.SetOpt(CURLoption.CURLOPT_POSTFIELDS, data);
e.SetOpt(CURLoption.CURLOPT_WRITEFUNCTION, wf);
e.Perform();
e.Cleanup();
}
private int MyWriteFunction(byte[] buf, int size, int nmemb, Object extraData)
{
StreamWriter sw = new StreamWriter(#"curl.txt");
foreach (byte b in buf)
{
sw.Write(((char)b));
}
sw.Flush();
sw.Close();
return buf.Length;
}
And in order to extract the Captcha image path from source code and let the user type the text
private void Get_Captcha_Image(string url)
{
Curl.GlobalInit((int)CURLinitFlag.CURL_GLOBAL_ALL);
Easy e = new Easy();
Easy.WriteFunction wf = MyWriteFunction;
e.SetOpt(CURLoption.CURLOPT_URL, url);
e.SetOpt(CURLoption.CURLOPT_WRITEFUNCTION, wf);
e.Perform();
e.Cleanup();
get_ca_2();
}
private void get_ca_2()
{
Regex r = new Regex(#"(?<=src=('|""))https?://.*?(?=\1)");
foreach (string line in File.ReadAllLines("curl.txt"))
{
Match m = r.Match(line);
if (m.Success)
{
if (m.Value.Contains("http://www.google.com/recaptcha/api/image?c="))
{
pictureBox1.ImageLocation = m.Value;
}
}
}
}
But what i noticed is that
<img width="300" height="57" src="http://www.google.com/recaptcha/api/image?c=03AHJ_VuvnenuZSRbfL_JTQLTYKFYzEFTkYrDgedu0SLyYvTDhsr2hHjQPwYlGJiP3dJRewkIhhdeILAd1_61_aFfU2dclbf8uovme-0gF3nm8Y7-LQVfaDQoI35bo3c35pOnF-xSY3Qfy_lh8TzhSWlMemEnkYnDpZw" alt="reCAPTCHA challenge image" style="display:block;">
For example is not present on the extracted webpage source code using curl
I tired a webbrowser and hide it and i was able to find the captcha image and i was successful on posting data , but i need to figure it on curl
I would investigate whether the website content changes based on your headers. Obviously the headers from curl are going to look very different from those from, say, IE. Try using a browser that lets you fake different user-agent and so on, see if that changes it. It might be as easy as using curl's --user-agent flag.