Click here to Skip to main content
14,643,428 members

Python to .net C# conversion

princektd asked:

Open original thread
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!
Tags: C#, Python, .NET (.NET4), WebForms


When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100