4

I am doing a project in which I have to make a windows application that can Take a URL in textbox from user. Now when the user press the Proceed button, the application should open that URl in a webbrowser control and fill the form on that page containing userID & password textboxes and submit it via the login button on that web page. Now my application should show the next page in that webbrowser control to the user.

I can open the url in the application's webbrowser control through my C# Code, but I can't figure it out that how to find the userID & pasword textboxes on that web page that is currently opened in the webbrowser control of my application, how to fill them, how to find the login button & how to click it through my C# Code.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Somi
  • 53
  • 1
  • 2
  • 6
  • 3
    You don't need to fill any textboxes, you just need to simulate pressing a login button and provide proper data. When user presses a login button, usually it means he's making a POST request to the server. Try to log in yourself and capture the request you are making (there are various ways to do it, either through browsers' web developing tools or standalone applications), take a look what is inside that request and simulate it in your application. – S_F Jul 08 '13 at 14:38
  • I am so sorry that I was not very much clear in my question. Actually the user is no pressing any login button. He is just opening my windows app & provide a url. Now my app have to open that url, fill the text boxes and pree the login button. I hope that the question is clear now. – Somi Jul 08 '13 at 14:47
  • 1
    I meant a user of the website under that URL, not a user of your application. What I wrote still stands - test how that particular website sends data to its server first, then write a code which will send the same data through your application. The problem starts if you want to use your program for several different websites as it's pretty much guaranteed each of them will require a different code. Even if you managed to put up a proper POST data just by processing the HTML code, there's still request headers to consider, cookies etc. Sorry I can't be of more help but it's a broad topic. – S_F Jul 08 '13 at 14:54

4 Answers4

7

For this you will have to look into the page source of the 3rd party site and find the id of the username, password textbox and submit button. (If you provide a link I would check it for you). Then use this code:

//add a reference to Microsoft.mshtml in solution explorer
using mshtml;

private SHDocVw.WebBrowser_V1 Web_V1;

Form1_Load()
{
    Web_V1 = (SHDocVw.WebBrowser_V1)webBrowser1.ActiveXInstance;
}

webBrowser1_Document_Complete()
{
if (webBrowser1.ReadyState == WebBrowserReadyState.Complete)
    {
        if (webBrowser1.Url.ToString() == "YourLoginSite.Com")
        {
            try
            {
                HTMLDocument pass = new HTMLDocument();
                pass = (HTMLDocument)Web_V1.Document;
                HTMLInputElement passBox = (HTMLInputElement)pass.all.item("PassIDThatyoufoundinsource", 0);
                passBox.value = "YourPassword";
                HTMLDocument log = new HTMLDocument();
                log = (HTMLDocument)Web_V1.Document;
                HTMLInputElement logBox = (HTMLInputElement)log.all.item("loginidfrompagesource", 0);
                logBox.value = "yourlogin";
                HTMLInputElement submit = (HTMLInputElement)pass.all.item("SubmitButtonIDFromPageSource", 0);
                submit.click();
            }
            catch { }
        }
    }
}
Patrick Geyer
  • 1,515
  • 13
  • 30
5

I would use Selenium as opposed to the WebBrowser control.

It has an excellent C# library, and this kind of thing is the main reason it was developed.

Arran
  • 24,648
  • 6
  • 68
  • 78
1

You don't have to simulate filling in the username/password fields nor clicking on the login button. You need to simulate the browser rather than the user.

Read the login page html and parse it to find the ids of the username and password fields. The username can be obtained by looking for tags with name set as "username", "user", "login", etc. The password will usually be an tag with type="password". Javascript based popup panels for login would involve parsing the js.

Then follow the example code shown here, How do you programmatically fill in a form and 'POST' a web page?

Community
  • 1
  • 1
Nemo
  • 3,285
  • 1
  • 28
  • 22
1

The important thing here is that you're simulating a browser POST event. Don't worry about text boxes and other visual form elements, your goal is to generate a HTTP POST request with the appropriate key-value pairs.

Your first step is to look through the HTML of the page you're pretend to be and figure out the names of the user id and password form elements. So, let's say for example that they're called "txtUsername" and "txtPassword" respectively, then the post arguments that the browser (or user-agent) will be sending up in its POST request will besomething like:

txtUsername=fflintstone&txtPassword=ilikerocks

As a background to this, you might like to do a little research on how HTTP works. But I'll leave that to you.

The other important thing is to figure out what URL it posts this login request to. Normally, this is whatever appears in the address bar of the browser when you log in, but it may be something else. You'll need to check the action attribute of the form element so see where it goes.

It may be useful to download a copy of Fiddler2. Yes, weird name, but it's a great web debugging tool that basically acts as a proxy and captures everything going between the browser and the remote host. Once you figure out how to use it, you can then pull apart each request-response to see what's happening. It'll give you the URL being called, the type of the request (usually GET or POST), the request arguments, and the full text of the response.

Now, you want to build your app. You need to build logic which make the correct HTTP requests, pass in the form arguments, and get back the results. Luckily, the System.Net.HttpWebRequest class will help you do just that.

Let's say the login page is at www.hello.org/login.aspx and it expects you to POST the login arguments. So your code might look something like this (obviously, this is very simplified):

Imports System.IO
Imports System.Net
Imports System.Web
Dim uri As String = "http://www.hello.org/login.aspx"
Dim request As HttpWebRequest = DirectCast(WebRequest.Create(uri), HttpWebRequest)
request.Timeout = 10000 ' 10 seconds
request.UserAgent = "FlintstoneFetcher/1.0" ' or whatever
request.Accept = "text/*"
request.Headers.Add("Accept-Language", "en")
request.Method = "POST"
Dim data As Byte() = New ASCIIEncoding().GetBytes("txtUsername=fflintstone&txtPassword=ilikerocks")
request.ContentType = "application/x-www-form-urlencoded"
request.ContentLength = data.Length
Dim postStream As Stream = request.GetRequestStream()
postStream.Write(data, 0, data.Length)
postStream.Close()
Dim webResponse As HttpWebResponse
webResponse = DirectCast(request.GetResponse(), HttpWebResponse)
Dim streamReader As StreamReader = New StreamReader(webResponse.GetResponseStream(), Encoding.GetEncoding(1252))
Dim response As String = streamReader.ReadToEnd()
streamReader.Close()
webResponse.Close()

The response string now contains the full response text from the remote host, and that host should consider you logged in. You may need to do a little extra work if the remote host is trying to set cookies (you'll need to return those cookies). Alternatively, if it expects you to pass integrated authentication on successive pages, you'll need to add credentials to your successive requests, something like:

request.Credentials = New NetworkCredential(theUsername, thePassword)

That should be enough information to get cracking. I would recommend that you modularise your logic for working with HTTP into a class of its own. I've implemented a complex solution that logs into a certain website, navigates to a pre-determined page, parses the html and looks for a daily file to be downloaded in the "invox" and if it exists then downloads it. I set this up as a batch process which runs each morning, saving someone having to do this manually. Hopefully, my experience will benefit you!

Mark Micallef
  • 2,643
  • 7
  • 28
  • 36