Geeks With Blogs
Allan Rwakatungu's blog Developer and Enterprise Architect

In my previous blog I wrote an introductory post on services and how you can build services using the .NET frameworks Windows Communication Foundation (WCF)
In this post I will show how to develop a real world application using WCF

The problem


During the last meeting we realized developers in Uganda are not so cool – they don’t use twitter so may not get the latest news and updates from the technology world. We also noticed they mostly use kabiriti phones (jokes).

With their kabiriti phones they are unable to access the twitter web client or alternative twitter mobile clients like tweetdeck , twirl or tweetie.

However, the kabiriti phones support SMS (Yeeeeeeei).

So what we going to do to make these developers cool and keep them updated is by enabling them to receive tweets via SMS.

We shall also enable them to develop their own applications that can extend this functionality

Analysis

Thanks to services and open API’s solving our problem is going to be easy.

 1. To get tweets we can use the twitter service for FREE

2. To send SMS we shall use www.clickatell.com/ as they can send SMS to any country in the world. Besides we could not find any local service that offers API's for sending SMS :(.

3. To enable developers to integrate with our application so that they can extend it and build even cooler applications we use WCF. In addittion , because connectivity might be an issue we decided to use WCF because if has a inbuilt queing features.
We also choose WCF because this is a post about .NET and WCF :).

The Code

Accessing the tweets

To consume twitters REST API we shall use the WCF REST starter kit.
Like it name indicates , the REST starter kit is a set of .NET framework classes that enable developers to create and access REST style services ( like the twitter service).

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using Microsoft.Http;

using System.Net;

using System.Xml.Linq;

 

namespace UG.Demo

{

    public class TwitterService

    {

        public IList<TwitterStatus> SomeMethodName()

        {

            //Connect to the twitter service (HttpClient is part of the REST startkit classes)

            HttpClient cl = new HttpClient("http://api.twitter.com/1/statuses/friends_timeline.xml");

            //Supply your basic authentication credentials

            cl.TransportSettings.Credentials = new NetworkCredential("ourusername", "ourpassword");

            //issue an http

            HttpResponseMessage resp = cl.Get();

            //ensure we got reponse 200

            resp.EnsureStatusIsSuccessful();

            //use XLinq to parse the REST XML

            var statuses = from r in resp.Content.ReadAsXElement().Descendants("status")

                           select new TwitterStatus

                           {

                               User = r.Element("user").Element("screen_name").Value,

                               Status = r.Element("text").Value

                           };

            return statuses.ToList();

        }

    }

    public class TwitterStatus

    {

        public string User { get; set; }

        public string Status { get; set; }

    }

}

 Sending SMS

 

public class SMSService

    {

        public void Send(string phone, string message)

        {

           

            HttpClient cl1 = new HttpClient();

             //the clickatell XML format for sending SMS

            string xml = String.Format("<clickAPI><sendMsg><api_id>3239621</api_id><user>ourusername</user><password>ourpassword</password><to>{0}</to><text>{1}</text></sendMsg></clickAPI>",phone,message);

            //Post form data

            HttpUrlEncodedForm form = new HttpUrlEncodedForm();

            form.Add("data", xml);

            System.Net.ServicePointManager.Expect100Continue = false;

            string uri = @"http://api.clickatell.com/xml/xml";

            HttpResponseMessage resp = cl1.Post(uri, form.CreateHttpContent());

            resp.EnsureStatusIsSuccessful();

        }

    }

 

 

Our WCF Service

namespace UG.Demo

{

    [ServiceContract]

    public interface IShowMeTheMoney

    {

        [OperationContract(IsOneWay = true)]

        void SendMessage(IList<string> numbers);

    }

}

 

public class ShowMeTheMoneyService:IShowMeTheMoney

    {

        TwitterService twitsvc;

        SMSService smssvc;

        public ShowMeTheMoneyService()

        {

            twitsvc = new TwitterService();

            smssvc = new SMSService();

        }

        #region IShowMeTheMoney Members

 

        public void SendMessage(IList<string> numbers)

        {

            var twit = twitsvc.SomeMethodName().FirstOrDefault();

            foreach (var item in numbers)

            {

 

                smssvc.Send(item, String.Format("@{0} {1}", twit.User, twit.Status));

            }

        }

 

 


We host our application in a Windows Console and we also support queing 

namespace UG.Demo

{

    class Program

    {

        static void Main(string[] args)

        {

            // Get MSMQ queue name from appsettings in configuration.

            string queueName = ConfigurationManager.AppSettings["queueName"];

 

            // Create the transacted MSMQ queue if necessary.

            if (!MessageQueue.Exists(queueName))

                MessageQueue.Create(queueName, true);

 

    s.

            // This is useful to generate a proxy for the client.

            string baseAddress = ConfigurationManager.AppSettings["baseAddress"];

 

            // Create a ServiceHost for the service type.

            using (ServiceHost serviceHost = new ServiceHost(typeof(ShowMeTheMoneyService), new Uri(baseAddress)))

            {

                // Open the ServiceHostBase to create listeners and start listening for messages.

                serviceHost.Open();

 

                // The service can now be accessed.

                Console.WriteLine("The service is ready.");

                Console.WriteLine("Press <ENTER> to terminate service.");

                Console.WriteLine();

                Console.ReadLine();

 

                // Close the ServiceHostBase to shutdown the service.

                serviceHost.Close();

            }

 

        }

    }

}

 

 

Thats it. We have just developed an application that can can retrieve tweets from twitter and send SMS to any number in the world.

Wrap - up

I just showed you a very simple but yet very powerful application built using open API's that i accessed from half the way the world.

I would like to encourage developers , especially Ugandan's to develop public , open , standard services (API's) for their applications.

Wilson Kutegeka who made the last presentation is the developer of clinic master  - he could make it even more powerful by opening up its functionality as open standard based API's (using WCF off course). This would allow some of the younger talented developers like David Mugume who attended the meeting to extend this software for instance by building an application where patients can get their medical history by SMS.

if Malisa Ncube who also works in the health sector built open API's then by combining the functionality of his applications with clinic master an even more powerful application might be built.

Hope you see where am going with this.

Its my opinion that "local" software engeeners can develop powerful applications by collaborating via open standard API's ; so I encourage all off you to check out WCF because it is a tool that can enable you to build these services.

Hopefully in a few months we shall start to see some localized API's.

For inspiration (or use) check out programmable web

 

Posted on Tuesday, June 8, 2010 4:19 AM Services , Windows Communication Foundation , Service Oriented Architecture (WCF) | Back to top


Comments on this post: Building services with the .NET framework Cont’d

# re: Building services with the .NET framework Cont’d
Requesting Gravatar...
Its very usefull but codes are very hard to understand for a beginner like me. The aplication that you developed that can can retrieve tweets from twitter and send SMS to any number in the world is very useful. I have added this article to my favorited.
Left by Bill on Feb 22, 2011 4:30 AM

# re: Building services with the .NET framework Cont’d
Requesting Gravatar...
I am fan of NET and WCF. Your blog is cool and informative.
Left by Kale Kapı on Feb 22, 2011 6:11 AM

Your comment:
 (will show your gravatar)


Copyright © Allan Rwakatungu | Powered by: GeeksWithBlogs.net