Wednesday 22 October 2008

A Simple RSS Reader in WPF

I present here, a simple Rss reader written almost entirely in XAML. I personally find WPF Data binding powerful and exciting to work with.

To start with, i've used the XmlDataProvider class to hook up the source to an rss feed and set it's XPath property to "rss/channel/item", so that i get all items in the channel.

The layout is an utterly simple dockpanel which has a stackpanel docked to the top, a status bar docked to the bottom and a grid which fills up the remaining space.

The databinding is self explanatory with the following code.,However an important thing to note is that the <Textbox> which has the rss feed link is binded to the source directly. The 'UpdateSourceTrigger' property is by default set to LostFocus(). I've changed it to 'PropertyChanged', so that when a user enters an rss feed, the bindings get updated. Also notice that 'BindsDirectlyToSource' is set to True. Another interesting feature is the Master-Detail binding. Notice that between Line numbers 53-63. The listbox's selection is binded to  description and link which are textblocks inside a stack panel. Now, when the listbox gets focus, we bind the frame's source to the uri in the texbox.

I've added some styles to the listbox aswell. all of which could be found in the source code. This surely is very simple and yet a foundation to write a powerful rss reader in wpf. :)

We could add more rss feeds, write value converters, validation rules etc. as required.


Window1.xaml

   1: <Window x:Class="RssReader.Window1"


   2:     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"


   3:     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"


   4:     Title="RssReader" Height="600" Width="800">


   5:     


   6:     <Window.Resources>


   7:     <XmlDataProvider x:Key="rssdata"


   8:                      Source="http://newsrss.bbc.co.uk/rss/newsonline_uk_edition/front_page/rss.xml"


   9:                      XPath="rss/channel/item"/>


  10:         


  11:     </Window.Resources>


  12:     


  13:     <DockPanel   DataContext="{Binding Source={StaticResource rssdata}}">


  14:         <StackPanel DockPanel.Dock="Top"


  15:                     TextElement.FontWeight="Bold" Background="Gray">


  16:         


  17:             <TextBlock Text="{Binding XPath=./../title}"


  18:                     FontSize="20" Margin="10 10 10 0"/>


  19:             


  20:             <TextBlock Text="{Binding XPath=./../description}"


  21:                     FontSize="10" FontWeight="Normal" Margin="10 0"/>


  22:             


  23:             <TextBox Margin="5" Text="{Binding Source={StaticResource rssdata},                             


  24:                                 BindsDirectlyToSource=True,


  25:                                 Path=Source,


  26:                                 UpdateSourceTrigger=PropertyChanged}"/>


  27:         </StackPanel>


  28:  


  29:         <StatusBar DockPanel.Dock="Bottom">


  30:             <StatusBarItem Content="{Binding XPath=title}"/>


  31:             <Separator/>


  32:             <StatusBarItem Content="{Binding XPath=pubDate}"/>


  33:         </StatusBar>


  34:  


  35:         <Grid>


  36:             <Grid.ColumnDefinitions>


  37:                 <ColumnDefinition Width="25*"/>


  38:                 <ColumnDefinition Width="75*"/>


  39:                 <ColumnDefinition/>


  40:             </Grid.ColumnDefinitions>


  41:            


  42:             <ListBox Grid.Column="0" IsSynchronizedWithCurrentItem="True"                     


  43:                      ItemsSource="{Binding}" DisplayMemberPath="title"


  44:                      Style="{StaticResource ListBoxHand}"/>


  45:             <GridSplitter/>


  46:             


  47:             <Grid Grid.Column="1">


  48:                 <Grid.RowDefinitions>


  49:                     <RowDefinition Height="Auto"> </RowDefinition>


  50:                     <RowDefinition Height="85*"> </RowDefinition>


  51:                 </Grid.RowDefinitions>


  52:  


  53:                 <ListBox x:Name="selection" Grid.Row="0" IsSynchronizedWithCurrentItem="True"                         


  54:                          Style="{StaticResource SimpleListBox}"


  55:                          VerticalAlignment="Stretch"


  56:                          GotFocus="selection_GotFocus">


  57:                              


  58:                     <StackPanel>


  59:                             <TextBlock Text="{Binding XPath=description}" />


  60:                             <TextBlock x:Name="txtlink" Text="{Binding XPath=link}"/>


  61:                         </StackPanel>


  62:                 </ListBox>


  63:                     <Frame x:Name="Explorer" Grid.Row="1"/>


  64:             </Grid>


  65:         </Grid>


  66:  


  67:       </DockPanel>


  68:     </Window>


  69:  




Window1.xaml.cs





   1: private void selection_GotFocus(object sender, RoutedEventArgs e) {


   2:   Uri uri = new Uri(this.txtlink.Text.ToString());


   3:   this.Explorer.Source = uri;


   4: }


   5:   




Screenie



rssreader_wpf


C0d3 : here

Wednesday 15 October 2008

Silverlight 2 released! :)

Microsoft releases SL 2. The  press release can be found here. More details and specifications from the SL Developer team can be found here. Also, check out Visual Studio Tools for SL 2 and the sdk documentation.

SL 2 Highlights from the press release

.NET Framework support with a rich base class library. This is a compatible subset of the full .NET Framework.

Powerful built-in controls. These include DataGrid, ListBox, Slider, ScrollViewer, Calendar controls and more.

Advanced skinning and templating support. This makes it easy to customize the look and feel of an application.

Deep zoom. This enables unparalleled interactivity and navigation of ultrahigh resolution imagery.

Comprehensive networking support. Out-of-the-box support allows calling REST, WS*/SOAP, POX, RSS and standard HTTP services, enabling users to create applications that easily integrate with existing back-end systems.

Expanded .NET Framework language support. Unlike other runtimes, Silverlight 2 supports a variety of programming languages, including Visual Basic, C#, JavaScript, IronPython and IronRuby, making it easier for developers already familiar with one of these languages to repurpose their existing skill sets.

Advanced content protection. This now includes Silverlight DRM, powered by PlayReady, offering robust content protection for connected Silverlight experiences.

Improved server scalability and expanded advertiser support. This includes new streaming and progressive download capabilities, superior search engine optimization techniques, and next-generation in-stream advertising support.

Vibrant partner ecosystem. Visual Studio Industry Partners such as ComponentOne LLC, Infragistics Inc. and Telerik Inc. are providing products that further enhance developer capabilities when creating Silverlight applications using Visual Studio.

Cross-platform and cross-browser support. This includes support for Mac, Windows and Linux in Firefox, Safari and Windows Internet Explorer.

Tuesday 7 October 2008

Winforms vs WPF

We have two powerful technologies to build windows client applications. The obvious questions are

when to use which technology ?

Which technology to choose for new applications and when organizations developing Windows Forms applications should adopt WPF ?

Answers here

Quick conclusions from the same source.

  • If you have an existing Windows Forms application or are building a traditional forms-based application and are looking for a mature technology to use with mature tools and component support then Windows Forms is a good fit.
  •  

  • If you have an existing Windows Forms (or MFC/Win32) application that could benefit from some of the advanced presentation features of WPF, you can add WPF to your existing project.
  •  

  • If you’re wanting to create a new experience for your users that is rich, interactive, sophisticated, or highly custom or branded, WPF is Microsoft’s next-generation platform for your project today.
  •  

  • If you’re targeting the web, Silverlight shares the same development model as WPF but is optimized for a lightweight, cross-platform runtime. Investing in either WPF or Silverlight nets you the skills, tools, and assets for both platforms.
  • Monday 6 October 2008

    WCF Application Profiling

    1] Performance Profiling, MSDN

    2] WPF Graphics Rendering Overiew, MSDN

    3] Graphics Rendering Tiers, MSDN

    4] Windows Client Article on Performance profiling a WPF app.

    Compiling a Hello World WPF App

    Getting to know the Binary Application Markup Language and the ‘.g.cs ‘files

    XAML code gets compiled into a combination of  C# file (.g.cs) and a BAML (.baml). The BAML file is an optimized, pre-tokenized version of the elements that were specified in the .xaml file. This is injected into the .Net Assembly (PE/DLL).

    Notice that the static main method() gets generated in the App.g.cs file which points to an instance of WPF core application object (System.Windows.Application)

    /// <summary>
            /// Application Entry Point.
            /// </summary>
            [System.STAThreadAttribute()]
            [System.Diagnostics.DebuggerNonUserCodeAttribute()]
            public static void Main() {
                HelloWorld.App app = new HelloWorld.App();
                app.InitializeComponent();
                app.Run();
            }

    The MS build project file has the <ApplicationDefinition> tag which is used to specify the xaml file that defines the application class.(app.xaml) Below is a cut and paste from my HelloWorld.csproject file.

    <?xml version="1.0" encoding="utf-8"?>
    <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="
    http://schemas.microsoft.com/developer/msbuild/2003">
      <PropertyGroup>
        <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
        <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
        <ProductVersion>9.0.21022</ProductVersion>
        <SchemaVersion>2.0</SchemaVersion>
        <ProjectGuid>{15622594-2CE3-40D5-9D03-8A3F8AE7C3AB}</ProjectGuid>
        <OutputType>WinExe</OutputType>
        <AppDesignerFolder>Properties</AppDesignerFolder>
        <RootNamespace>HelloWorld</RootNamespace>
        <AssemblyName>HelloWorld</AssemblyName>
        <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
        <FileAlignment>512</FileAlignment>
        <ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
        <WarningLevel>4</WarningLevel>
        <StartupObject>HelloWorld.App</StartupObject>
      </PropertyGroup>
      <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
        <DebugSymbols>true</DebugSymbols>
        <DebugType>full</DebugType>
        <Optimize>false</Optimize>
        <OutputPath>bin\Debug\</OutputPath>
        <DefineConstants>DEBUG;TRACE</DefineConstants>
        <ErrorReport>prompt</ErrorReport>
        <WarningLevel>4</WarningLevel>
      </PropertyGroup>
      <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
        <DebugType>pdbonly</DebugType>
        <Optimize>true</Optimize>
        <OutputPath>bin\Release\</OutputPath>
        <DefineConstants>TRACE</DefineConstants>
        <ErrorReport>prompt</ErrorReport>
        <WarningLevel>4</WarningLevel>
      </PropertyGroup>
      <ItemGroup>
        <Reference Include="System" />
        <Reference Include="System.Core">
          <RequiredTargetFramework>3.5</RequiredTargetFramework>
        </Reference>
        <Reference Include="System.Xml.Linq">
          <RequiredTargetFramework>3.5</RequiredTargetFramework>
        </Reference>
        <Reference Include="System.Data.DataSetExtensions">
          <RequiredTargetFramework>3.5</RequiredTargetFramework>
        </Reference>
        <Reference Include="System.Data" />
        <Reference Include="System.Xml" />
        <Reference Include="WindowsBase" />
        <Reference Include="PresentationCore" />
        <Reference Include="PresentationFramework" />
      </ItemGroup>
      <ItemGroup>
        <ApplicationDefinition Include="App.xaml">
          <Generator>MSBuild:Compile</Generator>
          <SubType>Designer</SubType>
        </ApplicationDefinition>
        <Page Include="Window1.xaml">
          <Generator>MSBuild:Compile</Generator>
          <SubType>Designer</SubType>
        </Page>
        <Compile Include="App.xaml.cs">
          <DependentUpon>App.xaml</DependentUpon>
          <SubType>Code</SubType>
        </Compile>
        <Compile Include="Window1.xaml.cs">
          <DependentUpon>Window1.xaml</DependentUpon>
          <SubType>Code</SubType>
        </Compile>
      </ItemGroup>
      <ItemGroup>
        <Compile Include="Properties\AssemblyInfo.cs">
          <SubType>Code</SubType>
        </Compile>
        <Compile Include="Properties\Resources.Designer.cs">
          <AutoGen>True</AutoGen>
          <DesignTime>True</DesignTime>
          <DependentUpon>Resources.resx</DependentUpon>
        </Compile>
        <Compile Include="Properties\Settings.Designer.cs">
          <AutoGen>True</AutoGen>
          <DependentUpon>Settings.settings</DependentUpon>
          <DesignTimeSharedInput>True</DesignTimeSharedInput>
        </Compile>
        <Compile Include="Test.cs" />
        <EmbeddedResource Include="Properties\Resources.resx">
          <Generator>ResXFileCodeGenerator</Generator>
          <LastGenOutput>Resources.Designer.cs</LastGenOutput>
          <SubType>Designer</SubType>
        </EmbeddedResource>
        <None Include="Properties\Settings.settings">
          <Generator>SettingsSingleFileGenerator</Generator>
          <LastGenOutput>Settings.Designer.cs</LastGenOutput>
        </None>
        <AppDesigner Include="Properties\" />
      </ItemGroup>
      <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
      <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
           Other similar extension points exist, see Microsoft.Common.targets.
      <Target Name="BeforeBuild">
      </Target>
      <Target Name="AfterBuild">
      </Target>
      -->
    </Project>

    Now, the combination of <ApplicationDefinition> element and the <Import> tag ‘Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets"’ will create our application entry point.

     

    My ‘App.xaml’ file

    <Application x:Class="HelloWorld.App"
        xmlns="
    http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Startup="Application_Startup"
        StartupUri="Window1.xaml">   
        <Application.Resources>
        </Application.Resources>
    </Application>

     

    Notice the StartUp tag here. The connection between XAML and the code behind can be found in the file ‘App.g.cs’

     

    /// <summary>
    /// InitializeComponent
    /// </summary>
    [System.Diagnostics.DebuggerNonUserCodeAttribute()]
    public void InitializeComponent() {
        #line 4 "..\..\App.xaml"
        this.Startup += new System.Windows.StartupEventHandler(this.Application_Startup);
        #line default
        #line hidden
        #line 5 "..\..\App.xaml"
        this.StartupUri = new System.Uri("Window1.xaml", System.UriKind.Relative);
        #line default
        #line hidden
    }

    Now, we are sure that ‘App.g.cs’ has a significant role in bridging the event handlers specified in the XAML file to the code behind files (c# files). Since ‘App.g.cs’ is a partical class, may be visual studio uses it for Intellisense.  This is not all ?, Where does the XAML file go after the compilation process ?. Notice that if you navigate to .\obj\debug or .obj\release folders you find a Window1.baml file. Now, as i’ve already said before, BAML is an optimized version of XAML.

    I found this explanation on the web [1] , dumping the content here.

    What tools are used to generate the .G.CS classes when a XAML project is created? Also is there an API for this so I can do it at runtime?

    The answer:

    In order to compile xaml files, we have declared a few MsBuild tasks in PresentationBuildTasks.dll. Projects that contain <Page Include="Page1.xaml" /> and that import MicrosoftWinFX.targets will be markup compiled.There are 2 "Targets" defined in that targets file that do the work for markup compilation. MarkupCompilePass1 – creates a .g.cs file for each Page.  If the xaml doesn't refer to any classes defined in the assembly being created during the build, a baml file is created. This baml file is a binary (pre-tokenized) version of the hierarchy of objects and property sets from the xaml file. MarkupCompilePass2 – creates all baml files that weren't able to be created in Pass1

    The only APIs that WPF exposes to do this markup compilation are those msbuild based tasks in PresentationBuildTasks.dll.MsBuild can be called at runtime (from full trust apps).

     

    Check out [2] for more on BAML and .net assembly. If you are thinking of writing your own UI representation like YAML etc, then you might need the BAML Reader/Writer [3].

     

    Some Links to understand what’s going on beneath the hood.

    1. Rrelyes, MS

    2. A nice little anatomy of a wpf compilation here

    3. BAML Reader/Writer

    Indian Bands

     

    Parikrama - Delhi - Rock n Roll (They opened for Iron Maiden in Bangalore. They were fantastic. Iron Maiden was impressed and promoted them to play in Download Festival 2007.

     

     

    AVIAL - Kerala (Rock / Progressive)

     

    VINAPRA - Bangalore (Rock)

    Dilbert

     

     2

    3

    6 

    7

    Sunday 5 October 2008

    Vatsa's Viewpoint

    My friend vatsa's flickr pics. Really good photographer.

    Mind the copyright on the pics !

    Industrial Design

     

    If you ever wondered what's Common in  iPod, iPhone , MAC OS, Nintendo Wii and some of Google's simpler User Interfaces, It's the industrial design.

    Watch this video from Buxton , delivered at Mix08 UK. This is mind blowing stuff. Also check out his research page and a book on Industrial design.

    Some quick notes..

    1] Where the heck is your designer ?

    CEO

    CTO

    VP Sales

    VP Engineering

    VP Marketing ..

    ? (Where is the designer). Turns out that when Steve Jobs joined apple, within 24 hours,i.e on the very first day, he met the finance, marketing and the whole engineering team and already had a vision. 2 words . of course, It was 'industrial design'. And now you see the results.

    shuffle

    nano

    IPod

    IPhone

    MacBookAir

     

    An industrial designer is a huge asset to a product company. A guy who knows or rather have to know everything from design concepts to business awareness and usability. Buxton argues that if you don't understand it and your still in business, then probably  you are lucky or your competitors are pathetic.

    Another important lesson to learn from Apple is the wide spectrum of things they focus on starting from Industrial design and including every single bit that you can possibly think of. (promotions, marketing, sales, shipping, support, user feedback) The elegant little 'shuffle' which happily resides on millions of shirts across the world is an example.

    iphone and ipod's cover flow

    coverflow_IPhone

    Think about it.

    Creative design { academic research , enterprise research } ->Vision

    Vision { Business awareness } -> Concept

    Concept -> Product

     

    2] Innovation

    Nintendo Wii

    wii1

     wii

    2] Not everyone can be a designer ( but almost everyone you work with thinks that they are!)

    3] Atleast, an engineer with depth in business and depth in design ~= Industrial Designer

    4] Can you sketch the UI of your phone in 15 seconds ?

    5] Architecture and design of a BUILDING

    vs

    Architecture and design of a Software Product

    Where is the analogy ?. Why can't we learn from them ?

    Buxton argues that software be blue printed and planned before constructing.(This is where the industrial designer comes into picture). I kinda disagree on this one.

    Personally, i think the only important reason why software industry is cost effective compared to manufacturing industries would be the magical world        're-usability'. Again, consider a production pipeline of cars vs software. A badly designed car can incur losses to a company, So does a badly designed software product. But can we use the car's carburetor again ? NO! (may be the design, but the physical component is out there with the user)

    How about software ? YES!!!, throw away the bad components, reuse the carburetor component, may be a couple more of them.

    " General Industrial Designers are a cross between an engineer and an artist. They study both 'function' and 'form', and the connection between product and the user. They do not design the gears or motors that make machines move, or the circuits that control the movement, but they can affect technical aspects through usability design and form relationships. And usually, they partner with engineers and marketers, to identify and fulfill needs, wants and expectations " - wiki

    One such guy i can relate to immediately is Jayanth. happens to be a inspiration and a very good friend of mine. (Jayanth Kannan, Raptor Entertainment)

    "Product design and industrial design can overlap into the fields of user interface design, information design and interaction design. Various schools of industrial design and/or product design may specialize in one of these aspects, ranging from pure art colleges (product styling) to mixed programs of engineering and design, to related disciplines like exhibit design and interior design, to schools where aesthetic design is almost completely subordinated to concerns of function and ergonomics of use (the so-called functionalist school)." - wiki

    More Links,

    A new mantra for creativity - Bill Buxton, Business Week.

    Now, Should i say coincidence!

    dilby_button