Htmlunit, bad encoding when submit post - htmlunit

Good day!
Do send a message to the forum.
When sending my data break
added to the header charset, it did not help
What could be the problem?
WebClient webClient = new WebClient(BrowserVersion.CHROME);
page = webClient.getPage(urlPage);
HtmlForm formEditPost = page.getFormByName("postform");
HtmlTextInput subjectInput = formEditPost.getInputByName("subject");
subjectInput.setText("заголовок");
HtmlTextArea messageElement = formEditPost.getTextAreaByName("message");
messageElement.setText("сообщение");
HtmlSubmitInput sendMessage = formEditPost.getInputByName("post");
page = sendMessage.click();

Related

How do I send a base64 encoded PDF file?

I want my bot to send a PDF file to the user. I have the PDF as a base64 string and tried to send it through an attachment:
Attachment attachment1 = new Attachment();
attachment1.Name = "name.pdf";
attachment1.ContentType = "application/pdf";
attachment1.ContentUrl = "data:application/pdf;base64," + base64String;
var m = context.MakeMessage();
m.Attachments.Add(attachment1);
m.Text = "File";
await context.PostAsync(m);
Within the emulator, it just doesn't work but in the channels Telegram and Facebook (which I need), the bot just outputs an error...
Has someone already succeed in it?
Note: Using an HTTP address works fine, but I need to use the base64 string
As this method in botframework call sendDocument method of Telegram, and this method in its document property get http url or a file_id, so you can't pass base64String to this method as a valid document type.
You can follow the valid type of the document passing into the telegram in this link (also, see the following image).
The pdf file must be embedded resource. Hope it help.
if (this.channelid == "telegram")
{
var url = string.Format("https://api.telegram.org/bot{0}/sendDocument", Settings.tokentelegram);
Assembly _assembly;
Stream file;
using (var form = new MultipartFormDataContent())
{
form.Add(new StringContent(this.chat_id, Encoding.UTF8), "chat_id");
_assembly = Assembly.GetExecutingAssembly();
file = _assembly.GetManifestResourceStream("Namespace.FolderResourses.name.pdf");
form.Add(new StreamContent(file), "document", "name.pdf");
using (var client = new HttpClient())
{
await client.PostAsync(url, form);
}
}
}

Paypal:IPN Listener not receiving IPN messages

I have a website with online transaction using paypal as payment option. Checkout and the shopping cart calculations on paypal side are working, but i'm not receiving any IPN messages from paypal sandbox. after writing the log I found out that parameter formdata is null. Even checked with the IPN history and it shows the status of IPN message as retrying... IPN notification url has also been set.
Below is the listener code.
[Route("IPN")]
public IHttpActionResult IPN(FormDataCollection formData)
{
var formVals = new Dictionary<string, string>();
formVals.Add("cmd", "_notify-validate");
string response = GetPayPalResponse(formVals, formData);
if (response.ToUpper().Trim() == "VERIFIED")
{
//entry into database
}
else
{
return InternalServerError();
}
return InternalServerError();
}
string GetPayPalResponse(Dictionary<string, string> formVals, FormDataCollection formData)
{
string paypalUrl = GetPayPalURL();
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(paypalUrl);
// Set values for the request back
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
Encoding encoding = Encoding.UTF8;
StringBuilder sb = new StringBuilder();
foreach (var entry in formData.ToList())
{
sb.AppendFormat("{0}={1}&", entry.Key, encoding.GetString(encoding.GetBytes(entry.Value)));
}
string strRequest = sb.ToString();
strRequest += "cmd=_notify-validate";
req.ContentLength = strRequest.Length;
//Send the request to PayPal and get the response
StreamWriter streamOut = new StreamWriter(req.GetRequestStream());
streamOut.Write(strRequest);
streamOut.Close();
StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());
string strResponse = streamIn.ReadToEnd();
streamIn.Close();
return strResponse;
}
This was working before, but no idea what had stopped it.
Being new to paypal payment gateway, any help would be highly appreciated.
There is a certain problem with paypal since yesterday. I hope it is a remporary issue and it will be fixed asap. I have problems with sandbox myself, but it has happened before as well.
I am also having problems with Sandbox mode... can anyone else confirm this? I am using .NET SDK and adaptive payments...
EDIT: all working again today ;)

HtmlUnit Session Management

I'm trying to login to Facebook page using HtmlUnit and view its HTML content. I'm trying to fill up the login credentials through HtmlUnit but I don't see the session being carried when the submit button is clicked.
Couldnt find much content on htmlunit session management classes. I have also attached the code that I'm currently using to attempt this problem. Any help appreciated!
WebClient webClient = new WebClient();
HtmlPage page1 = webClient.getPage("https://www.facebook.com");
List<HtmlForm> listF = page1.getForms();
HtmlForm form = null;
for(int i=0; i<listF.size(); i++)
{
if(listF.get(i).getId().equals("login_form"))
{
form = listF.get(i);
}
}
HtmlTextInput uName = form.getInputByName("email");
HtmlPasswordInput passWord = form.getInputByName("pass");
HtmlSubmitInput button = form.getInputByValue("Log In");
uName.setValueAttribute(FACEBOOK_UNAME);
passWord.setValueAttribute(FACEBOOK_PASS);
HtmlPage page2 = button.click();
Found the answer. Just enabled cookies before starting to get webpages. It works.
Added the below piece of code
WebClient webClient = new WebClient();
CookieManager cookieMan = new CookieManager();
cookieMan = webClient.getCookieManager();
cookieMan.setCookiesEnabled(true);
Another advice is if you are trying to restore HTTP session in HtmlUnit, instead of using webClient.getCookieManager().addCookie(cookie);, use this instead :
webClient.addCookie("cookieName=cookieValue", URL, null);

wp7 - twitter photo upload

We are trying to upload image to Twitter via silverlight code in WP7. We are able to post the message but not the image.
We tried all including download of their library but not getting the hint.
In following link,
https://dev.twitter.com/docs/api/1/post/statuses/update_with_media
there is one point which we are not able to set.
"Unlike POST statuses/update, this method expects raw multipart data. Your POST request's Content-Type should be set to multipart/form-data with the media[] parameter "
I am not getting it how to put it.
Can anyone please guide me or provide sample for image upload?
If your photo is called LoadedPhoto, you could create a memory stream from it
MemoryStream ms = new MemoryStream();
LoadedPhoto.SaveJpeg(ms, LoadedPhoto.PixelWidth, LoadedPhoto.PixelHeight, 0, 100);
Create OAuthCredentials object according to the authentication details you have acquired
var credentials = new OAuthCredentials
{
Type = OAuthType.ProtectedResource,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
ConsumerKey = Common.TwitterSettings.ConsumerKey,
ConsumerSecret = Common.TwitterSettings.ConsumerKeySecret,
Token = file.AccessToken,
TokenSecret = file.AccessTokenSecret,
Version = "1.0"
};
Create a RestClient and a RestRequest
var restClient = new RestClient
{
Authority = "https://upload.twitter.com"
};
var restRequest = new RestRequest
{
Credentials = credentials,
Path = "/1/statuses/update_with_media.xml",
Method = Hammock.Web.WebMethod.Post
};
Set the stream position to 0
ms.Position = 0;
Add fields to RestRequest
restRequest.AddField("status", message);
restRequest.AddFile("media[]", "ScreenShot.png", ms, "image/jpeg");
And then begin request
restClient.BeginRequest(restRequest, callback);
callback is a callback method for the request.
Taken from my blog post, see there for more details if you're interested.

WebClient NotFound error but working with HttpWebRequest/Response

In my WinPhone app I'm accessing a REST service.
At the beginnings I was using this code:
WebClient wc = new WebClient();
wc.Credentials = credentials;
wc.Headers["App-Key"] = appKey;
wc.DownloadStringCompleted +=
(o, args) => MessageBox.Show(args.Error == null ? "OK" : "Error");
wc.DownloadStringAsync(uri);
but it suddenly stopped working returning me a "The remote server returned an error: NotFound" error. After a google session and some clicks in the control panel, I didn't get it to work.
I decided to try this other way:
HttpWebRequest request = HttpWebRequest.CreateHttp(uri);
request.Credentials = credentials;
request.Headers["App-Key"] = appKey;
request.BeginGetResponse(asResult =>
{
var response = request.EndGetResponse(asResult) as HttpWebResponse;
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseString = reader.ReadToEnd();
Dispatcher.BeginInvoke(
() => MessageBox.Show(response.StatusCode.ToString()));
}, null);
and it works.
I also tried to run the first snipped pointing the URI to google's home page and it works (I had to remove the credentials, of course).
Can anyone explain what's going on?
UPDATE
I managed to get it working by replacing the
wc.Credentials = new NetworkCredentials(username, password);
with
wc.Headers["Authorization"] = "Basic someBase64encodedString";
but i still wonder what happened and which are the differences between the first and the second line.
PS: the test URI is: https://api.pingdom.com/api/2.0/checks but you will need an app-key from them.
When using the Credentials property, the HttpWebRequest implementation will wait the challenge response from server before to send the 'Authorization' header value.
But this can be an issue in some cases, so you have to force Basic authentication by providing directly the Authorization header.
Example when using a REST Client library like Spring.Rest :
RestTemplate template = new RestTemplate("http://example.com");
template.RequestInterceptors.Add(new BasicSigningRequestInterceptor("login", "password"));
string result = template.GetForObject<string>(uri);

Resources