Eclipsed4utoo's Blog
Not Your Ordinary Programmer

WPF – Using an Application Configuration File

     Posted on Fri ,05/02/2010 by Ryan Alford

This is going to be a real short post about an issue that I ran into recently with WPF.

I was wanting to use an app config file with my WPF application.  I was running into an issue with the ConfigurationManager calls not getting the information from the app config file.

I added the app config just like I would in a Windows Form..
AppConfig

My app config file looked something like this…

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
     <add key="myKey" value="SomeValue" />
  </appSettings>
</configuration>

I was using the standard code that works fine in Windows Forms(needed to add a reference to the System.Configuration):

using System.Configuration

private void Window_Loaded(object sender, RoutedEventArgs e)
{
     var myKey = ConfigurationManager.AppSettings["myKey"];
}

However, the app settings were not being found.  After scratching my head for a while and searching numerous places online, I found a small response on a forum.  None of the “MVP”s picked up on it.  It was because of the name of the app config file.  By default, VS2008 added the file as “App1.config”.  For some reason, the ConfigurationManager class looks for a file named exactly “App.config”.

So simply changing the name of the config file to “App.config” fixed the issue and the code started working.

C# – Log in to Website Programmatically

     Posted on Fri ,22/01/2010 by Ryan Alford

In this tutorial, will show how to log into a website through code.  I am going to use Twitter in my example.

THIS IS FOR EDUCATIONAL PURPOSES ONLY.  I WOULD NOT ADVISE THE USE OF THIS TO ALWAYS LOG-IN TO TWITTER.

First, you will need to download and install Tamper Data.  It’s an add-on for Firefox that allows you to view and tamper with GET/POST web request data.  We won’t be doing any tampering.  We will be using it to view what POST parameters the page is expecting.

Next, navigate to the log in page for Twitter(http://twitter.com/login).  Once the page has loaded, go to Tools –> Tamper Data to open Tamper Data.  At the top of Tamper Data, click the Start Tamper button.  After clicking the button, click the “Sign In” button on Twitter’s log in page.  Once you hit the Sign In button, Tamper Data will prompt you with this popup….

Tamper Data Popup

Click “Tamper”.  You will then be presented with this window…

Tamper Data

If you notice on the right-hand side of the window, you will see the POST parameters.  These are:

authenticity_token
session[username_or_email]
session[password]
commit

Now that we have those, we can close the Tamper Data window, and close Firefox.

Now for the code.  The code is actually fairly simple.  We are just going to use the WebBrowser class to make the requests to the server to get the html source of the page.  This will give us the “authenticity_token” for us to use in the POST request.

string url = "https://twitter.com/login";
string username = "someUserName";
string password = "somePassword";
string commit = "Sign+In"; //this matches the data from Tamper Data

private void Login()
{
     WebBrowser b = new WebBrowser();
     b.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(b_DocumentCompleted);
     b.Navigate(url);
}

private void b_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
     WebBrowser b = sender as WebBrowser;
     string response = b.DocumentText;

     // looks in the page source to find the authenticity token.
     // could also use regular expressions here.
     int index = response.IndexOf("authenticity_token");
     int startIndex = index + 41;
     string authenticityToken = response.Substring(startIndex, 40);

     // unregisters the first event handler
     // adds a second event handler
     b.DocumentCompleted -= new WebBrowserDocumentCompletedEventHandler(b_DocumentCompleted);
     b.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(b_DocumentCompleted2);

     // format our data that we are going to post to the server
     // this will include our post parameters.  They do not need to be in a specific
     //    order, as long as they are concatenated together using an ampersand ( & )
     string postData = string.Format("authenticity_token={2}&session[username_or_email]={0}&session[password]={1}&commit={3}", username, password, authenticityToken, commit);

     ASCIIEncoding enc = new ASCIIEncoding();

     //  we are encoding the postData to a byte array
     b.Navigate("https://twitter.com/sessions", "", enc.GetBytes(postData), "Content-Type: application/x-www-form-urlencoded\r\n");
}

private void b_DocumentCompleted2(object sender, WebBrowserDocumentCompletedEventArgs e)
{
     WebBrowser b = sender as WebBrowser;
     string response = b.DocumentText;

     if (response.Contains("Sign out"))
     {
         MessageBox.Show("Login Successful");
     }
}

And that’s all you need to do.  You can now use the response variable to see the tweets that are in your timeline.

Android – Open Contacts Activity and Return Chosen Contact

     Posted on Wed ,30/12/2009 by Ryan Alford

I was looking for a way to open the Contacts Activity, chose a Contact, then have that Contact returned to my application.  I found a number of code snippets, but they all used depreciated API calls.  So I decided to make this post with the updated API calls for Android 2.0.

First, you will need to add this permission to your AndroidManifest.xml file:

<uses-permission android:name="android.permission.READ_CONTACTS"/>

Next, add this constant as a class level variable:

private static final int PICK_CONTACT = 3;

Now, you will add the code to open the Contacts Activity.  This is done by using an Intent:

// I did this from a button click
public void btnAddContacts_Click(View view){
     Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
     startActivityForResult(intent, PICK_CONTACT);
}

Now, you will override the “onActivityResult” activity method, and get the Contact information:

@Override
public void onActivityResult(int reqCode, int resultCode, Intent data){
    super.onActivityResult(reqCode, resultCode, data);

    switch(reqCode){
       case (PICK_CONTACT):
         if (resultCode == Activity.RESULT_OK){
             Uri contactData = data.getData();
             Cursor c = managedQuery(contactData, null, null, null, null);

             if (c.moveToFirst()){
                 // other data is available for the Contact.  I have decided
                 //    to only get the name of the Contact.
                 String name = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
                 Toast.makeText(getApplicationContext(), name, Toast.LENGTH_SHORT).show();
             }
         }
    }
}

And that is all you need to do.

Get Adobe Flash playerPlugin by wpburn.com wordpress themes