1

I'm using a WebBrowser control to automate management of a web page. When I start my WPF application, it shows the webpage ant lets me login. Then my application starts to do some automated tasks by going to a page, filling a form and submitting (it’s a POST-form). It submits the same form ~100 times with different values.

Right now my code is as follows:

void webBrowser1_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
    var doc = (HTMLDocument) webBrowser1.Document;
    var form = doc.getElementById("theForm");

    SetValueOfFormInput(doc, "id", Foo.ID);
    SetValueOfFormInput(doc, "item1", Foo.Item1);
    SetValueOfFormInput(doc, "item2", Foo.Item2);
    form.all.item("submit").click();
}

private static void SetValueOfFormInput(HTMLDocument doc, string name, string value)
{
    var item = doc.all.item(name);
    item.setAttribute("value", value);
}

Can I do this on a better way and can I do it in a MVVM way?

And no, I can't modify the the webpage to do the management easier :-(

Edit: Ideally, I would be able to do this without having to use the WebBrowser control. The program logon to the website and performs all tasks without having to modify the forms in the html pages

Mamta D
  • 6,310
  • 3
  • 27
  • 41
magol
  • 6,135
  • 17
  • 65
  • 120
  • What do you mean by MVVM way? Such that you have some class that represents id, item1, item2 and some process to automatically set those values on the form? – Mike Jun 16 '11 at 21:12
  • So that I don't have to do a lot of work in code behinde. – magol Jun 16 '11 at 21:15

1 Answers1

0

Why not using the WebClient or WebRequest classes? For the webclient, you can use the UploadValues method which will do exactly what you want (http://msdn.microsoft.com/en-us/library/9w7b4fz7.aspx) and you can also simply addapt the class to use cookies so your login will be "permanent" (http://stackoverflow.com/questions/1777221/c-using-cookiecontainer-with-webclient-class)

If you like to do it even more model driven, i would use the WebRequest (has allready a cookiecontainer) and have some class with the needed data. This one would derive from a class, which can serialize all needed properties into a simple string you would post to the server - AFAIK it's same like the getter-parameters (param1=val1&param2=val2&...) so basically:

class Data : Postable { public string Param1{get;set;} public string Param2{get;set;} ...}
class Postable 
{ 
    public override string ToString() 
    { 
        StringBuilder ret = new StringBuilder();
        foreach(Property p in GetType().GetProperties())
        {
            ret.Append("{0}={1}&", p.Name, p.<GetValue>);
        }
        return ret.ToString();
    } 
}
peter
  • 14,348
  • 9
  • 62
  • 96