curl is not showing captcha - c#

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.

Related

BizTalk SMTP send mail with attachments (no orchestration, custom send pipeline component)

I hope someone can help me out with this since when I drop a JSON test file in my rcv-folder the only result is that in the BizTalk console (in 'Running instances'), the message only states 'Queued (Awaiting processing)'. I am not sure where my issue is in the code.
I am supposed to receive a JSON which will contain some info and possibly multiple attachments (in Base64 format) and then send the mail out (with attachments in correct format, i.e. PDF, txt, xls) to a certain email-address. One of the requirements is to not use an orchestration. But I am stuck and have no idea what I am doing anymore. What makes this question different from others is that I have no orchestration in my solution. Everything will be processed in a custom send pipeline component.
The sendpipeline (in encode stage) does contain my custom component and also the MIME/SMIME encoder. I am using the SMTP-adapter.
I have created the custom pipeline component with a wizard and my initial plan was in the form below:
Receive the file (in JSON-format. It will be transformed into XML for further processing). This will all be taken care of in my rcv-pipeline and this step already works for me.
Pick out all the necessary variables from XML needed to send in the e-mail. These variables are the ones I want to show in the E-mail text. Not sure how to explain it better.
Pick out all the attachments in base64, loop through them, convert to 'regular files' and then attach them to the mail (with correct filenames, extension etc.)
The XML looks like below:
ArchiveobjectsListErrands
- ArchiveobjectErrand
* UUID (Here are the variables I need to show in the E-mail. The plain text, so to say)
- ArchiveobjectListPaper
- Attachments
* Name
* Extension
* Size
* Base64String (Base64 string which will be needed to be fetched (in GetAttachments) and then processed in (ProcessAttachments))
The code I have is below:
public Microsoft.BizTalk.Message.Interop.IBaseMessage Execute(Microsoft.BizTalk.Component.Interop.IPipelineContext pContext, Microsoft.BizTalk.Message.Interop.IBaseMessage pInMsg)
{
// 1) Read file with XPathNavigator (https://learn.microsoft.com/en-us/dotnet/standard/data/xml/extract-xml-data-using-xpathnavigator)
XPathNavigator nav = ReadXmlFromMsgBox(pInMsg);
var outMsg = pContext.GetMessageFactory().CreateMessage();
outMsg.Context = PipelineUtil.CloneMessageContext(pInMsg.Context);
// 2) Pick out the necessary vars that the registrator requires
GetRegistratorProperties(nav, pContext, outMsg);
// 3) Read attachments
var attachments = GetAttachments(pInMsg, nav);
// 4) Processa attachments
ProcessAttachments(pContext, outMsg, attachments);
// 5) Send message along for further processing in the send pipeline
return outMsg;
}
private void GetRegistratorProperties(XPathNavigator _nav, IPipelineContext _pContext, IBaseMessage _msg)
{
var bodyPart = _pContext.GetMessageFactory().CreateMessagePart();
bodyPart.ContentType = "text/application";
bodyPart.PartProperties.Write("EmailBodyText", "http://schemas.microsoft.com/BizTalk/2003/smtp-properties", "EmailBodyText.");
bodyPart.PartProperties.Write("Subject", "http://schemas.microsoft.com/BizTalk/2003/smtp-properties", "Registratorsubject - Create errand");
_msg.AddPart("Body", bodyPart, true); // True for body but false for attachments
}
private void ProcessAttachments(IPipelineContext _pContext, IBaseMessage _msg, IList<Attachment> _attachments)
{
var msgPart = _pContext.GetMessageFactory().CreateMessagePart();
//outMsg.Context = PipelineUtil.CloneMessageContext(_msg.Context);
int i = 0;
foreach (var item in _attachments)
{
msgPart.PartProperties.Write("FileName", "http://schemas.microsoft.com/BizTalk/2003/mime-properties", item.filnamn+item.extension);
msgPart.PartProperties.Write("ContentDescription", "http://schemas.microsoft.com/BizTalk/2003/mime-properties", item.contentType);
msgPart.Data = new MemoryStream(BytesFromBase64String(item.base64));
//bodyPart.Charset = "utf-8";
msgPart.ContentType = item.contentType;
//_pInMsg.AddPart("Attachment part " + i.ToString(), bodyPart, false);
_msg.AddPart("Attachment part " + i.ToString(), msgPart, false);
i++;
}
}
private IList<Attachment> GetAttachments(IBaseMessage pInMsg, XPathNavigator _nav)
{
XPathNodeIterator iterator = _nav.Select("Path to attachments in xml");
IList<Attachment> myList = new List<Attachment>();
while (iterator.MoveNext())
{
XPathNavigator node = iterator.Current;
Attachment atttachments = new Attachment();
atttachments.filenamne = node.SelectSingleNode("Name").Value;
atttachments.extension = node.SelectSingleNode("Extension").Value;
atttachments.contentType = node.SelectSingleNode("Mimetype").Value;
atttachments.base64 = node.SelectSingleNode("Base64String").Value;
myList.Add(atttachments);
}
return myList;
}
private XPathNavigator ReadXmlFromMsgBox(IBaseMessage pInMsg)
{
// Using XPathNavigator to avoid creating a XMLDoc in memory
Stream originalMessage = pInMsg.BodyPart.GetOriginalDataStream();
XPathNavigator _navigator = new XPathDocument(originalMessage).CreateNavigator();
return _navigator;
}
[Serializable]
private class FileStreamFactory : IStreamFactory
{
byte[] _data;
public FileStreamFactory(byte[] data)
{
_data = data;
}
public Stream CreateStream()
{
return new MemoryStream(_data);
}
}
private static byte[] BytesFromBase64String(string msg)
{
return Convert.FromBase64String(msg);
}
#endregion
}
I can show some example file of the XML if deemed necessary. I avoided it due to brevity and also since it is quite large.
I would greatly appreciate if anyone could help out with how the code is supposed to look to achieve what is needed, a mail with some text and attachments named correctly regarding filename and extension.
Body text and Attachments are just different segments in a MIME encoded email, usually a plain text one is the first one.
If it has a status of 'Queued (Awaiting processing)', then it sounds like either
the host instance that is expecting to process it is not in a running state. Fix: Start the host instance.
the send port is not in a Started sate. Fix: set the send port to Started
or the send port has a service window set on it. Fix: disable the service window.

Receive files sent by loopj httpclient in asp.net server

I want to save a picture from an Android device to my ASP.NET server.
The code in android is this:
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("name", fileName);
try {
File imageFile = new File(mPath);
params.put("image", imageFile);
} catch(FileNotFoundException e) {
Log.e("onStart", "fail to get imagefile");
}
client.get(url, params, new AsyncHttpResponseHandler() {
...
}
However, i cant seem to get my file on my server using C#.
Can someone please give me an example how to get my file?
I feel so stupid, it turns out i had to change one word.
from this:
client.get(url, params, new AsyncHttpResponseHandler() { ...
to:
client.post(getApplicationContext(), url, params, new AsyncHttpResponseHandler() { ...

How to get the facebook signed request in c#

I'm new to Facebook apps. I'm trying to create an MVC 4 application with Facebook Application as my Project Template.
I'm trying to catch the page id on which the page tab is created and I've got it somehow.
My problem here is when someone visits my app, I want to know the page id through which they are viewing the page tab. I've searched a lot where I got to know that I've to use FacebookSignedRequest for this. But this class is not available to me.
Thanks in advance for any help.
If you are simply trying to parse the signed_request parameter from Facebook, you can do so using the following C# code.
This code also verifies the hash using your own app_secret param, to ensure the signed_request originated from Facebook.
public static string DecodeSignedRequest(string signed_request)
{
try
{
if (signed_request.Contains("."))
{
string[] split = signed_request.Split('.');
string signatureRaw = FixBase64String(split[0]);
string dataRaw = FixBase64String(split[1]);
// the decoded signature
byte[] signature = Convert.FromBase64String(signatureRaw);
byte[] dataBuffer = Convert.FromBase64String(dataRaw);
// JSON object
string data = Encoding.UTF8.GetString(dataBuffer);
byte[] appSecretBytes = Encoding.UTF8.GetBytes(app_secret);
System.Security.Cryptography.HMAC hmac = new System.Security.Cryptography.HMACSHA256(appSecretBytes);
byte[] expectedHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(split[1]));
if (expectedHash.SequenceEqual(signature))
{
return data;
}
}
}
catch
{
// error
}
return "";
}
private static string FixBase64String(string str)
{
while (str.Length % 4 != 0)
{
str = str.PadRight(str.Length + 1, '=');
}
return str.Replace("-", "+").Replace("_", "/");
}
All I had to do was create a Facebook Client object and call the ParseSignedRequest method with the app secret.
var fb = new FacebookClient();
dynamic signedRequest = fb.ParseSignedRequest(appSecret, Request.Form["signed_request"]);
This returns a Json object which we have to parse using JObject.Parse

C# equivalent to Java SSL-socket-connection

Hey guys I'm trying to write an AXL-client (SOAP) for the Cisco Unified Communications Manager. For that purpose I need to establish an ssl-connection to the AXL-service. Unfortunatly I dont know much about all that ssl-stuff.
However I was able to find a working Java-example, that does, what I want. The problem is, i need that in C#.NET. So I'm hoping, that someone could "translate" the following Java-code in a C#-version. But it has to do exactly the same, espacially the authentication and certificate-stuff.
Here is the code:
String sAXLSOAPRequest = "...";
byte[] bArray = null; // buffer for reading response from
Socket socket = null; // socket to AXL server
OutputStream out = null; // output stream to server
InputStream in = null; // input stream from server
X509TrustManager xtm = new MyTrustManager();
TrustManager[] mytm = { xtm };
SSLContext ctx = SSLContext.getInstance("SSL");
ctx.init(null, mytm, null);
SSLSocketFactory sslFact = (SSLSocketFactory) ctx.getSocketFactory();
socket = (SSLSocket) sslFact.createSocket("192.168.1.100", Integer.parseInt("8443"));
in = socket.getInputStream();
// send the request to the server
// read the response from the server
StringBuffer sb = new StringBuffer(2048);
bArray = new byte[2048];
int ch = 0;
int sum = 0;
out = socket.getOutputStream();
out.write(sAXLSOAPRequest.getBytes());
while ((ch = in.read(bArray)) != -1) {
sum += ch;
sb.append(new String(bArray, 0, ch));
}
socket.close();
// output the response to the standard output
System.out.println(sb.toString());
and this is the MyTrustManager-Class:
public class MyTrustManager implements X509TrustManager {
MyTrustManager() {
// create/load keystore
}
public void checkClientTrusted(X509Certificate chain[], String authType)
throws CertificateException {
}
public void checkServerTrusted(X509Certificate chain[], String authType)
throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
Any help would be appreciated.
Thanks
edit: sorry i should have mentioned: youre right i can generate a proxy-class, but sadly its not working properly. cisco did a really bad job with that (not to mention the really bad documentation). the proxy class throws some xml-errors when parsing some responses. so i have to do it manually for that cases...
i'll worry about the certificate security later
Have you tried consuming the web service the "proper" way? Add a SOAP web service reference to your C# project in Visual Studio, gets the stubs etc? That's the easiest way of doing it from C#. You can just specify a https protocol in the URL when you add the reference.

C#-Facebook-SDK WP7, the principles of how Facebook works?

Apologies if this is somewhere, but I'm struggling to find the details I need for wp7.
I have created the application on Facebook as required, and am retrieving an access token. The following code posts to Facebook but I cannot get a response, nor can I work out how to monitor the response?
public bool fbUpload(string accessToken, Picture pic)
{
try
{
Stream s = null;
s = PicturesLoader.LoadFileFromStorage(pic.Url);
//Sets the byte array to the correct number of bytes
byte[] imageData = new byte[s.Length];
s.Read(imageData, 0, System.Convert.ToInt32(s.Length));
FacebookApp app = new FacebookApp();
IDictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("access_token", accessToken);
parameters.Add("message", "TEST - WP7 application [upload pic and comment on wall...]");
var mediaObject = new FacebookMediaObject { FileName = pic.Name, ContentType = "image/jpeg" };
mediaObject.SetValue(imageData);
parameters["source"] = mediaObject;
FacebookAsyncResult postResult;
FacebookAsyncCallback fbCB = new FacebookAsyncCallback();
app.PostAsync(parameters, fbCB);
return true;
}
catch (InvalidCastException ex)
{
return false;
}
}
The other question I have, is how do you allow users to allow access based upon their own Facebook account. I want to store a user's account details so they only have to set up the account details once, and then they can use my phone app with having to sign in?
You can handle the post result something like this:
FacebookAsyncCallback callBack = new FacebookAsyncCallback(postResult);
fbApp.PostAsync(parameters, args, callBack);
private void postResult(FacebookAsyncResult asyncResult)
{
// Do something with asyncResult here;
}
Regarding the second question, you must ask for permissions to access this data.
You usually do that in the FacebookOAuthClient.GetLoginUrl(<appId>, null, <permissions>) method call.
Once that's done, you can store the files you have permissions to locally in your app.

Categories