Zbone
Zbone

Reputation: 507

facebook desktop app C#

I am trying to build a desktop app to use facebook api and get data from friends. Anyways I am stuck in the log in stage. I have used some advice and made the log in to facebook with WebBrowser. It works great. I am stuck at trying to make it give me status = Failed or success

I tried doing it like this at the end of the button_1 method

if (!w.DocumentText.Contains(@"<div class=""linkWrap noCount"">Messages</div>"))
    {
        w.Navigate(@"http://www.facebook.com/login.php");
        MessageBox.Show("Login error. Wrong username or password!");
    }

    else
    {
       MessageBox.Show("Logged in successfully");

    }

the < div class=""linkWrap noCount"">Messages< /div> is only shown while logged in so thats why I use it to see if a user is logged in

but the problem is it always gives me an error (wrong user and pass) becasue it reads it before the browser finishes to navigate to the page. I tried threads and thread sleep and even timers but it doesnt seem to work

an ideas?

here is the code:

private void button1_Click(object sender, EventArgs e)
    {
        Thread thread = new Thread(new ThreadStart(WorkThreadFunction));
        thread.Start();

         string email = textBox1.Text;
    string password = textBox2.Text;

    // create a new browser
    WebBrowser w = new WebBrowser();
    w.Dock = DockStyle.Fill;
    this.Controls.Add(w); // you may add the controll to your windows forms if  you want to see what is going on
    // latter you may not chose to add the browser or you can even set it to invisible... 


    // navigate to facebook
    w.Navigate(@"http://www.facebook.com/login.php");

    // wait a little
    for (int i = 0; i < 100; i++)
    {
        System.Threading.Thread.Sleep(10);
        System.Windows.Forms.Application.DoEvents();
    }


    HtmlElement temp=null;

    // while we find an element by id named email
    while (temp == null)
    {
        temp = w.Document.GetElementById("email");
        System.Threading.Thread.Sleep(10);
        System.Windows.Forms.Application.DoEvents();
    }

    // once we find it place the value
    temp.SetAttribute("value", email);


    temp = null;
    // wiat till element with id pass exists
    while (temp == null)
    {
        temp = w.Document.GetElementById("pass");
        System.Threading.Thread.Sleep(10);
        System.Windows.Forms.Application.DoEvents();
    }
    // once it exist set its value equal to passowrd
    temp.SetAttribute("value", password);

    // if you already found the last fields the button should also be there...

    var inputs = w.Document.GetElementsByTagName("input");

    int counter = 0;
    bool enableClick = false;

    // iterate through all the inputs in the document
    foreach (HtmlElement btn in inputs)
    {

        try
        {
            var att = btn.GetAttribute("tabindex");
            var name = btn.GetAttribute("id");

            if (enableClick)// button to submit always has a differnt id. it should be after password textbox
            {
                btn.InvokeMember("click");
                counter++;
            }

            if (name.ToUpper().Contains("PASS") || att=="4") 
            {
                enableClick = true;  // button should be next to the password input                    
            }

            // try a max of 5 times
            if (counter > 5)
            {
                break;

            }
        }
        catch
        {


        }


                }






    }

Upvotes: 0

Views: 848

Answers (2)

The Mask
The Mask

Reputation: 17447

I recommend you use Facebook C# SDK. It uses the OAuth protocol, for user-authentication.

Down an code example how to get user friends with Facebook-C#-SDK:

using Facebook; //add reference to facebook dll for it work

declare the fields:

private FacebookOAuthResult result;
private FacebookOAuthClient OAuth;

and

private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {

            if (webBrowser1.Url.AbsolutePath == "/login.php")
            {
                     // do login..      
            }

            if (FacebookOAuthResult.TryParse(e.Url, out result))
            {
                if (result.IsSuccess)
                {
                  FacebookClient fbClient = new FacebookClient(result.AccessToken);
                  dynamic friends = fbClient.Get("/me/friends"); //User friends
                  // do something.. 
                }
                else
                {
                    string errorDescription = result.ErrorDescription;
                    string errorReason = result.ErrorReason;
                    string msg = String.Format("{0} ({1})", errorReason, errorDescription);
                    MessageBox.Show(msg, "User-authentication failed!");
                }
            }
        }

and then for start user-authentication:

//.. 

    OAuth = new FacebookOAuthClient();
    OAuth.AppId = appId; // see link above,you can find how to get it
    OAuth.AppSecret = appSecret; // see link above,you can find how to get it

    Uri loginUrl = OAuth.GetLoginUrl(paramenters);
    webBrowser1.Navigate(loginUrl.AbsoluteUri);

Upvotes: 1

Stelian Matei
Stelian Matei

Reputation: 11623

Checkout the facebook-sharp SDK for Windows forms:

https://github.com/facebook-csharp-sdk/facebook-winforms

Upvotes: 3

Related Questions