C# WebBrowser and multithreading - c#

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.

Related

How to Call asmx service without adding service reference in C#.Net

I am working on calling asmx webservice method without adding service reference as asmx doesn't provide wsdl. I can access asmx service from fiddler as well as from postman. It works fine. However when I try to call it from my C# code it throws 403 forbidden exception.
Below is my c# code.
internal class Class3
{
string _soapEnvelope =
#"<soap:Envelope
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xmlns:xsd='http://www.w3.org/2001/XMLSchema'
xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>
<soap:Body></soap:Body></soap:Envelope>";
private string CreateSoapEnvelope()
{
Dictionary<string, string> Params = new Dictionary<string, string>();
Params.Add("aId", "11"); // Add parameterName & Value to dictionary
Params.Add("cId", "22");
Params.Add("lId", "20");
string MethodCall = "<" + "GetSettings" + #" xmlns=""http://tempuri.org/"">";
string StrParameters = string.Empty;
foreach (var param in Params)
{
StrParameters += string.Format("<{0}>{1}</{0}>", param.Key, param.Value);
}
MethodCall = MethodCall + StrParameters + "</" + "GetSettings" + ">";
StringBuilder sb = new StringBuilder(_soapEnvelope);
sb.Insert(sb.ToString().IndexOf("</soap:Body>"), MethodCall);
return sb.ToString();
}
private HttpWebRequest CreateWebRequest()
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("sample.asmx");
webRequest.Headers.Add("SOAPAction", "\"http://tempuri.org/" + "GetSettings" + "\"");
webRequest.Headers.Add("To", "sample.asmx");
webRequest.Credentials = CredentialCache.DefaultCredentials;
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9";
webRequest.Host = "sample.com";
webRequest.Headers.Set(HttpRequestHeader.CacheControl, "max-age=0");
webRequest.Headers.Add("Upgrade-Insecure-Requests: 1");
webRequest.Headers.Add("Origin", "null");
webRequest.Headers.Add("Accept-Encoding", "gzip, deflate");
webRequest.Headers.Add("Accept-Language", "en-US,en;q=0.9,zh-CN;q=0.8,zh-TW;q=0.7,zh;q=0.6");
webRequest.Method = "POST";
return webRequest;
}
public string InvokeService()
{
try
{
WebResponse response = null;
string strResponse = "";
//Create the request
HttpWebRequest req = this.CreateWebRequest();
//write the soap envelope to request stream
using (Stream stm = req.GetRequestStream())
{
using (StreamWriter stmw = new StreamWriter(stm))
{
stmw.Write(this.CreateSoapEnvelope());
}
}
//get the response from the web service
response = req.GetResponse();
Stream str = response.GetResponseStream();
StreamReader sr = new StreamReader(str);
strResponse = sr.ReadToEnd();
return HttpUtility.HtmlDecode(strResponse);
}
catch (Exception ex)
{
return "";
}
}
}
internal class Program
{
static void Main(string[] args)
{
new Class3().InvokeService();
}
}
Tried adding below headers as well but it doesnt make any difference.
webRequest.ContentLength = 600000;
webRequest.ProtocolVersion = HttpVersion.Version11;
webRequest.KeepAlive = false;
webRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36";
I am using VS2022 - Console Application with .Net Framework 4.6.2
Can somebody please help me understand what am I doing wrong here.
after lot of research I got to know that the way I am passing parameters were incorrect. Below is the simple and correct version of doing same. Its working now
string remoteUrl = "service.asmx";
string poststring = "aId=11&cId=22&lId=20";
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(remoteUrl);
httpRequest.Host = "host.com";
httpRequest.Method = "POST";
httpRequest.ContentType = "application/x-www-form-urlencoded";
httpRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.5195.127 Safari/537.36";
// Convert the post string to a byte array
byte[] bytedata = System.Text.Encoding.UTF8.GetBytes(poststring);
httpRequest.ContentLength = bytedata.Length;
// Create the stream
Stream requestStream = httpRequest.GetRequestStream();
requestStream.Write(bytedata, 0, bytedata.Length);
requestStream.Close();
// Get the response from remote server
HttpWebResponse httpWebResponse = (HttpWebResponse)httpRequest.GetResponse();
Stream responseStream = httpWebResponse.GetResponseStream();
System.Text.StringBuilder sb = new System.Text.StringBuilder();
using (StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8))
{
string line;
while ((line = reader.ReadLine()) != null)
{
sb.Append(line);
}
}
string data = sb.ToString();

Login to Gmail using HttpWebRequest no cookie received

I want to Login into my Gmail account and change the password for 100 times to set it to my old password. (as you know google keeps the history of 100 previous passwords, and does not let you to choose one of them).
I'm using HttpWebRequest and HttpWebResponse to solve my problem. and I monitored the request and response in Fiddler.
But when I login to gmail with following code I don't get any cookies.
Where's the problem?!
HttpWebRequest http = WebRequest.Create("https://accounts.google.com/ServiceLoginAuth") as HttpWebRequest;
http.KeepAlive = true;
http.Host = "accounts.google.com";
http.CachePolicy = new HttpRequestCachePolicy(HttpCacheAgeControl.MaxAge, new TimeSpan(0));
http.Referer = "https://accounts.google.com/ServiceLogin?sacu=1&scc=1&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&hl=en&service=mail";
http.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
http.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36";
http.Method = "POST";
http.ContentType = "application/x-www-form-urlencoded";
string postData = "";
postData += "GALX=" + "qpld0kUdZuc";
postData += "&continue=" + "https://mail.google.com/mail/";
postData += "&service=" + "mail";
postData += "&rm=" + "false";
postData += "&itmpl=" + "default";
postData += "&hl=" + "en";
postData += "&scc=" + "1";
postData += "ss=" + "1";
postData += "&sacu=" + "1";
postData += "&_utf8=" + "☃";
postData += "&bgresponse=" + "!A0L90r-qE6ZLyUQ7tYD_B09KGgIAAAAjUgAAAAcqARcN5-HZ6OMO9yMKHpX_wJvfu81b67CyiAbn0EbvzuV9yjTly_ZM6err6uAruVCVnx5qUodg7vq6PIaYWpBtVnOzc2Ean-7ITFxt4SqBb0VAKLOJElXwWmximH-oydxBVH05VR4xLmWF1D00_yiPaXcqibx8ihD8yB1e8bOWrmfdzuVgyOfImv1LTSATv-AMI2W0dfTJlWmmngo4yefWiIEAYHJwixpArol4gDtxBAW81W98CMyXPNxXyu3JV3mCUMSrCh1EPJAX3DpfrU7bmD1O-gO7p8Gw5qU1vAuYt61AaLC9ydABYpvd3oysvccseXDdXJEI9fpeoOV8TNc3QvLYarUPbtjG1gYxgMh_zY72ogVucxCoj8U";
postData += "&pstMsg=" + "1";
postData += "&dnConn=" + "";
postData += "&checkConnection=" + "";
postData += "&checkedDomains=" + "youtube";
postData += "&Email=" + "myEmailAddress";
postData += "&Passwd=" + "my password";
postData += "&signIn=" + "Sign in";
postData += "&PersistentCookie=" + "yes";
byte[] dataBytes = UTF8Encoding.UTF8.GetBytes(postData);
http.ContentLength = dataBytes.Length;
using (Stream postStream = http.GetRequestStream())
{
postStream.Write(dataBytes, 0, dataBytes.Length);
}
HttpWebResponse httpResponse = http.GetResponse() as HttpWebResponse;
// Probably want to inspect the http.Headers here first
http = WebRequest.Create("https://accounts.google.com/b/0/EditPasswd") as HttpWebRequest;
http.CookieContainer = new CookieContainer();
http.CookieContainer.Add(httpResponse.Cookies);
Try setting a cookie container on your request. This answer may help:
C# keep session id over httpwebrequest

save response from web request as mp3 file

When i try to read the stream i get timeout exception. The response i get from the server is the mp3 file and i don't have a clue how to save it as a mp3.
WebClient webClient = new WebClient();
int selectedIndex = listBox2.SelectedIndex;
JObject o = JObject.Parse(result);
string SongID = o["SongID"].ToString();
string SongName = o["SongName"].ToString();
string Year = o["Year"].ToString();
string AlbumName = o["AlbumName"].ToString();
textBox4.Text = SongID + Environment.NewLine + SongName + Environment.NewLine + Year + Environment.NewLine + AlbumName;
string stream = Webpost("{\"header\":{\"token\":\"" +prepToken("getStreamKeyFromSongIDEx", ":chickenFingers:")+"\",\"privacy\":0,\"country\":{\"DMA\":0,\"CC1\":0,\"IPR\":0,\"CC2\":0,\"CC3\":2305843009213694000,\"ID\":190,\"CC4\":0},\"uuid\":\"8E5D1ABD-EE1B-4498-B960-8E46077E8ED4\",\"client\":\"jsqueue\",\"session\":\""+session+"\",\"clientRevision\":\"20130520\"},\"method\":\"getStreamKeyFromSongIDEx\",\"parameters\":{\"mobile\":false,\"prefetch\":false,\"songID\":"+SongID+",\"type\":0,\"country\":{\"DMA\":0,\"CC1\":0,\"IPR\":0,\"CC2\":0,\"CC3\":2305843009213694000,\"ID\":190,\"CC4\":0}}}", "http://*****.com/more.php?getStreamKeyFromSongIDEx", "POST", "text/plain");
JObject ss = JObject.Parse(stream);
string streamkey = ss["result"]["streamKey"].ToString();
string ip = ss["result"]["ip"].ToString();
textBox4.Text += Environment.NewLine+ "downloiad url: " + ip + Environment.NewLine + "stream key: " + streamkey;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://" + ip + "/stream.php");
request.Method = "POST";
string postData = "streamKey="+ streamkey;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentLength = postData.Length;
request.Host = ip;
request.Accept = "*/*";
request.Headers.Add("Origin", string.Format("http://*********.com"));
request.Headers.Add("Accept-Language", string.Format("sv-SE,sv;q=0.8,en-US;q=0.6,en;q=0.4"));
request.Headers.Add("Accept-Encoding", string.Format("gzip,deflate,sdch"));
request.Headers.Add("Cookie", string.Format("ismobile=no; PHPSESSID="+ session + "__utma=111479378.517776767.1385046829.1385170025.1385750338.12; __utmb=111479378.14.9.1385751143490; __utmc=111479378; __utmz=111479378.1385157436.6.2.utmcsr=nettech.wikia.com|utmccn=(referral)|utmcmd=referral|utmcct=/wiki/*****_Internal_API"));
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36";
textBox4.Text += Environment.NewLine + "headers: " + Environment.NewLine + request.Headers;
textBox4.Text += Environment.NewLine + "StreamKey:" + byteArray;
Stream respStream = request.GetRequestStream();
you can try something like this
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("mp3 url");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Get the stream associated with the response.
Stream receiveStream = response.GetResponseStream();
byte[] buffer = new byte[32768];
using (FileStream fileStream = File.Create("yourfullnamepath.mp3"))
{
while (true)
{
int read = receiveStream.Read(buffer, 0, buffer.Length);
if (read <= 0)
break;
fileStream.Write(buffer, 0, read);
}
}

Error 403 with email checking program POST C#

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();
}

How to create new threads using c# on vBulletin forum?

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

Categories