Previous month:
May 2011
Next month:
July 2011

June 2011

Integrating Twitter Feeds in Web Applications

After launching my Website now running with ASP.NET MVC3 instead of ASP.NET Web Forms I’ve been asked how a twitter feed can be integrated within a Web page. With ASP.NET Web Helpers this is really an easy task. This blog post demonstrates how the twitter feed can be integrated with ASP.NET Web Pages and also with ASP.NET Web Forms.

Twitter Feed with ASP.NET MVC

Let’s start with an ASP.NET MVC Project using Razor. After the project is created, the ASP.NET Web Helpers Library can be added to the project from the context menu Add Library Package Reference. From the Add Library Package Reference select the ASP.NET Web Helpers Library as shown in the screenshot.

image

Within the view where the twitter feed should be displayed, the Twitter API can be used as soon as the namespace Microsoft.Web.Helpers is imported.

The Profile method of the Twitter class is used to display the twitter feed. This method is defined using optional parameters as shown in the following screenshot. It’s just necessary to pass the twitter profile name, but it’s also possible to specify if the twitter feed should be continuously refreshed, the number of tweets to be shown, and the colors of the background, tweets, links…

image

The full code of the view to display the twitter feed is shown in these few lines.

1 @using Microsoft.Web.Helpers 2 @{ 3 ViewBag.Title = "Twitter Sample"; 4 } 5 6 <h2>Twitter Sample</h2> 7 8 @Twitter.Profile("ChristianNagel")

Running the application a nice formatted twitter feed is shown:

image

More Features from the Twitter Helper

Other than showing a profile, the Twitter class offers several other features. For example, it is possible to display a list from a user. The next figure shows my Formula 1 list.

1 @Twitter.List("christiannagel", "F1")

image

 

A search is possible as well. With the next sample I’m searching for tweets containing the tag for the Build Windows conference.

1 @Twitter.Search("#bldwin")

image

A follow me button can be done easily as well.

1 @Twitter.FollowButton("christiannagel")

image

A tweet button to tweet about something specific from a Webpage can also be placed on a site. The parameters of the TweetButton method can easily be understood with the information about the Tweet button on the twitter site.

Using this code

1 @Twitter.TweetButton(url: "http://www.cninnovation.com", 2 userName: "christiannagel", 3 tweetText: "attended a cool workshop")

shows this button

image

Clicking on the button the twitter dialog pops up:

image

Twitter Feed with ASP.NET Web Forms

If your are still running an ASP.NET Web Forms application, twitter feeds can be integrated as well. The library package reference with the ASP.NET Web Helpers Library can be added in a similar way to Web Forms as was done with ASP.NET MVC. However, as the library package dialog lists no dependencies for this item, there’s still a dependency. It’s just that ASP.NET Web Pages and ASP.NET MVC have referenced this dependency be default, with ASP.NET Web Forms it is necessary to add the assembly System.Web.WebPages to the project. Don’t forget to change the property to copy the assembly locally with the properties of the reference settings.

With the directives of the ASP.NET Web page, the namespace and assembly references can be added to use the Twitter class:

1 <%@ Assembly Name="Microsoft.Web.Helpers" %> 2 <%@ Assembly Name="System.Web.WebPages" %> 3 <%@ Import Namespace="Microsoft.Web.Helpers" %>

 

Now the Twitter class can be used within the ASP.NET Web Forms page in the same way you’ve seen it earlier.

1 <%= Twitter.Profile("christiannagel") %>

Summary

Web helper classes such as the Twitter class are a great extension to make it easier to create Web applications. The Twitter class defined with the ASP.NET Web Helpers library makes it easy to integrate with all the twitter features. And it can be used with all the Microsoft ASP.NET technologies such as ASP.NET MVC, ASP.NET Web Pages, and ASP.NET Web Forms.

More information in my trainings.

Christian

CN innovation


WPF ListBox as Bar Chart

A ListBox displays a list of items, and one (or more) item(s) can be selected. With WPF it’s possible to define a complete different look for ListBox elements. With templates items can be customized with a complete different look, and the ListBox itself can be customized with a control template. This way a ListBox can look like a bar chart. This article demonstrates changing the look of a ListBox to a bar chart.

Data Source

First data are needed. I’ve created a simple class that returns a list of numbers with the type IEnumerable<int>:

public class DataFactory { public IEnumerable<int> GetData() { return new int[] { 3, 5, 8, 6, 11, 7 }; } }

 

The class is instantiated by the ObjectDataProvider which invokes the method GetData to return the list of numbers.

<ObjectDataProvider x:Key="someData" ObjectType="{x:Type local:DataFactory}" MethodName="GetData" />

Binding the ListBox

A ListBox is bound to the data by setting the ItemsSource property, and defining the DataContext of a parent element from the ListBox.

<Grid DataContext="{Binding Source={StaticResource someData}}"> <ListBox ItemsSource="{Binding}" /> </Grid>

Running the application a default representation of the ListBox and its items is shown.

image

Item Template

To display the values as bars, a DataTemplate can be created. The template contains a red rectangle where the Width property is bound to the value returned from the collection item.

<DataTemplate x:Key="BarChartItemTemplate"> <Border Width="200" Height="50"> <Grid> <Rectangle Fill="Red" StrokeThickness="0" Height="40" Width="{Binding}" Margin="3" HorizontalAlignment="Right" VerticalAlignment="Bottom" /> </Grid> </Border> </DataTemplate>

With the ListBox, the ItemTemplate references the data template defined earlier.

<ListBox ItemsSource="{Binding}" ItemTemplate="{DynamicResource BarChartItemTemplate}" />

Running the application with its current state the rectangles are already visible as shown in the following figure. However, as the values returned from the collection are small, the rectangle has a small width.

image

To change the width of the rectangle based on the existing values returned from the collection it would be possible to use a converter. A converter class implements the interface IValueConverter and is configured with the binding. Another option – this one is used here – is to create a transformation. The rectangle is scaled by using a ScaleTransform setting ScaleX to 20 to scale the rectangle in x direction by 20.

<Rectangle Fill="Red" StrokeThickness="0" Height="40" Width="{Binding}" Margin="3" HorizontalAlignment="Right" VerticalAlignment="Bottom"> <Rectangle.LayoutTransform> <ScaleTransform ScaleX="20" /> </Rectangle.LayoutTransform> </Rectangle>

With this transformation the rectangles look better. With the configuration as it is now, the first values are on top of the ListBox, and the last items on bottom. A behavior that is usually expected with ListBox controls. However, using a bar chart display usually it looks better to arrange the values in a horizontal way, starting with the first value on the left. This is done next.

image

Rotating the Panel

To display the values horizontally within a bar chart the complete panel from the ListBox can be rotated. An ItemsPanelTemplate defines the panel for the items, and this is rotated by 90 degrees and scaled by –1 in the x direction to have the first items on the left side.

<ItemsPanelTemplate x:Key="BarChartItemsPanel"> <VirtualizingStackPanel IsItemsHost="True"> <VirtualizingStackPanel.LayoutTransform> <TransformGroup> <RotateTransform Angle="90" /> <ScaleTransform ScaleX="-1" ScaleY="1" /> </TransformGroup> </VirtualizingStackPanel.LayoutTransform> </VirtualizingStackPanel> </ItemsPanelTemplate>

With the ListBox control the ItemsPanelTemplate is assigned to the ItemsPanel property.

<ListBox ItemsSource="{Binding}" ItemTemplate="{DynamicResource BarChartItemTemplate}" ItemsPanel="{DynamicResource BarChartItemsPanel}" />

Running the application now, the items are displayed horizontally and the first items in the list are shown left.

image

Adding Values to the Display

If text values should be displayed in the ListBox as well beside the red rectangles, the ItemTemplate can be changed. Here, a TextBlock is added to the DataTemplate that binds the Text property to the same value as the Width property of the rectangle. As the TextBlock is in the same position of the grid as the rectangle it is just shown on top of it.

<DataTemplate x:Key="BarChartItemTemplate"> <Border Width="200" Height="50"> <Grid> <Rectangle Fill="Red" StrokeThickness="0" Height="40" Width="{Binding}" Margin="3" HorizontalAlignment="Right" VerticalAlignment="Bottom"> <Rectangle.LayoutTransform> <ScaleTransform ScaleX="20" /> </Rectangle.LayoutTransform> </Rectangle> <TextBlock Margin="20" FontWeight="Bold" HorizontalAlignment="Right" VerticalAlignment="Center" Text="{Binding}"> <TextBlock.LayoutTransform> <ScaleTransform ScaleX="-1" ScaleY="1" /> </TextBlock.LayoutTransform> </TextBlock> </Grid> </Border> </DataTemplate>

Now both the rectangles and the values are shown when running the application.

image

Does this look like a ListBox? It has the same functionality as a list box, just  different look. Using XAML it’s easy to change the look in any way.

More information on WPF and XAML in my workshops and in the book Professional C# 4 and .NET 4.

Christian

CN innovation


Filter Weekdays from a Date Range

Jalpesh p. Vadgama made an blog post for C# beginners to find Saturday, Sunday from a date range using a simple for loop and switch statements. I had a similar requirement where the implementation is more reusable that I like to share now. The code sample makes use of C# features such as extension methods, LINQ, the yield statement, and the params keyword.

Within Jalpesh’s code a for loop iterates through a date range by using the time span between the dates and a for loop to iterate until the number of dates is reached. Using the DayOfWeek property of the DateTime type the weekday was accessed, and with a switch statement.

Here is the new version. I’m creating an extension method to the DateTime type, so the method WeekdaysFromDateRange can be used directly with the DateTime type. fromDate and toDate are the first parameters on the method. The last parameter is an DayOfWeek array that with the params keyword allows passing any number of DayOfWeek values. Within the implementation of the method a while loop iterates through all dates up to the end date and checks by using the Contains extension method defined in the System.Linq namespace if the weekday is one of the required ones and if it is returns it with the yield return statement.

 

1 public static class DateTimeExtension 2 { 3 public static IEnumerable<DateTime> WeekdaysFromDateRange( 4 this DateTime fromDate, DateTime toDate, params DayOfWeek[] dayOfWeek) 5 { 6 DateTime date = fromDate; 7 while (date <= toDate) 8 { 9 if (dayOfWeek.Contains(date.DayOfWeek)) 10 yield return date; 11 date = date.AddDays(1); 12 } 13 } 14 }

This new method can now be used like a method from the DateTime types, passing an end date and any number of weekdays. In the sample code I’m passing DayOfWeek.Saturday and DayOfWeek.Sunday so that all Saturdays and Sundays are displayed within the foreach loop.

.
1 DateTime beginDate = new DateTime(2011, 3, 1); 2 DateTime endDate = new DateTime(2011, 6, 4); 3 foreach (var date in beginDate.WeekdaysFromDateRange( 4 endDate, DayOfWeek.Saturday, DayOfWeek.Sunday)) 5 { 6 Console.WriteLine("{0:D}", date); 7 }
Running the application the resulting dates are shown with the long date format.
image
More information on C# language features in my book Professional C# 4 and .NET 4 and in my C# Workshops.
Christian
CN innovation

Filter and Display Data with ASP.NET MVC (Part 2)–Partial Views and JQuery

In the previous blog post the sample to filter and display data with Formula 1 racers filtered by the country was started with ASP.NET MVC3. The first part created the model using the ADO.NET Entity Framework to map the Racers table to the Racer type, a controller to return filtered racers, and a view to display the racers. This article extends the example by adding a country selection and using JQuery to get the racers based on the selection.

DropDownList and ViewBag

First let’s start adding a controller method to display the countries of all racers. In the previous sample data was sent from the controller to the view by passing a model to the View method. This is one way of passing data to the view. Another way that is used here, is using ViewData or ViewBag properties of the ViewPage class. ViewData is of type ViewDataDictionary and allows assigning any object by using a dictionary key. ViewBag is new with MVC 3 and uses dynamic extensions to allow writing code without using the indexer syntax. For example, instead of writing ViewData[“Countries”], ViewBag.Countries can be used.

In the sample, a SelectList is assigned to ViewBag.Countries. SelectList is used to fill HTML select elements. SelectList is a collection of SelectListItem objects and has DataTextField and DataValueField properties to define what should be displayed in the select element, and what should be used as a value of the select element. In the sample, the SelectList is filled with a string list of unique countries.

public ViewResult Index() { var countries = new SelectList( db.Racers.Select(r => r.Country).Distinct().ToList()); ViewBag.Countries = countries; return View(); }

Within the view the HTML Helper method DropDownList can be used to create a select HTML element. The method DropDownList is defined with the class SelectExtensions. SelectExtensions defines extension methods to the HtmlHelper type for ListBox and DropDownList. The first paramter used with DropDownList defines a name and id for the HTML select element and also uses ViewData with the key of the first parameter (Countries) to display these data with option elements. The second parameter defines the option that is selected by default – in case it doesn’t exist this option is added.

<legend>Racers by Country</legend> <div> @Html.DropDownList("Countries", "select a country") </div>

Running the application the select element lists countries from all racers as shown in the following figure.

image

After the country is selected, the racers of the country should be displayed.

Partial View

With the previous blog post racers have been filtered based on a country by using an URL parameter route. Instead of building the same functionality within the page that contains the DropDownList it would make sense to make that functionality reusable. With ASP.NET MVC something like user controls can be created. With ASP.NET MVC the technology to render a part of a Web page is a partial view. According to that the action method within the controller returns a PartialViewResult that is created from the PartialView method:

public PartialViewResult RacersByCountryPartial(string id) { return PartialView( db.Racers.Where(r => r.Country == id).OrderByDescending(r => r.Wins) .ThenBy(r => r.Lastname).ToList()); }

The partial view that makes use of the model is defined in the view file RacersByCountryPartial.cshml. The implementation is the same as in the previous blog post just with the difference that here’s just the HTML part defined that goes into another HTML page.

@model IEnumerable<MvcDataQuery.Content.Racer> <table> <tr> <th> Firstname </th> <th> Lastname </th> <th> Country </th> <th> Starts </th> <th> Wins </th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.Firstname) </td> <td> @Html.DisplayFor(modelItem => item.Lastname) </td> <td> @Html.DisplayFor(modelItem => item.Country) </td> <td> @Html.DisplayFor(modelItem => item.Starts) </td> <td> @Html.DisplayFor(modelItem => item.Wins) </td> </tr> } </table>

A partial view can be rendered within a page by using the method RenderPartial. This method requires the action and model with the parameters. If the page itself has a model directive, the model can be passed to the partial action using ViewData.Model.

@{ Html.RenderPartial("RacersByCountryPartial", ViewData.Model); }

With the sample the action to request the partial page should be done from the client side using JavaScript when the selection of the select element changes. This is done in the next step.

Requesting Partial Views with JQuery

JQuery scripts are included with ASP.NET MVC by default. So now we’re making use of JQuery to request the partial view from the server.

First, empty div elements are defined that will be updated by JQuery calls.

<fieldset> <legend>Racers by Country</legend> <div> @Html.DropDownList("Countries", "select a country") </div> <br /> <div id="target"> </div> <div id="log"> </div> </fieldset>

Now let’s get into scripting. On the change event of the select element that lists the countries, the racers should be requested. The event handler can only be added after the DOM of the page is loaded.

$ is a shorthand alias for the jquery function. The first selector that is used is the document itself. The ready function binds a function that is invoked as soon as DOM of the page is ready to be used. The function that is invoked as soon as DOM is loaded searches for the element with the name Countries (using #Countries in the selector) and binds a function to the change event of that element.

<script type="text/javascript"> $(document).ready(function () { $("#Countries").change(function () { }); }); </script>

The function that is bound to the change event of the select element is invoked as soon as the selection is changed. Let’s implement this function. First we need to find the selected country. The variable countrySelected gets the current selection from the select element. $(“select option:selected”) finds the option elements inside the select element that have the selected attribute set to true. Because with a multi-selection select more than one items can be selected (which is not the case here), we need to get just one. The first() function just returns one element. text() gets the text value from this element, which is the selected country. $.get() makes an HTTP GET request. The first parameter of the requires the URL to be passed. The URL is generated from the server-side method Url.Action. This method returns the relative path to the controller where the parameter of the method is appended. With this sample it’s the Home controller and thus the relative path /Home/RacersByCountryPartial. The second parameter of the get function specifies key/value pairs that are sent to the server. Here the selected country retrieved from the select element is passed. The next parameter defines a function that is invoked as soon as the result from the HTTP GET request is returned. The selector looks for the div element with the target id, then the content of the div element is updated with the data returned from the GET request.

<script type="text/javascript"> $(document).ready(function () { $("#Countries").change(function () { var countrySelected = $("select option:selected").first().text(); $.get('@Url.Action("RacersByCountryPartial")', { id: countrySelected }, function (data) { $("#target").html(data); }); }); }); </script>

Of course the HTTP GET request to the server can fail. That’s why a function is attached in case an Ajax call fails. Within this function just a message box is shown to display the error.

<script type="text/javascript"> $(document).ready(function () { $("#Countries").change(function () { $("#log").ajaxError(function (event, jqxhr, settings, exception) { alert(exception); }); var countrySelected = $("select option:selected").first().text(); $.get('@Url.Action("RacersByCountryPartial")', { id: countrySelected }, function (data) { $("#target").html(data); }); }); }); </script>
Now the sample is ready to filter and display racers.  
image

This concludes the filter and query sample with ASP.NET MVC.

Summary

With ASP.NET MVC the server-side functionality is separated into controller, view, and model. This separation makes it easy to create unit tests. This is in contrast to the technology ASP.NET Web Pages that was shown earlier. ASP.NET Web Pages makes a mix of server-side code within client-side pages. ASP.NET Web Pages an serve as a starter, then it is easy to change into ASP.NET MVC by adding models and controllers, and changing the views accordingly.

ASP.NET MVC also full control over the client writing HTML code with JavaScript and JavaScript libraries such as JQuery. HTML Helper methods make it easy to generate HTML code.

ASP.NET MVC has a big difference compared to writing Web applications with ASP.NET Web Forms. Using ASP.NET Web Forms, Web applications can be written nearly without any HTML and JavaScript code. This makes it easy if a developer is coming from writing Windows Forms applications, but looses control over data sent across the network and performance both on the client- and the server side.

ASP.NET MVC gives full control over HTML and JavaScript. JQuery makes writing scripting code easier especially if you are used to writing Lambda expressions. Functionality behind the scene is written with well known .NET technologies. The MVC pattern makes unit testing a lot easier.

Christian

CN innovation

All the articles of this ASP.NET series

More information in my workshops


Windows 8 - HTML 5, JavaScript & Windows Azure

Now we’ve seen the cool user interface of Windows 8. And we’ve also heard first information on the new application model: “Web-connected and web-powered apps built using HTML5 and JavaScript have access to the power of the PC” [source: http://www.buildwindows.com/]. This is great news for Windows as I think there are a lot more HTML & JavaScript developers than .NET developers. Everyone can write applications for Windows.

What so far didn’t make it to the news, I think Windows 8 is a big win for Windows Azure. What are apps doing? Apps offer an UI for using services. Apps probably cache this data locally, make use of several sensors available with the new PCs…  I want to use data created by the apps from every device I have. I want to use the same apps on every device (maybe with different features depending on the device) accessing the same data. This is a job for Windows Azure. Client side apps connect to data storage, access services running in the cloud. The server-side part is written with … C#, C++, Visual Basic… making use of technologies like ADO.NET Entity Framework, Windows Communication Foundation, Windows Workflow Foundation…

Will be all client-side apps written with HTML & JavaScript? I guess, not. I wouldn’t write an application like Visual Studio with JavaScript. Visual Studio uses WPF for the UI. A few years ago there was a discussion on WPF versus Silverlight. Now there’s a discussion on Silverlight versus HTML. Silverlight might now have caught up to WPF, and it would be possible to write the UI of Visual Studio with Silverlight 6.

Microsoft always offered great interop scenarios. It’s possible to use WPF within C++ MFC applications, use WPF within Windows Forms, use ActiveX controls within WPF applications… I guess that there will be interop features with the new Windows 8 app-model for many different scenarios mixing WPF, HTML, MFC…Don’t expect some interop scenario for VB 6 Winking smile

Applications like Visual Studio will not be written with HTML and JavaScript – at least not with the next two editions. Windows 8 is the first step in a new world, and more steps will follow. Thousands of applications can make use of the new Windows 8 application model in a pure fashion.

Let’s see what the future brings. Can’t wait on working with the new application model.

Christian

http://www.cninnovation.com

More information on HTML 5, JavaScript, Windows Azure, and more in my workshops