Click here to Skip to main content
11,568,522 members (49,267 online)
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C# WebForms Python .NET4
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: http://www.abc.com/abcd/login.do
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'''
  '''ref: http://pythonfilter.com/blog/changing-or-spoofing-your-user-agent-python.html'''
 
  req_headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; U; ru; rv:5.0.1.6) 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 = opener.open(request, data)
  code = response.code
  headers = response.headers
  html = response.read()
  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('http://www.abc.com/abcd/login.do', 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:5.0.1.6) 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:5.0.1.6) 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);
 
dataStream.Close();
 
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(), 
UrlEncode(parameters)));
 

the line
string.Format("{0}?{1}", cRow["LINK"].ToString(),
UrlEncode(parameters))
gives me a 'COMPLETE' url sting:
http://www.abc.com/abcd/login.do?action=doLoginSubmit&userId=abcd&password=1234

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.


EDIT:

For some reason, doing a webbrowser.Navigate to the COMPLETE URL 'twice' seems to cause a successful login!
Posted 28-Dec-12 5:52am
Edited 1-Jan-13 18:35pm
v2
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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:
http://en.wikipedia.org/wiki/IronPython[^],
http://ironpython.net/[^].

Happy New Year!

—SA
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

# Bronto API WSDL BRONTO_WSDL = 'https://api.bronto.com/v4?wsdl' # Start up basic logging logging.basicConfig() # Replace the placeholder text with a valid # API token TOKEN = "ADD API TOKEN HERE" # Login using the token to obtain a session ID bApi = Client( BRONTO_WSDL ) try: session_id = bApi.service.login(TOKEN) # Just exit if something goes wrong except WebFault, e: print '\nERROR MESSAGE:' print e sys.exit() # Set up the soap headers using the # session_id obtained from login() session_header = bApi.factory.create("sessionHeader") session_header.sessionId = session_id bApi.set_options(soapheaders=session_header)
  Permalink  

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

  Print Answers RSS


Advertise | Privacy | Mobile
Web03 | 2.8.150624.2 | Last Updated 2 Apr 2014
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

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