How to create a Karaoke machine in Silverlight

(Scroll to the bottom for the nice UI)

clip_image002
Figure: Karaoke machine UI done by a Developer :-)

Goal

  1. We have 2 textboxes for artist and title
  2. On click of “Start fun” button we call a web service to get the lyrics of the requested song
  3. After that we scroll the lyrics in the textbox below

See how easy that is, with Silverlight!!!

System overview

clip_image002[4]
Figure: Silverlight application calls the local web server, which calls the Lyrics web server

It’s that complicated, because cross domain access is blocked in Silverlight and the Lyrics web service doesn’t have a clientaccesspolicy.xml file

 

Prerequisites

“Silverlight SDK Toolkit”

Download “Silverlight SDK Toolkit” from MSDN
http://www.microsoft.com/downloads/details.aspx?FamilyId=c22d6a7b-546f-4407-8ef6-d60c8ee221ed&displaylang=en

Create a new Silverlight Application project

clip_image004
Figure: Create a Silverlight project

clip_image006
Figure: Yes, Add a ASP.NET web project

Create a reference to the external Lyrics web service

  1. Right click on “SilverlightApplication.Web”
    clip_image008
  2. Click on “Add Web Reference”
  3. Use this URL to reference the web service
    http://lyricwiki.org/server.php?wsdl
  4. Click on Add Reference to finish
    clip_image010

Create the web service proxy that calls the external Lyrics web service

  1. Right click on “SilverlightApplication.Web”
  2. Add New item
    clip_image012
  3. Choose “Web Service”
  4. Name it “LyricService”
  5. Enter a new method called GetSong
[WebMethod]
public org.lyricwiki.LyricsResult GetSong(string artist, string title)
{
    org.lyricwiki.LyricWiki lyricWiki = new org.lyricwiki.LyricWiki();
    return lyricWiki.getSong(artist, title);
}

Build your solution!

Create a reference to the web application proxy service



Create the layout (page.xaml)

<UserControl x:Class="SilverlightApplication.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Width="400" Height="300">
    <StackPanel>
        <TextBlock  Text="Artist"></TextBlock>
        <TextBox x:Name="textBoxArtist" Width="200" Margin="5" Height="50"></TextBox>
        <TextBlock  x:Name="Artist" Text="Title"></TextBlock>
        <TextBox x:Name="textBoxTitle" Width="200" Margin="5" Height="50"></TextBox>
        <Button x:Name="buttonStart" Content="Start fun!" Margin="10" Width="100" Height="50" Click="buttonStart_Click"></Button>
        <TextBlock x:Name="textBlockResult" FontSize="20"  Text="nothing so far" Margin="10" Height="30" Width="700"></TextBlock>
    </StackPanel>
</UserControl>
Figure: XAML for the ugly Karaoke player

Code! Finally :-)


Use a timer to tick every 100 milliseconds and scroll through the lyrics

DispatcherTimer timer = new DispatcherTimer();  
timer.Interval = new TimeSpan(0, 0, 0, 0, 100);  
timer.Tick += new EventHandler(timer_Tick);

On each timer tick, we scroll the text


private void ScrollText()
{
// Scroll 1 caret to the left, I know thats not nice :-) but easy!
textBlockResult.Text = textBlockResult.Text.Substring(1) + textBlockResult.Text.Substring(0, 1);
}

Create the event handler on song completed call

    //No code, tooo easy

Create the timer and start it after song completed call

    //No code, tooo easy

 

 

Remember: Everything is async in Silverlight



Advanced Tasks


1. Add a slider for the speed of the text

clip_image018


Figure: Slider for adjusting the speed of the text scrolling


2. Make your Silverlight application look pretty

clip_image020


3. Make the text show only 1 line full, the other lines with low opacity

Google for: Silverlight Opacity


4. Scroll the text line by line (instead by characters)

Search for the first Newline in the text and split the text there


5. Make the application go in full screen after start

Have a look at http://www.silverlightshow.net/tips/Tip-How-to-enter-full-screen-mode.aspx


6. If no title entered, let the user choose from a list of songs by the artist

clip_image022


7. Make the song scroll like Star wars

See http://franksworld.com/blog/archive/2009/05/01/11451.aspx

clip_image024


8. Embed a youtube video next to the text of that song

See http://code.google.com/apis/youtube/overview.html for details on calling the youtube webservice

Please: Rowtests in Visual Studio 2010?

I hope that we can finally do row tests ([RowTest] attribute) in Visual Studio 2010, like we can in mbUnit and nUnit.
That would make our data driven unit tests so much easier!!!

But nothing to find on the official VS2010 webpage or Soma’s Blog Search for Rowtest

 

[TestMethod]
[DeploymentItem(@"TestData\validConditions.txt")]
[DeploymentItem(@"TestData\schema.ini")]
[DataSource("System.Data.OleDb", @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|;Extended Properties='text;FMT=TabDelimited;HDR=YES'", @"validConditions#txt", DataAccessMethod.Sequential)]
public void ValidateRulesEntry_Valid_ValidConditionsFromFile()
{
 string condition = TestContext.DataRow[0].ToString();
 string returnMessage;


 bool successFul = CodeParserTryParseCondition(condition, "No error", out returnMessage);


 Assert.IsTrue(successFul, string.Format("Condition: {0}. Error: {1}.", condition, returnMessage));
}
BAD: Input data is in a text file, to view that data I have to open the text file

 

[TestMethod]
[RowTest]
[Row("Target.IsDirty")]
[Row("Target.IsValid")]
[Row("Target.Description.Contains(""Test"")")]
[Row("(1 != 2)")]
public void ValidateRulesEntry_Valid_ValidConditionsFromFile()
{
 string condition = TestContext.DataRow[0].ToString();
 string returnMessage;


 bool successFul = CodeParserTryParseCondition(condition, "No error", out returnMessage);


 Assert.IsTrue(successFul, string.Format("Condition: {0}. Error: {1}.", condition, returnMessage));
}
GOOD: Input data for unit test is attached to unit test itself --> easy to read, understand!

Getting the current Twitter-buzz with C#

My problem
I want to know what my friends on Twitter are talking about most

image

What’s the plan:

  1. Get the tweets from my friends
  2. Search this tweets for the #hashtags (Regex!!!)
  3. Count the hashtags
  4. Output the hashtags ordered by count

With tools like VS, .net framework and Twitter API this is EASY!!
Wooohooo

1. How to get the tweets

a) Twitter API

Find all info here http://apiwiki.twitter.com/ 
Currently Twitter has 2 APIs, maybe they make things easier and bring these together…
image

b) Tweetsharp

Tweetsharp is an awesome fluent interface for the Twitter API.
It’s toooo easy!!!! Make sure you check it out

http://code.google.com/p/tweetsharp/
image

c) Twitter "low level"

You can consume Twitter stuff via standard HTTP calls and get the response as XML or JSON, see this blog for an example http://psantos-blog.zi-yu.com/?p=197
That’s tooo hard :-)

 

I picked Tweetsharp, because there are so many samples available, and it is fluent!  I love Intellisense!

  1. Download tweetsharp http://code.google.com/p/tweetsharp/
  2. Unzip to your References Solution folder
  3. Add reference to your project
  4. Done

How easy is that!

 

Note
Make sure to use a Console project, we want to focus on functionality not on UI
image

 

The code to get the list of tweets looks like this

           var twitter = FluentTwitter.CreateRequest().AuthenticateAs(MyUser, MyPass) 
           .Statuses().OnFriendsTimeline().Take(1000).AsJson();

           // Get response from Twitter
           var response = twitter.Request();

           // Convert response to data classes
           var tweets = response.AsStatuses();

 

Next step

Iterate through tweets and search for the hashtags
We use a Regex for that

private static Regex regexHashTags = new Regex(@"#\w*", RegexOptions.IgnoreCase);

No more code, because that’s up to you how to do that

 

Put this hashtags into dictionary

Dictionary<string, int> 

(string is the hashtag, int is the count)
Easy, so no code here

 

Sort the Dictionary with LINQ

var sortedDict = (from entry in hashtagCountDict orderby entry.Value descending select entry);

 

The final output is easy again

Iterate through the sorted dictionary and throw it to the Console

image
Figure: Output of current Twitter buzz. Sharepoint is big currently (13/05/2009)
because of the TechEd announcements of Sharepoint 2010

 

Advanced steps

  1. Get the tweet updates every couple of seconds
  2. Use a   while (abortKeyNotPressed) {   }  with a Thread.Sleep to get the buzz every 1 minute
  3. Use Console KeyAvailable to abort application
  4. Use the space key to get the current state of the iteration
  5. Serialize current dictionary to file, and load that at startup
    Continue from last time

 

Thanks Robert Mühsig for VERY useful input http://code-inside.de/blog/2009/04/20/howto-twittern-mit-c/

How to: Take my ASP.NET 2.0 web app offline

Bad
After 4 years, (just today) I found a nice feature in ASP.NET from the year 2005!

Upload a file called “App_Offline.htm” to your web application root, to bring the whole application offline!
How easy is that!

Good
I never had to take one of my web applications offline
:-)

From Erik Porter (year 2005!!!)
http://weblogs.asp.net/eporter/archive/2005/10/05/426708.aspx

Latest Posts

Popular Posts