Entries:
Comments:
Posts:

Loading User Information from Channel 9

Something went wrong getting user information from Channel 9

Latest Achievement:

Loading User Information from MSDN

Something went wrong getting user information from MSDN

Visual Studio Achievements

Latest Achievement:

Loading Visual Studio Achievements

Something went wrong getting the Visual Studio Achievements

Shutdown/Restart/Logoff your PC using TweetMyPC

In this article I will show you how you can use Twitter API to Shutdown/Restart/Logoff your PC remotely using VB.net.

Introduction

I have a very slow internet connection at home and most of the time Downloads takes hours to complete. I decided to write an application which will help me Shutdown my PC from a remote location. I wanted to use it to shutdown when I go out when some downloading is going on in my laptop. Instead of using a server and client architecture I decided to use Twitter API and use “My Timeline” to supply commands. One other reason to use Twitter is that I will be able to tweet from my mobile as well. I don't need to look for a computer with an internet connection when I am on the move.

Why Yedda Twitter framework?

The Twitter REST API methods allow developers to access core Twitter data. This includes update timelines, status data, and user information. It's very easy to connect to Twitter and get user time line using .net. But I dint wanted to reinvent wheel and decided to use an existing Twitter library. Yedda Twitter framework is the best open source Twitter library available in the internet. You can learn more and download the library from yedda's home page.

Designing the Interface

I wanted the interface to be as simple as possible. Below is the screenshot of TweetMyPC's interface which does not have more than 2 Text Boxes, 1 Check Box, Label and a Button.

clip_image001

The form also has a Notify Icon, Context Menu Strip and a Timer. Following are the names of all the controls in the form.

  • From : frmTweetMyPc
  • Text Boxes : txtUserName, txtPassword
  • Button : btnSave
  • Check Box : chkStartAutomatic
  • Timer : tmrTweet (Interval : 10000)
  • Label : lblSatus

There are few My.settings properties to store user information. These properties are shown below.

clip_image002

The Code
Add the following code which minimizes the Form on Load and Enable Timer to check for Tweets every 1 minute.

Me.WindowState = FormWindowState.Minimized
Me.ShowInTaskbar = False
tmrTweet.Enabled = True

The following code in Button's Click event will validate Twitter username, Password and save it to My.Settings.

If txtUserName.Text.Trim = "" Then
    lblSatus.Text = "Please enter Twitter Username"
    txtUserName.Focus()
    Exit Sub
End If
If txtPassword.Text.Trim = "" Then
    lblSatus.Text = "Please enter Twitter Password"
    txtPassword.Focus()
    Exit Sub
End If

lblSatus.Text = ""


'Check for valid Username and Password and then Save Settings
Dim objTwitter As New Yedda.Twitter
Dim Updates As XmlDocument

Try 'Try Logging in
    Updates = objTwitter.GetUserTimelineAsXML(txtUserName.Text.Trim, txtPassword.Text.Trim)
    My.Settings.UserName = txtUserName.Text.Trim
    My.Settings.Password = txtPassword.Text.Trim
    Me.WindowState = FormWindowState.Minimized
    Me.ShowInTaskbar = False
    tmrTweet.Enabled = True
Catch ex As Exception
    MsgBox("Failed to Login to Twitter with the values supplied. Please check your login details.")
    txtUserName.Focus()
    Exit Sub
End Try

Yedda library is used to login to Twitter to check for valid username and password. The Label lblSatus is used to display any error messages.

Add the following code to the Checkbox's CheckChanged event which will add the required registry keys to start this app on Window's startup

If chkStartAutomatic.Checked = True Then       My.Settings.AutomaticStart = True
      Dim regKey As RegistryKey
      regKey = Registry.CurrentUser.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Run", True)
      regKey.SetValue(Application.ProductName, Application.ExecutablePath)
      regKey.Close()
Else
      My.Settings.AutomaticStart = False
      Dim regKey As RegistryKey
      regKey = Registry.CurrentUser.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Run", True)
      regKey.DeleteValue(Application.ProductName)
      regKey.Close()
End If

The following code in Timer's Tick event will do the job of checking Twitter Timeline every one minute and Shutdown/Restart/Log off the system based on the Tweet.

If My.Settings.UserName.Trim = "" Then
    Exit Sub
Else
    'Check for new Tweet 
    Dim objTwitter As New Yedda.Twitter
    Dim Updates As XmlDocument
    Dim node As XmlNode
    Try 'Try Logging in
        Updates = objTwitter.GetUserTimelineAsXML(My.Settings.UserName.Trim, My.Settings.Password.Trim)
        Catch ex As Exception
        MsgBox("Error : Failed to Login to Twitter with the values supplied. Please check your login details.")
        Exit Sub
    End Try
    Try
        node = Updates.SelectSingleNode("/statuses/status/id")
        If node.InnerText.Trim <> My.Settings.LastID.Trim Then 
            'Compare the Tweet ID to check for new tweets
            My.Settings.LastID = node.InnerText.Trim
            node = Updates.SelectSingleNode("/statuses/status/text")
            ProcessTweet(node.InnerText.Trim)
          End If
    Catch ex As Exception
        Exit Sub
    End Try
End If

If the Tweet is new then we process the tweet.

Private Sub ProcessTweet(ByVal Tweet As String)
    If Tweet = "Shutdown" Then
        System.Diagnostics.Process.Start("shutdown", "-s -f -t 100") 'Shutdown
    ElseIf Tweet = "Logoff" Then
        System.Diagnostics.Process.Start("shutdown", "-l -f -t 100") 'Logoff
    ElseIf Tweet = "Restart" Then
        System.Diagnostics.Process.Start("shutdown", "-r -f -t 100") ' Restart
    End If
End Sub

The Context Menu strip has two menu items. They are Edit Setting and Exit.

clip_image003

Add the following code the “Edit Settings” Client event and Notify Icon's Mouse Double Click Event.

tmrTweet.Enabled = False
txtUserName.Text = My.Settings.UserName.Trim
txtPassword.Text = My.Settings.Password.Trim
If My.Settings.AutomaticStart = True Then chkStartAutomatic.Checked = True
Me.WindowState = FormWindowState.Normal
Me.ShowInTaskbar = True

TweetMyPC runs silently on startup. To Edit Settings double click/Right Click the notify icon.

Working

Conclusion

Even though TweetMyPC is a simple app it has lot of interesting potential. Think about switching off your TV or washing machine using Twitter. It is possible with a little extra hardware and a simple .net program. TweetMyPC is free and open source. Feel free to download the sour code and add more functionality.

About The Author

Shoban Kumar is a Senior Software Engineer working for Allianz Cornhill India. Programming is his passion. He also writes about .net in http://www.dotnetcurry.com/ and an active participator in stackoverflow and speaker in Microsoft user group sessions. You also can follow him in Twitter.

Tags:

Follow the Discussion

  • JohnJohn

    So whats stopping me from say, joining twitter and constantly shutting down your computer?  What a silly idea this is...

  • VaibhavVaibhav

    Nice work. I haven't used Yedda, but I tried out Tweet# for my fun Twitter project: http://blog.gadodia.net/twitter-profile-copier/

  • WayneWayne

    John, look at how he is handling the tweet. You won't be able to shutdown someone elses computer by sending them a tweet that says "Shutdown"

  • DominicDominic

    Wow, this is cool. And @John, he is sending the tweet himself, so people can't send him a tweet with 'shutdown' like Wayne said. Gotta try this in C#

  • Clint RutkasClint I'm a "developer"

    @Ramana we have a few ideas on doing stuff like this Smiley

  • RamanaRamana

    Very cool app idea. Thanks.

    Would love to see a follow up on switching on or off one's TV or other appliances remotely using VB.net and Twitter framework.

  • Clint RutkasClint I'm a "developer"

    @Rogue, click the "Email Us" link and I'll help debug this with you.  It should just work as I've played with it but without seeing how you have yours set up, it could be some configuration Shoban didn't account for.

    From the link we listed, there is a newer release as well.  http://tweetmypc.codeplex.com/Release/ProjectReleases.aspx

  • RogueRogue

    Not loving the lack of documentation on setup and using this thing. Like, it's obvious that you enter your authentication info then click save and then tweet your PC to shutdown. Well, I created a new account with twitter and it doesn't recognize it on the app. The "what to expect" would be helpful as a read me to the app. As far as coding it, and compiling my own version, it seems awesome and I'm looking forward to giving it a shot.

  • DhaneshDhanesh

    Nice Thinking and different approach Smiley.. Kudos

  • RajRaj

    Cool Shoban..I'll see if this works..I recently read of this being implemented using smses,but using twitter is a easy solution Smiley

Remove this comment

Remove this thread

close

Comments Closed

Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums,
or Contact Us and let us know.