I have this code:
public void WriteNewTopic(string subject, string message)
{
_webRequest = (HttpWebRequest)WebRequest.Create(this.Url + "newthread.php?do=newthread&f=" + AppsId);
_webRequest.Headers.Add("Cookie", this.Cookie);
_webRequest.UserAgent = "Mozilla/5.0 (Windows NT 5.1; rv:2.0) Gecko/20100101 Firefox/4.0";
_webRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
_webRequest.ContentType = "application/x-www-form-urlencoded";
_webRequest.Referer = this.Url + "viewforum.php?f=" + this.AppsId;
_webRequest.Headers.Add("Accept-Charset", "ISO-8859-2,utf-8;q=0.7,*;q=0.7");
_webRequest.Headers.Add("Accept-Encoding", "gzip, deflate");
_webRequest.Headers.Add("Accept-Language", "pl,en-us;q=0.7,en;q=0.3");
_webRequest.Method = "POST";
_webRequest.CookieContainer = _cookieContainer;
_webRequest.AllowAutoRedirect = false;
string values =
"do=postthread&f=" + AppsId +
"&securitytoken=1301767251-1a5636806411d07afb5cfde72c4f0978a1cf4415" +
"&wysiwyg=0&subject=" + subject +
"&message=" + message;
_webRequest.ContentLength = values.Length;
byte[] buffer = new byte[256];
ASCIIEncoding ascii = new ASCIIEncoding();
buffer = ascii.GetBytes(values);
using (Stream stream = _webRequest.GetRequestStream())
{
stream.Write(buffer, 0, buffer.Length);
}
HttpWebResponse c;
try
{
c = (HttpWebResponse)_webRequest.GetResponse();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
if (c.Cookies.Count != 0)
{
this.Cookie = string.Empty;
foreach (Cookie cook in c.Cookies)
{
cook.HttpOnly = true;
Cookie = Cookie + cook + "; ";
}
}
}
But there's a security token in site source, but I can't get this token.
Help me!
I dont know how to create new thread in vBulletin forum, but I think it would be more easier if you will use watin automation library
Related
I have a class whose main function is:
public void SendSMS(SendInfo info, WebBrowser browser)
{
browser.Width = 300;
browser.Height = 300;
browser.ScriptErrorsSuppressed = true;
browser.DocumentCompleted += Browser_Navigated;
this.number = info.number;
this.message = info.template;
if (info.proxy != null) { WebRequest.DefaultWebProxy = info.proxy; }
debugCode = Application.OpenForms["Form1"].Controls["tabControl1"].Controls["tabPage1"].Controls["DebugCode"] as TextBox;
debugImage = Application.OpenForms["Form1"].Controls["tabControl1"].Controls["tabPage1"].Controls["pictureBox1"] as PictureBox;
MessageBox.Show("I'am start send, template: " + info.template);
browser.Navigate("My secret url :)");
}
After browser navigated,invoke second main function:
private void SendPostRequest(string number, string message, string captcha_key, string captcha_result)
{
MessageBox.Show("Number: " + number + " Message: " + message + " key: " + captcha_key +" result: " + captcha_result);
string postData = "Body=" + message + "&Captcha=" + captcha_result + "&CheckboxTransliterate=false&Phone=" + number.Substring(3, number.Length - 3) + "&PhoneCode=" + number.Substring(0, 3) + "&WidgetId=" + captcha_key + "&_captcha_key=" + captcha_key + "&clearJson=true";
byte[] bytes = Encoding.UTF8.GetBytes(postData);
HttpWebRequest sendRequest = WebRequest.Create("My secret url :") as HttpWebRequest;
sendRequest.Credentials = CredentialCache.DefaultCredentials;
sendRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36";
sendRequest.Method = "POST";
sendRequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
sendRequest.Referer = "My secret url :";
sendRequest.Headers.Add("Pragma", "no-cache");
sendRequest.Headers.Add("Cache-Control", "no-cache");
sendRequest.Accept = "application/json, text/plain, *";
sendRequest.Headers.Add(HttpRequestHeader.Cookie, cookies);
sendRequest.ContentLength = bytes.Length;
sendRequest.CookieContainer = new CookieContainer();
sendRequest.CookieContainer = GetUriCookieContainer(sendRequest.RequestUri);
using (Stream dataStream = sendRequest.GetRequestStream())
{dataStream.Write(bytes, 0, bytes.Length);}
onSendCompleted(sendRequest.GetResponse().GetResponseStream());
}
private void onSendCompleted(Stream SendResponsetStream)
{
string status = new StreamReader(SendResponsetStream).ReadToEnd();
SendResponsetStream.Close();
ArgumentsClass args = new ArgumentsClass();
args.ResponseMessage = status;
args.ResponseNumber = number;
OnSmsSendend(this, args);
}
How can I run it's void(Send SMS with its subfunctions) in other threads?
I need these functions(Send SMS with its subfunctions) to be run in parallel.
Thanks!
P.S. Sorry for my English :)
Since your SendSMS does not necessarily need to return anything and the parameters would come from a collection (an array or something similar), you can do something like this-
var tasks = new List<Task>();
foreach (var input in inputs)
{
tasks.Add(Task.Factory.StartNew(() => objjectInstance.SendSMS(input[info], input[browser]))); //objectInstance is class object instance
}
Here inputs is a collection of the input parameters of type- SendInfo and WebBrowser. You have to create the input parameter collection accordingly as per need.
I don't understand what may cause this error
I am using the below function with about 1000 concurrent connections
Each connection uses a different webproxy
After a while like 15 minutes working, the established TCP connection count starts to stack and internet connectivity becomes lost
When i do not use any webproxy, i do not encounter any error
I am using below function to retrieve active TCP connections count
var properties = IPGlobalProperties.GetIPGlobalProperties();
I don't see any leak in my function
So i need your help to solve this annoying problem
c# .net 4.6.2
Here the statuses of active TCP Connections when this problem occurs
public static cs_HttpFetchResults func_fetch_Page(
string srUrl, int irTimeOut = 60,
string srRequestUserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0",
string srProxy = null, int irCustomEncoding = 0, bool blAutoDecode = true, bool blKeepAlive = true)
{
cs_HttpFetchResults mycs_HttpFetchResults = new cs_HttpFetchResults();
mycs_HttpFetchResults.srFetchingFinalURL = srUrl;
HttpWebRequest request = null;
WebResponse response = null;
try
{
request = (HttpWebRequest)WebRequest.Create(srUrl);
request.CookieContainer = new System.Net.CookieContainer();
if (srProxy != null)
{
string srProxyHost = srProxy.Split(':')[0];
int irProxyPort = Int32.Parse(srProxy.Split(':')[1]);
WebProxy my_awesomeproxy = new WebProxy(srProxyHost, irProxyPort);
my_awesomeproxy.Credentials = new NetworkCredential();
request.Proxy = my_awesomeproxy;
}
else
{
request.Proxy = null;
}
request.ContinueTimeout = irTimeOut * 1000;
request.ReadWriteTimeout = irTimeOut * 1000;
request.Timeout = irTimeOut * 1000;
request.UserAgent = srRequestUserAgent;
request.KeepAlive = blKeepAlive;
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
WebHeaderCollection myWebHeaderCollection = request.Headers;
myWebHeaderCollection.Add("Accept-Language", "en-gb,en;q=0.5");
myWebHeaderCollection.Add("Accept-Encoding", "gzip, deflate");
request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
using (response = request.GetResponse())
{
using (Stream strumien = response.GetResponseStream())
{
Encoding myEncoding = Encoding.UTF8;
string srContentType = "";
if (response.ContentType != null)
{
srContentType = response.ContentType;
if (srContentType.Contains(";"))
{
srContentType = srContentType.Split(';')[1];
}
srContentType = srContentType.Replace("charset=", "");
srContentType = func_Process_Html_Input(srContentType);
}
try
{
myEncoding = Encoding.GetEncoding(srContentType);
}
catch
{
myEncoding = irCustomEncoding == 0 ? Encoding.UTF8 : Encoding.GetEncoding(irCustomEncoding);
}
using (StreamReader sr = new StreamReader(strumien, myEncoding))
{
mycs_HttpFetchResults.srFetchBody = sr.ReadToEnd();
if (blAutoDecode == true)
{
mycs_HttpFetchResults.srFetchBody = HttpUtility.HtmlDecode(mycs_HttpFetchResults.srFetchBody);
}
mycs_HttpFetchResults.srFetchingFinalURL = Return_Absolute_Url(response.ResponseUri.AbsoluteUri.ToString(), response.ResponseUri.AbsoluteUri.ToString());
mycs_HttpFetchResults.blResultSuccess = true;
}
}
}
if (request != null)
request.Abort();
request = null;
}
catch (Exception E)
{
if (E.Message.ToString().Contains("(404)"))
mycs_HttpFetchResults.bl404 = true;
csLogger.logCrawlingErrors("crawling failed url: " + srUrl, E);
}
finally
{
if (request != null)
request.Abort();
request = null;
if (response != null)
response.Close();
response = null;
}
return mycs_HttpFetchResults;
}
I have a digital IP camera. It is preset to use set static IP address, and I have asked the manufacturer whether they have an API I can call to set it to DHCP.
They replied:
PUT /Network/interfaces/1/ipAddress HTTP/1.1
Authorization: Basic YWRtaW46MTIzNDU=
Content-Type:text/xml
Content-Length:387
<IPAddress version="1.0" xmlns="http://www.hikvision.com/ver10/XMLSchema">
<ipVersion>v4</ipVersion>
<addressingType>dynamic</addressingType>
<ipAddress>172.2.62.49</ipAddress>
<subnetMask>255.255.255.0</subnetMask>
<DefaultGateway>
<ipAddress>172.2.62.1</ipAddress>
</DefaultGateway>
<PrimaryDNS>
<ipAddress>0.0.0.0</ipAddress>
</PrimaryDNS>
</IPAddress>
So, I translated that to:
private void button1_Click(object sender, EventArgs e)
{
try
{
HttpWebRequest req = null;
WebResponse rsp = null;
string uri = "http://192.0.0.64/Network/interfaces/1/ipAddress";
req =(HttpWebRequest) WebRequest.Create(uri);
req.UseDefaultCredentials = true;
//req.Credentials = new NetworkCredential("admin", "12345"); //I have tried using this as well as these are the default admin/pw supplied
req.Method = "PUT";
req.ProtocolVersion = HttpVersion.Version11;
req.ContentLength = 387;
string _cred = string.Format("{0} {1}", "Basic", "YWRtaW46MTIzNDU=");
req.Headers[HttpRequestHeader.Authorization] = _cred;
req.ContentType = "text/xml";
StreamWriter writer = new StreamWriter(req.GetRequestStream());
writer.WriteLine(GetDHCPPost());
writer.Close();
rsp = req.GetResponse();
}
catch (Exception ex)
{
//errors here >> cannot connect to server
}
}
private string GetDHCPPost()
{
StringBuilder sb = new StringBuilder();
sb.Append("<IPAddress version=\"1.0\" xmlns=\"http://www.hikvision.com/ver10/XMLSchema\">");
sb.Append("<ipVersion>v4</ipVersion>");
sb.Append("<addressingType>dynamic</addressingType>");
sb.Append("<ipAddress>172.2.62.49</ipAddress>");
sb.Append("<subnetMask>255.255.255.0</subnetMask>");
sb.Append("<DefaultGateway>");
sb.Append("<ipAddress>172.2.62.1</ipAddress>");
sb.Append("</DefaultGateway>");
sb.Append("<PrimaryDNS>");
sb.Append("<ipAddress>0.0.0.0</ipAddress>");
sb.Append("</PrimaryDNS>");
sb.Append("</IPAddress> ");
return sb.ToString();
}
But does not work. Am I making an obvious error?
Try this.
If you're using admin/12345.
I made this to write the temperature overlay to my hikvision camera.
Your xml code is definitely correct. I'm not 100% you would need to declare the port number, I know I always had too.
SendToHikVision("admin", "12345", "192.0.0.64", "*The Port You're Using");
void SendToHikVision(string UserName, string Password, string IP, string Port)
{
try
{
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://" + IP + ":" + Port + "/Network/interfaces/1/");
wr.Accept = "*/*";
wr.Method = "PUT";
wr.ReadWriteTimeout = 5000;
wr.Credentials = new NetworkCredential(UserName, Password);
byte[] pBytes = GetDHCPPost();
wr.ContentLength = pBytes.Length;
using (Stream DS = wr.GetRequestStream())
{
DS.Write(pBytes, 0, pBytes.Length);
DS.Close();
}
wr.BeginGetResponse(r => { var reponse = wr.EndGetResponse(r); }, null);
}
catch { }
}
byte[] GetDHCPPost()
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("<IPAddress version=\"1.0\" xmlns=\"http://www.hikvision.com/ver10/XMLSchema\">");
sb.AppendLine("<ipVersion>v4</ipVersion>");
sb.AppendLine("<addressingType>dynamic</addressingType>");
sb.AppendLine("<ipAddress>172.2.62.49</ipAddress>");
sb.AppendLine("<subnetMask>255.255.255.0</subnetMask>");
sb.AppendLine("<DefaultGateway>");
sb.AppendLine("<ipAddress>172.2.62.1</ipAddress>");
sb.AppendLine("</DefaultGateway>");
sb.AppendLine("<PrimaryDNS>");
sb.AppendLine("<ipAddress>0.0.0.0</ipAddress>");
sb.AppendLine("</PrimaryDNS>");
sb.AppendLine("</IPAddress> ");
return Encoding.ASCII.GetBytes(sb.ToString());
}
I have been trying to figure out why this post method isn't going through. I've been using Fiddler, and have been working on this for hours now. If someone could help that would be great.
private string getemail(string user, string pass)
{
var cookies = new CookieContainer();
var getRequest = (HttpWebRequest)WebRequest.Create("http://account.mojang.com/migrate");
cookies = (getRequest as HttpWebRequest).CookieContainer;
string[] tok = ReadResponse(getRequest).Split(new string[] { "name=\"authenticityToken\" value=\"" }, StringSplitOptions.None);
string[] toke = tok[1].Split('"');
string token = toke[0];
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://account.mojang.com/migrate/check");
request.CookieContainer = cookies;
request.Method = "POST";
request.Headers.Add("Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3");
request.Headers.Add("Accept-Encoding: gzip,deflate,sdch");
request.Headers.Add("Accept-Language: en-US,en;q=0.8");
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31";
request.ContentType = "text/plain";
using (var requestStream = request.GetRequestStream())
{
using (var writer = new StreamWriter(requestStream))
{
writer.Write("authenticityToken=" + token + "&mcusername=" + user + "&password=" + pass);
}
}
using (var responseStream = request.GetResponse().GetResponseStream())
{
using (var reader = new StreamReader(responseStream))
{
var result = reader.ReadToEnd();
return result;
}
}
}
Close your StreamWriter after writing content into request stream.
using (var writer = new StreamWriter(requestStream))
{
writer.Write("authenticityToken=" + token + "&mcusername=" + user + "&password=" + pass);
writer.Close();
}
The problem with this code is that the file, once it is uploaded, is not the correct format. I'm trying to upload a .zip file.
public string HttpPost(string uri, string parameter)
{
WebRequest webRequest = WebRequest.Create(uri);
NetworkCredential credentials = new NetworkCredential("username", "password");
webRequest.Credentials = credentials;
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(parameter);
Stream os = null;
try
{ // send the Post
webRequest.ContentLength = bytes.Length; //Count bytes to send
os = webRequest.GetRequestStream();
os.Write(bytes, 0, bytes.Length); //Send it
}
catch (WebException ex)
{
MessageBox.Show(ex.Message, "HttpPost: Request error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
if (os != null)
{
os.Close();
}
}
try
{ // get the response
WebResponse webResponse = webRequest.GetResponse();
if (webResponse == null)
{ return null; }
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
return sr.ReadToEnd().Trim();
}
catch (WebException ex)
{
MessageBox.Show(ex.Message, "HttpPost: Response error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return null;
}
This example how to upload file in MyBucket
private const string KeyId = "Your KeyId";
private const string AccessKey = "Your AccessKey";
private const string S3Url = "https://s3.amazonaws.com/";
private static void UploadFile()
{
var fileData = File.ReadAllBytes(#"C:\123.zip");
string timeStamp = string.Format("{0:r}", DateTime.UtcNow);
string stringToConvert = "PUT\n" + //Http verb
"\n" + //content-md5
"application/octet-stream\n" + //content-type
"\n" + //date
"x-amz-acl:public-read"+"\n" + //date
"x-amz-date:" + timeStamp + "\n" + //optionall
"/MyBucket/123.zip"; //resource
var ae = new UTF8Encoding();
var signature = new HMACSHA1 {Key = ae.GetBytes(AccessKey)};
var bytes = ae.GetBytes(stringToConvert);
var moreBytes = signature.ComputeHash(bytes);
var encodedCanonical = Convert.ToBase64String(moreBytes);
var url = "https://MyBucket.s3.amazonaws.com/123.zip";
var request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "PUT";
request.Headers["x-amz-date"] = timeStamp;
request.Headers["x-amz-acl"] = "public-read";
request.ContentType = "application/octet-stream";
request.ContentLength = fileData.Length;
request.Headers["Authorization"] = "AWS " + KeyId + ":" + encodedCanonical;
var requestStream = request.GetRequestStream();
requestStream.Write(fileData, 0, fileData.Length);
requestStream.Close();
using (var response = request.GetResponse() as HttpWebResponse)
{
var reader = new StreamReader(response.GetResponseStream());
var data = reader.ReadToEnd();
}
}
Take a look on Amazon S3 REST API