Posted by: followmcleod | November 27, 2009

Becoming A Better Developer

If you have the same technical mindset as myself you’ll always be looking for ways to improve your knowledge and development style. Davy Brion has come up with a great list of recommended reads for all developers.

Make sure you take a look at A Reading Guide To Becoming A Better Developer at Davy’s blog.

About James McLeod, Managing Director at Narvi Digital Media, Brighton

Posted by: followmcleod | November 22, 2009

Facebook Development Toolkit Example

FacebookThe following C# code extract has been written to demonstrate how to use the Facebook Development Toolkit from Clarity Consulting.

It’s assumed that your application has been registered with Facebook and you have the necessary keys. This is done by adding the developer application to your Facebook profile and registering your application. If you need more information on how to do this I would recommend reading the following Facebook Getting Started Guide.

Written below is a code extract that updates the status of the person who has logged into the application. The process of logging into Facebook is handled by the Session.Login() method by presenting a modal dialog box to the user.

Due to the threading model of the API it is important to use the STAThread attribute when creating the Main application method.

[STAThread]
static void Main(string[] args)
{.....

If this isn’t done an “ActiveX control ’8856f961-340a-11d0-a96b-00c04fd705a2′ cannot be instantiated because the current thread is not in a single-threaded apartment” exception will be thrown.

Before updating the user’s status it’s important to ask their permission by adding an ExtendedPermissions.status_update enum to the application session. This will display a confirmation dialog to the user after they have logged into the application.

List<Enums.ExtendedPermissions> Permissions = new List<Enums.ExtendedPermissions>();
Permissions.Add(Enums.ExtendedPermissions.status_update);

The following is where the application and application secret keys are added to the session. It’s important to read all of the recommendations on how to use the app keys as they can be used outside of your application if obtained through App.Config files.

All development recommendations can be found in the Facebook Developers Wiki.

Facebook.Session.DesktopSession d = new Facebook.Session.DesktopSession("myAppKeyFrom Facebook", "mySessionSecretFromFacebook", "mySessionKey", false, Permissions);

//display application login to user
d.Login();

After the session has been created it is then possible to create an instance of the Facebook Rest API. This is where all of the supported methods can be found that control the status of the logged in Facebook profile. Within the context of this example it is the Status.Set method that is being called.

Facebook.Rest.Api Api = new Facebook.Rest.Api(d);

Below is where the magic happens and the user’s status is updated. I’ve decided to go for the traditional ‘hello world’ example to add a bit of weight to my geekhood. :)

Api.Status.Set("has created a typical hello world status!");

Finally the user is logged out of the system.

d.Logout();

I hope you find this post useful as I know there aren’t very many examples out there at the moment. Feel free to add your examples to this page as it’s always a pleasure to share your views with the rest of the development community.

About James McLeod, Managing Director at Narvi Digital Media, Brighton

Posted by: followmcleod | November 12, 2009

Microsoft Facebook Development Toolkit

FacebookFacebook have announced Microsoft’s support of Facebook Connect with the release of version 3.0 of the Facebook Development Toolkit.

The goal of version 3.0 is to provide support for Silverlight, ASP.NET MVC, WPF, and FBML Server Controls. Microsoft have also provided login controls that replace the BasePage and MasterPage for Canvas Development.

The Microsoft Facebook Development Toolkit can be downloaded from Codeplex and has been developed by Clarity Consulting.

As with all third party APIs, incorporating another corporations DLLs into your project leaves you one step removed from the functionality of the system you are integrating. You may perceive faster project delivery but you will always be at the mercy of the third party for upgrades and bug fixes when issues arise.

With this in mind I believe downloading and developing with the API will fast track your understanding of how Facebook Connect works. However, don’t use the download option as an excuse not to flip the hood and get your hands dirty with the Facebook Connect API.

Still get involved with Facebook developer conversations at the Facebook Development Wiki and keep making your API calls to Facebook Connect directly. After all it’s our use of these systems that pushes corporations like Facebook and Twitter to evolve the systems to meet our needs.

In essence, give the Microsoft Facebook APIs a go, but don’t be totally reliant on Uncle Bill to provide you access to an open system that’s been provided with you in mind.

About James McLeod, Managing Director at Narvi Digital Media, Brighton

Posted by: followmcleod | November 4, 2009

HTTP Posting to Twitter Part 3

Twitter

For the past few weeks I’ve been exploring the Twitter API and have been setting down some examples on how to communicate with the Twitter system using C# and the .NET Framework.

This post ties my previous examples together by posting to the Twitter API update method which is a member of the status class. A full description of the Twitter API can be found here

If you haven’t seen my previous posts please feel free to read them here: HTTP Posting to Twitter Part 1 and HTTP Posting to Twitter Part 2. I’m also more than happy to accept comments on all my articles.

Below is a segment of code that I have taken from the class Status which contains all of the methods that are contained within Twitter’s status class. Within this example I have focused on the update method.

As you can see the Status class directly inherits from a class that I have named Twitter. The Twitter class contains the overridden ExecuteString method demonstrated in HTTP Posting to Twitter Part 2.

public class Status : Twitter
{..

public string update(string status)
{
    return ExecuteString(new PostingParameters("statuses/update.xml",
        String.Format("status={0}&source={1}",
            HttpUtility.UrlEncode(status),
                HttpUtility.UrlEncode(Config.Source))), true,
                    Method.Post);

}
..}

The first parameter accepted by the ExecuteString method is a class named PostingParameters. This class contains the properties URL and Message. These two properties store all of the information that is posted to Twitter.

The URL property is the relative URL of the method call on the Twitter website. The Message property contains the GET or POST variables the API call requires. Please note that the source variable is no longer accepted by the Twitter update method in favour of OAuth security validation.

The last two parameters that are required by ExecuteString are LoginRequired and an enum named Method. As you can see by the method call the user needs to be logged into the system in order to post a Twitter update. The method also needs to be posted to Twitter, so the HTTP request type Method.Post is set. All of these parameters are passed to the HttpRequest class in HTTP Posting to Twitter Part 1 which adds all of the correct credentials to the HTTP call.

In response Twitter returns an XML string that contains a number of parameters. These are documented in the online Twitter API documents. What I do with the returned XML will be documented in a future post to this blog.

Please feel free to leave a comment or get in contact. I am more than happy to receive your feedback.

About James McLeod, Managing Director at Narvi Digital Media, Brighton

Posted by: followmcleod | October 26, 2009

HTTP Posting to Twitter Part 2

Twitter APIThis is the second part of my HTTP Twitter posting series. Within this post I start to build upon the ExecuteString method that encapsulates the HttpWebRequest object and process.
  
If you want to read related articles they can be found here:
    
The code example below overrides the virtual method ExecuteString within its own class. This means the HttpWebRequest class can be used to post to other APIs that use HTTP as its transportation method.
    
The ExecuteString method below is used to piece all of the communication parts that are needed for a successful Twitter post. This includes the Twitter URL and PostingParameters, whether a user account login is required for the API call, and the method of the call (Post, Get, or Delete). 
    

protected override string ExecuteString(PostingParameters PostingParameters, bool LoginRequired, Method Method)

{

    PostingParameters.URL =

    String.Format(“{0}{1}”, Config.TwitterURL, PostingParameters.URL);

    return base.ExecuteString(PostingParameters, LoginRequired,                                                             Method);

}

In my next post I’ll implement a method call that posts a status change to show the total lifecycle of a Twitter call.
    
In the meantime it’ll be good to hear from you. Feel free to post comments and ask questions.
    

About James McLeod, Managing Director at Narvi Digital Media, Brighton

Posted by: followmcleod | October 22, 2009

Base64Encoding a Simple String

dotnetAfter researching other blog posts and opinions for the most efficient and safe way to Base64Encode and Base64Decode a string I’ve decided to place my final output here. Hopefully you find it useful.
 
Thanks to @MikeHatfield for his input into the post. I’ve amended the code example to reflect Mike’s comment.
 

static public string Base64Encode(string toEncode)
{
    byte[] encodedBytes = System.Text.Encoding.UTF8.GetBytes
                                                        (toEncode);
    return System.Convert.ToBase64String(encodedBytes);
}

static public string Base64Decode(string toDecode)
{
    byte[] encodedBytes = System.Convert.FromBase64String(toDecode);
    return System.Text.Encoding.UTF8.GetString(encodedBytes);
}

About James McLeod, Managing Director at Narvi Digital Media, Brighton

Posted by: followmcleod | October 21, 2009

Squidoo Twitter Apps

TwitterThanks @KevinLiebl for passing this great link over. www.squidoo.com/twitterapps is an extensive list of all the Twitter Apps you’ll ever need in your social networking life.

Feel free to leave your Twitter app recommendation at the end of this post. It’ll be great to hear your views and comments.

About James McLeod, Managing Director at Narvi Digital Media, Brighton

Posted by: followmcleod | October 19, 2009

HTTP Posting to Twitter Part 1

Twitter APIAs part of my ongoing social media integration research I’ve created my own C# Twitter API in order to understand how the system interacts with external applications. The following is an extract of the fundamental communications hub of the Twitter API.
    
The second and third articles can be found here: HTTP Posting to Twitter Part 2 and HTTP Posting to Twitter Part 3
 
By using the HttpWebRequest class I have created a number of methods that manage http posts and http responses. This is done through the protected virtual method ExecuteString. 
 

protected virtual string ExecuteString(PostingParameters PostingParameters, bool LoginRequired, Method Method)
{
    // Create a new HttpWebRequest object for sending http data to the
    // URL set in the class PostingParameters
    HttpWebRequest Request =
            (HttpWebRequest)HttpWebRequest.Create
                                (PostingParameters.URL);
   

    // Gets or sets a Boolean value that determines whether
    // 100-Continue behaviour is used.
    Request.ServicePoint.Expect100Continue = false;

    // GetMethodType is a method created for setting the
    // Request.Method string according to the Method Enum
    // passed through the parameters. These can be Post,
    // Get, or Delete within this class
    Request.Method = GetMethodType(Method);

    // If Twitter requires a login for a particular post, this will
    // set the security credentials
    if (LoginRequired)
    {
        if (this.Username != String.Empty && this.Password !=             String.Empty)
        {
        Request.Credentials = new NetworkCredential(this.Username,             this.Password);
        }
        else
        {
            throw new ApplicationException(“Login Credentials             Required”);
        }
    }

    PostMessage(ref PostingParameters, ref Request);
    return GetResponse(ref Request);
}

The PostMessage method is used to post the http request to Twitter. If PostingParameters.Message is set to null it is assumed the request is a poll for information rather a post that will change a status or any other piece of information.
    

private void PostMessage(ref PostingParameters PostingParameters, ref HttpWebRequest Request)
{
    byte[] Bytes = null;

    if (PostingParameters.Message != null)
    {
        Request.ContentType = “application/x-www-form-urlencoded”;

        // Convert the message to a byte array
        // before the message is sent to Twitter
        Bytes = System.Text.Encoding.ASCII.GetBytes
                (PostingParameters.Message);

        // Set the ContentLength of the request to the size of         // the byte array
        Request.ContentLength = Bytes.Length;

            // Create a new Stream. The ‘using’ will destroy
            // the object if an exception is thrown.
        using (Stream RequestStream = Request.GetRequestStream())
        {
            RequestStream.Write(Bytes, 0, Bytes.Length);
            RequestStream.Close();
        }
    }
}

The GetResponse method is used to grab the information that is sent back from Twitter. This is normally a string of XML but can also be other server responses.
    
The HttpWebRequest object is passed into the method by reference. The response from Twitter is returned as a string.
    

private string GetResponse(ref HttpWebRequest Request)
{
    string ReturnValue = String.Empty;

    // Get the Response from the Request object
    WebResponse Response = Request.GetResponse();

    // Read the Response into a new Stream. The ‘using’
    // will destroy the object if an exception is thrown
    using (StreamReader Reader =
                new StreamReader(Response.GetResponseStream()))
    {
        // Stream the response into the ReturnValue string
        ReturnValue = Reader.ReadToEnd();
        Reader.Close();
    }

    return ReturnValue;
}

In my next post I’ll expose how I implement a class that communicates directly with Twitter.
    
In the meantime it’ll be good to hear from you. Feel free to post comments and ask questions.
    

About James McLeod, Managing Director at Narvi Digital Media, Brighton

Posted by: followmcleod | October 18, 2009

B-ALERT in the Office

With an inbox full of email and people queuing next to the desk wanting to ask questions I’ve made the conscious decision to put a halt on this path to stress. In fact I’ve decided to reinforce a system that I’ve used in the the past and has proven to be successful. This this the B-ALERT system.

The B-ALERT system has been designed to give a well balanced structure to your life so you don’t become overwhelmed with work, it helps you stretch your mind, explore new things and enjoy a well balanced lifestyle.

I’ve highlighted the B-ALERT basics below. The full description can be found in the book ‘The Power of Focus’ by Canfield, Hansen, and Hewitt (ISBN: 0-09-187650-8).

B-ALERT stands for the following and needs to be incorporated into your daily working life:

B is for Blueprint: This is your strategic plan for the day. Priorities, appointments, projects. Try and review the priority list either before the start of your working day or at the end of the previous day.

A is for Action: Concentrate on the most important activities that will move you towards accomplishing your goals. It is recommended that you split your goals into 60 day milestones to keep you on track to accomplishing your aims.

L is for Learning: Expand your knowledge through reading, the Internet, CDs, Podcasts, or blogs. It is recommend that you incorporate 30 minutes of learning into your working day.

E is for Exercise: Try to incorporate 30 minutes of exercise into your working day. I try and cycle to work. Living in Sussex this also allows me to see the Sussex countryside. This will help with the relaxation below, your general health, and your sleeping patterns.

R is for Relaxation: Eliminate your daily stress. This is easier said then done and is a habit you need to adopt. This is especially so in times of recession and when you have a stressful job. Take a lunch break, regular breaks between work, learn to meditate or take up a hobby that concentrates your focus. Playing the guitar is a good way of relaxing.

T is for Think: Take some time to reflect on the day. Review your goals, visualise yourself reaching your goals, develop new ideas and also write a journal. This is an NLP technique in self belief and will help you build your self confidence.

Over the next coming weeks I’ll document my progress on B-ALERT and will let you know my successes. I’m hoping the stresses of the global economy will lessen and my ability to create and communicate new ideas will increase.

B-ALERT is not the only system I’ll be incorperating into my daily life. In future posts I’ll cover some great advice that I’ve picked up for swinging you away from negativity thought processes and will help you adopt a positive, focused mind.

About James McLeod, Managing Director at Narvi Digital Media, Brighton

Categories

Follow

Get every new post delivered to your Inbox.