Click here to Skip to main content
15,605,787 members
Please Sign up or sign in to vote.
1.11/5 (2 votes)
I have a small function written in python. What it does is accept 2 parameters, and uses them to login to a site.

suppose the URL of the site is:
there are 3 parameters: 1) action = doLoginSubmit
(this is a fixed static parameter. does not change)
2) userId = abcd
3) password = 1234
(these 2 are supplied by user)

here is the python code:

def get_url(url, data=None, timeout=60, opener=None):
  '''get_url accepts a URL string and return the server response code, response headers, and contents of the file'''

  req_headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; U; ru; rv: Gecko/20110501 Firefox/5.0.1 Firefox/5.0.1'
request = urllib2.Request(url, headers=req_headers)

  if not opener:
    jar = cookielib.FileCookieJar("cookies")
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(jar))
  response =, data)
  code = response.code
  headers = response.headers
  html =
  return code, headers, html, opener

def site_login():
  login_data = urllib.urlencode({'userId' : abcd, 'password' : 1234, 'action' : 'doLoginSubmit'})

  code, headers, html, cur_opener = get_url('', data=login_data, opener=cur_opener)

  if debug: print html

i am trying to make a C# equivalent.
here is my code:

Dictionary<string, string> parameters = new Dictionary<string, string> 
	{ "action", "doLoginSubmit"},
	{ "userId", uRow["USERNAME"].ToString() },
	{ "password", uRow["PASSWORD"].ToString() }
//WebClient client = new WebClient();
//client.Headers.Set("UserAgent", "Mozilla/5.0 (Windows NT 6.1; U; ru; rv: Gecko/20110501 Firefox/5.0.1 Firefox/5.0.1");

//Stream dataStream = client.OpenWrite(string.Format("{0}?", cRow["LINK"].ToString()), "POST");

//string result = client.UploadString(string.Format("{0}?",cRow["LINK"].ToString()), "POST" , UrlEncode(parameters));

WebRequest request = WebRequest.Create(string.Format("{0}?{1}", cRow["LINK"].ToString(), UrlEncode(parameters)));

request.Method = "POST";

((HttpWebRequest)request).UserAgent = "Mozilla/5.0 (Windows NT 6.1; U; ru; rv: Gecko/20110501 Firefox/5.0.1 Firefox/5.0.1";

postDataBytes = Encoding.UTF8.GetBytes(UrlEncode(parameters));

request.ContentType = "application/x-www-form-urlencoded";

request.ContentLength = postDataBytes.Length;

Stream dataStream = request.GetRequestStream();
							dataStream.Write(postDataBytes, 0, postDataBytes.Length);


WebResponse response = request.GetResponse();

dataStream = response.GetResponseStream();

StreamReader reader = new StreamReader(dataStream);

string responseFromServer = System.Web.HttpUtility.UrlDecode(reader.ReadToEnd());

//webBrowser.Url = new Uri(string.Format("{0}?{1}", cRow["LINK"].ToString(), 

the line
string.Format("{0}?{1}", cRow["LINK"].ToString(),

gives me a 'COMPLETE' url sting:

now copying this URL string into Firefox address bar and press enter and i can successfully login to the site. Firefox displays the page after successful login and i have further confirmed that the login is in fact successful.

So, i know at least this much portion of my code is right.

What i want to do next is to 'run' this URL without a browser or webcontrol or UI, or somehow successfully submit the credentials to the site and perform a successful login without having to click additional buttons. I mean, the login process itself will have no visual indicators. Only, after the this function completes, if successful, popup a message-box saying 'success' else a message 'failed'.

As can be seen from the commented out lines,
i have tried webclient-openwrite, uploadstring, uploaddata
also webrequest/webresponse to the site url with the parameters passed properly. i have also tried a direct webcontrol navigate to the 'COMPLETE' URL string but it does not login successfully.

the line
string responseFromServer = System.Web.HttpUtility.UrlDecode(reader.ReadToEnd());

tells me if login is successful or not, and i have confirmed that it is not successful.
Please help me out in getting a successful login.
i use C# .Net4.


For some reason, doing a webbrowser.Navigate to the COMPLETE URL 'twice' seems to cause a successful login!
Updated 8-Sep-20 9:44am
Member 1139403 10-Aug-15 14:07pm

1 solution

Instead of translating the code, which is always a pretty boring work, especially if you are "just translating", did you consider using IronPython instead?

Please see:[^],[^].

Happy New Year!

Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900