Twitter API Friends Timeline and LINQ to XML

15. April 2009

So here is some code to grab the friends timeline utilizing LINQ to XML.  There are two parts to this. 1) a function to make the request to their API and bring back the response and 2) use LINQ to XML to read the friends timeline.

You'll notice in my code I add the querystring item "count" because it's open to bring back the items you want. Without "count" it brings back the 20 items.

1) Code to make the request and return a string (which is the XML) brought back

public string GetFriendsTimeline(int count)
{
        WebRequest req = WebRequest.Create(string.Format("http://twitter.com/statuses/friends_timeline.xml?count={0}", count));
        NetworkCredential creds = new NetworkCredential(_username, _password);

        req.Credentials = creds;
        req.Method = "GET";
        WebResponse resp = (WebResponse)req.GetResponse();

        Stream respStream = resp.GetResponseStream();
        StreamReader reader = new StreamReader(respStream);

        string respString = reader.ReadToEnd();

        reader.Close();
        respStream.Close();
        resp.Close();

        return respString;
}

_username and _password are private variables stored in the class that holds this function so replace the variable with your credentials if need be during testing

2) The function that utilizez LINQ to XML to easily roll through the XML string in the Friends Timline

private void GetRecentTweets()
{

        timelineString = objTwitter.GetFriendsTimeline(10);

        XDocument xDoc = XDocument.Parse(timelineString);

        var resultTweets = from tweets in xDoc.Descendants("status")
                          select new
                          {
                              ID = tweets.Element("id").Value,
                              Text = tweets.Element("text").Value,
                              Source = tweets.Element("source").Value,
                              UserID = tweets.Element("user").Element("id").Value,
                              UserName = tweets.Element("user").Element("name").Value,
                              UserScreenName = tweets.Element("user").Element("screen_name").Value,
                              UserImageUrl = tweets.Element("user").Element("profile_image_url").Value,
                              CreatedDate = tweets.Element("created_at").Value,
                          };

 //...the rest of your code here for

}

remember the function in step one is located in a class so a simple copy and paste of this code will not work in your program.  However, the two functions combined will deciding how you want them to be laid out in your program.  Happy programming.

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

C# ,

Export Event Logs Windows 2003 in .NET - C#

7. April 2009

This is a small console application I wrote to export the event log files in C#.  I did this because in Windows 2003 I couldn't find a way to get it to XML by doing a Save As or anything like that.  I did notice in Windows Vista that you can save it as XML...which is nice, but couldn't find a way for Server 2003.  Anyway I did this more or less because I wanted to see stuff happening with ASP.NET 2.0 since it writes to the Application Log with any unhandled exception.  So as I always do I'm just going to paste the entire code...about 140 lines. This program takes the following information:

Server Name
Source of Entry (i.e., ASP.NET 2.0.50727.0)
Log Type ( i.e., Application, Security)

This ends up exporting the event log from Windows 2003 to an XML file.

Oh yea, as always use it at your own risk, if anything it just won't work because it can't open the Event Log or can't write the file...not too much error catching going on in here since I wrote it in about 30 minutes or so.

using System;
using System.Diagnostics;
using System.IO;

namespace AppLogExporter
{
    class Program
    {

        static int evtType = 0;
        static int logType = 0;
        static string serverName = "";
        static string eventSource = "";

        static void Main(string[] args)
        {
            ShowEntryMenu();
            GetLogInfo();
            Console.ReadLine();
        }

        #region "Show Entry Menu"
        private static void ShowEntryMenu()
        {

            Console.Write("Enter Server Name: ");
            serverName = Console.ReadLine();

            Console.WriteLine();

            Console.Write("Enter Source for Log Entry: ");
            eventSource = Console.ReadLine();

            Console.WriteLine();

            Console.WriteLine("Select Log Type");
            Console.WriteLine("1:Application");
            Console.WriteLine("2:Security");
            Console.WriteLine("3:Setup");
            Console.Write("Log Type: ");

            logType = Int32.Parse(Console.ReadLine());

            Console.WriteLine();

            Console.WriteLine("Select the Event Type to Export");
            Console.WriteLine("1:Error");
            Console.WriteLine("2:Information");
            Console.WriteLine("3:Warning");
            Console.WriteLine("4:All");
            Console.Write("Event Type: ");

            evtType = Int32.Parse(Console.ReadLine());

        }

        #endregion

        #region "GetLogInfo"
        private static void GetLogInfo()
        {
            EventLog eventLog = null;
            string eventType = string.Empty;
            StreamWriter swLog = new StreamWriter("D:\\ApplicationLogExport.xml", false);
           
            swLog.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
            swLog.WriteLine("<SystemLog>");

            try
            {
                switch (logType)
                {
                    case 1: eventLog = new EventLog("Application", serverName);
                        break;
                    case 2: eventLog = new EventLog("Security", serverName);
                        break;
                    case 3: eventLog = new EventLog("Setup", serverName);
                        break;
                    default: break;
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: Unable to open log file for the following reason: {0}", ex.Message);
                return;              
            }
          
            switch (evtType)
            {
                case 1: eventType = "Error";
                    break;
                case 2: eventType = "Information";
                    break;
                case 3: eventType = "Warning";
                    break;
                case 4: eventType = "All";
                    break;
                default: break;

            }

            //READ EACH ENTRY IN THE LOG AND WRITE TO FILE
            foreach (EventLogEntry evtLogEntry in eventLog.Entries)
            {

                if (eventType == "All")
                {
                    //get all event types
                    if (evtLogEntry.Source == eventSource)
                    {
                        Console.WriteLine(string.Format("Entry: {0} - Message: {1}", evtLogEntry.EntryType, evtLogEntry.Message));
                        swLog.WriteLine("<Entry>");
                        swLog.WriteLine("<Type>{0}</Type>", evtLogEntry.EntryType);
                        swLog.WriteLine("<EntryDate>{0}</EntryDate>", evtLogEntry.TimeWritten);
                        swLog.WriteLine("<Message>{0}</Message>", evtLogEntry.Message);
                        swLog.WriteLine("</Entry>");
                    }
                }
                else
                {
                    if (evtLogEntry.Source == eventSource && evtLogEntry.EntryType.ToString() == eventType)
                    {
                        Console.WriteLine(string.Format("Entry: {0} - Message: {1}", evtLogEntry.EntryType, evtLogEntry.Message));

                        swLog.WriteLine("<Entry>");
                        swLog.WriteLine("<Type>{0}</Type>", evtLogEntry.EntryType);
                        swLog.WriteLine("<EntryDate>{0}</EntryDate>", evtLogEntry.TimeWritten);
                        swLog.WriteLine("<Message><![CDATA[{0}]]></Message>", evtLogEntry.Message);
                        swLog.WriteLine("</Entry>");
                    }
                }
            }

            swLog.WriteLine("</SystemLog>");
            swLog.Close();
            swLog.Dispose();
        }
        #endregion
    }
}

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

C#

Timer Not Working in Windows Service

20. March 2009

So I had the same problem as all the others out there with a timer not working correctly in a Windows Service.  Here was my situation.  I was using the System.Threading.Timer and had a callback assigned to it.  Everything would work fine, but for some reason after 10-14 hours it stopped running.  At first I thought it was my code in the service so I added logging code and try-catches to a lot of places to see where it may be failing.  I also added code in the callback event just to make sure it was hitting that, well it wasn't.  It never made it to the callback event, hence why nothing else was getting logged. 

So I got some advice from my friend Quintin (check him out on stackoverflow) and he suggested using System.Timers.Timer.  And sure enough it worked! Now, I'm personally still puzzled as to why this works because alot of articles on the net said don't use System.Timers.Timer in a windows service and use System.Threading.Timer instead (hence why I chose that one first).  Anyway, here is an article on MSDN that explains the difference of the timers and just the small code snippet of my timer in the service.

http://msdn.microsoft.com/en-us/library/tb9yt5e6(VS.80).aspx

This logic is called via the OnStart method for the service

System.Timers.Timer _timer = new System.Timers.Timer();
_timer.Enabled = true;
_timer.Interval = 1800000;

_timer.Elapsed += new System.Timers.ElapsedEventHandler(_timer_Elapsed);

Good luck

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

C#