Você está pronto para o HTML 5 ?

 

Quem acompanhou o começo da web deve lembrar do quanto as primeiras páginas eram feias. O design de páginas com HTML puro era cinza, quadradão, feito na base de frames e tabelas, as animações eram arquivos GIF toscos e restava ao webmaster fazer graça com scripts inúteis. Nesses últimos anos, vários padrões e tecnologias surgiram para ajudar a linguagem, como o CSS, o Flash e o XHTML. Mesmo assim, chegou a hora de mais mudança. A nova versão do padrão HTML está mais sólida, com os principais navegadores suportando suas inovações e facilitando assim a vida do designer, que poderá dispensar bibliotecas e pacotes auxiliares.

Vale lembrar que nem tudo funciona em todos os browsers, já que, na falta de uma especificação definitiva (que está prevista para 2012), os empresas adicionam os recursos do HTML 5 nos navegadores a conta-gotas. Conheça, a seguir, as principais mudanças que já estão aprovadas pela W3C e pelo WHATWG, as entidades que decidem o futuro da linguagem HTML.

Multimídia sem plug-in

O conteúdo em áudio e vídeo na web é refém dos plug-ins, como o Flash, para ser exibido. O HTML 5 prevê uma forma de contornar isso com as tags <video> e <:audio>. Falta ainda definir os tipos de codecs a ser utilizados universalmente com essas tags. Hoje, Chrome e Safari conseguem exibir filmes em H.264 e tocar áudio AAC, encapsulados num arquivo MP4. Já o Firefox, fiel aos padrões abertos, mostra só vídeos Theora e som Vorbis, dentro de um arquivo Ogg. O impasse não preocupa tanto, pois as tags <video> e <:audio> podem receber mais de um arquivo, com o browser selecionando qual é a opção compatível. Para adicionar um vídeo à página, basta usar o código:

<video src="meuvideo.mp4 width="320" height="240" controls></video>

CSS arrumadinho

O novo HTML promete aposentar frames e tabelas das páginas, com o CSS efetivado como responsável para esse fim. Além disso, a versão 5 conta com tags para definir seções dos sites, facilitando a integração com as folhas de estilo. Atualmente, o normal é usar um elemento <div>, com seu nome indicando o tipo de seção. As novas tags são <header>, <footer>, <article>, <section>, <nav> e <aside>. Elas definem o cabeçalho, o rodapé, um artigo, uma seção (de um artigo), a barra de navegação e anotações sobre o conteúdo. Com esses elementos, é criada uma padronização que facilita a localização de conteúdo pelos buscadores e o reaproveitamento dos arquivos CSS.

Gráficos nascidos na web

O elemento <canvas> permite criar desenhos usando JavaScript. Assim é possível, por exemplo, transformar dados do site em gráficos dinâmicos. A tag também serve para usar um texto ou imagem como substituto do desenho, caso o browser não tenha suporte aos gráficos dinâmicos. Nesse caso, o conteúdo alternativo fica entre e <canvas> e </canvas>.

Calendários sem erro

Qual é a data definida por 10/2/2010? Pode ser 10 de fevereiro, no padrão usado no Brasil, e, ao mesmo tempo, 2 de outubro, no modelo americano. O HTML 5 pode contornar essas situações com tags que definem o tipo de dados e sua formatação no texto da página web. A tag <time> marca hora e data e evitaria o problema descrito acima usando o código <timedatetime=”2010-02-10″> </time>, que poderia identificar as informações do navegador e decidir qual seria a data correta, para que ela possa ser exibida no padrão do usuário.

Versão offline

Já ouviu falar no Google Gears? Ele transforma aplicativos web em programas que rodam no browser mesmo em máquinas sem conexão com a web. Essa mágica é feita pelo recurso DOM Storage, que poderá ser usado por qualquer site em HTML 5. Um ponto essencial dessa forma de armazenamento local é que o servidor remoto não pode acessar diretamente o conteúdo (diferentemente dos cookies). Somente o browser e os scripts da página acessada podem modificar o conteúdo offline. Hoje, cada browser usa um limite de espaço. O Firefox aloca no máximo 5 MB por domínio web acessado. Já o Internet Explorer libera 10 MB por base de dados criada, independentemente do domínio.

Muito além dos cliques

Existem várias bibliotecas para habilitar o suporte ao recurso de arrastar e soltar objetos em sites. Mas no HTML 5 a coisa fica bem mais fácil. Basta definir valores para três eventos em JavaScript: dragenter, dragover e drop. Eles indicam, respectivamente, a entrada e a passagem de um elemento sobre outro, além do evento para o momento em que um item é solto. Definir um elemento da página como item que pode ser arrastado é mais fácil ainda. Basta adicionar a definição draggable=”true” a ele.

Fonte: Info

Comentário: O HTML 5 vem pra reorganizar o festival de TAGs que são utilizadas hoje para exibir vídeos, animações ou personalizar nosso layout, criadas a partir da evolução da Internet. Creio que a nova linguagem vai ajudar e muito os desenvolvedores e novatos a criarem seus sites mais facilmente e ao mesmo tempo compatível com a maioria dos navegadores (isto se os usuários atualizarem suas máquinas). 

Anúncios

Sample Data in the WPF and Silverlight Designer

Objective

Requirements

Retail release of Visual Studio 2010 and the latest Silverlight 4 tools for Visual Studio 2010.

Table of Contents

  1. Background
  2. Faux Types and Real Types
  3. Images in Sample Data Files
  4. Adding New Sample Data File
  5. Consuming Sample Data File
  6. WPF Sample Data Scenarios
  7. Silverlight Sample Data Scenarios
  8. WCF RIA Services Sample Data Scenario
  9. Choosing Sample Data Loading Technique
  10. Comments

Background 

Cider and Blend 4

Developers using a visual Designer use sample data to light up their UI at design-time; to cause the Designer to render like it will at run-time. This time saving feature is especially important when designing DataTemplates or adjusting the layout of a DataGrid since the developer will not have to actually run the application to see what it will render like with data.

Sample data in Cider and Blend is easy to understand and wire up.

Sample data files are XAML files. Each sample data file contains one or more instances of user type’s instantiated in XAML. The XAML sample data file and resulting instances of data are connected to the UI using the d:DesignData MarkupExtension. d:DesignData can be applied to a data source declared in XAML like a CollectionViewSource, DomainDataSource or can be assigned to a d:DataContext property.

Each sample data file has an associated Build Action that determines if d:DesignData will create actual instances of the types in the sample data file or if faux types will be created. Faux types are necessary when the types in the sample data file are not creatable or if read-only properties need to be populated with sample data values.

Blend 4

Blend has tooling to create and modify XAML sample data for a class. Blend also provides a sample data drag and drop experience to wire up the d:DataContext and appropriate properties.

Blend provides an additional feature that enables creating XML sample data on the fly without a predefined class. The XML sample data can then be easily be configured and modified. This XML sample data only works in Blend.

To learn more about Blend please see the Expression Blend Blog, Unni’s Blog, Kirupa’s Blog or Christian Schormann’s Blog.

Faux Types and Real Types 

The term faux type is used in this document to indicate that a cloned type will be created instead of your actual type. Benefits of faux types include the ability to create an otherwise non-creatable type in sample data, the ability to set read-only properties in sample data and the by-passing of code in the real type’s constructor.

When using real types in sample data, be aware that any code in the type’s constructor will be executed at design-time. For an entity object this would not normally be an issue, but if the real type is a ViewModel, the code in that ViewModel’s constructor will be executed. If that constructor’s code loads data from a database for example, problems could occur in the Designer when the sample data is loaded. User code running at design-time is responsible for over 20% of all Designer load failures. You can read up on running code in a constructor in this blog post.

Images in Sample Data Files 

WPF Sample Data Files Only

If the image is part of the project, it can be referenced using the below relative folder syntax.

<m:Customer FirstName="Alfons" LastName="Parovszky" Photo="../Images/image01.png">

WPF and Silverlight Sample Data Files

All images in Silverlight sample data files require the pack syntax. WPF projects must use this syntax if the image is located in another assembly:

<m:Customer FirstName="Alfons" LastName="Parovszky" 
            Photo="/SLSampleDataScenarios;component/Images/image01.png">

 

If the image is not part of any project, you can use the below file:/// URI syntax to use an image in a sample data file.

<m:Customer FirstName="Alfons" LastName="Parovszky" 
            Photo="file:///c:/Images/markbou.jpg">

Adding New Sample Data File 

The following applies to both WPF and Silverlight applications.

  • Add a new ResourceDictionary or Text File to the project.
    • If ResourceDictionary delete the default file content.
    • If Text File, change file extension to .xaml
  • Using the file properties, set build action to either:
    • DesignData – will create faux types
    • DesignDataWithDesignTimeCreatableTypes – will create actual types
  • Using the file properties, set Copy to Output Directory to: Do not copy
  • Using the file properties, set Custom Tool:  <blank>
  • Using XAML Editor add your sample data content to the file.

Sample Data File Properties

Single Instance Sample Data Example

<m:Customer 
    xmlns:m="clr-namespace:SampleDataScenarios.Model" 
    FirstName="Alfons" LastName="Parovszky" 
    Photo="../Images/image01.png">
</m:Customer>

Multiple Instance Sample Data Example

<m:Customers xmlns:m="clr-namespace:SampleDataScenarios.Model">
    <m:Customer FirstName="Alfons" LastName="Parovszky" Photo="../Images/image01.png">
        <m:Customer.Addresses>
            <m:Address LineOne="125 North St" City="Greatville" State="CA" Zip="98004" />
            <m:Address LineOne="3000 1st St NE" City="Coolville" State="CA" Zip="98004" />
        </m:Customer.Addresses>
    </m:Customer>
    <m:Customer FirstName="Lori" LastName="Penor" Photo="../Images/image02.png">
        <m:Customer.Addresses>
            <m:Address LineOne="126 East St" City="Greatville" State="CA" Zip="98004" />
            <m:Address LineOne="3001 2st St NE" City="Coolville" State="CA" Zip="98004" />
        </m:Customer.Addresses>
    </m:Customer>
    <m:Customer FirstName="Justin" LastName="Harrison" Photo="../Images/image03.png">
        <m:Customer.Addresses>
            <m:Address LineOne="127 West St" City="Greatville" State="CA" Zip="98004" />
            <m:Address LineOne="3002 3st St NE" City="Coolville" State="CA" Zip="98004" />
        </m:Customer.Addresses>
    </m:Customer>
</m:Customers>

WPF Supported Sample Data File Scenarios

For sample data files where the root object is a single instance, simply add the type to the sample data file as done in Single Instance Sample Data Example above.

For collections, the root object can be an ArrayList or a custom type that derives from a collection or generic collection as done in Multiple Instance Sample Data Example above. Notice that WPF can also use the same technique as outlined below in Silverlight Scenarios. The Multiple Instance Sample Data Example uses the below DesignSampleDataCollection class as the root instead of an ArrayList.

Silverlight Supported Sample Data File Scenarios

For sample data files where the root object is a single instance, simply add the type to the sample data file as done in Single Instance Sample Data Example above.

For collections, the root object must be a type that derives from a collection or generic collection.

Non-WCF RIA Services Scenario

If the project does not have a collection object for the desired root type and the type does not derive from the RIA Services Entity object, you need to create a generic reusable collection like the below DesignSampleDataCollection.

C#

namespace SampleDataScenarios.Model {
  public class DesignTimeSampleDataCollection : List<Object> {

    public DesignTimeSampleDataCollection() { }
  }
}

VB.NET

Public Class DesignTimeSampleDataCollection
  Inherits List(Of Object)

  Public Sub New()

  End Sub

End Class

WCF RIA Services Scenario

If the project does not have a collection object for the desired root type and the type derives from the RIA Services Entity object, you need to create a generic reusable collection like the below DesignRIAEntitySampleDataCollection.

namespace ContosoSales.SampleData {
    public class DesignRIAEntitySampleDataCollection : 
          List<System.ServiceModel.DomainServices.Client.Entity> {

        public DesignRIAEntitySampleDataCollection() { }
    }
}

Consuming Sample Data File 

The d:DesignData Markup Extension assumes the role of a sample data file loader and parser that provides instantiated or faux types to the consumer.

Sample Data Consumers

The following design-time properties can consume the sample data provided by d:DesignData:

  • d:DataContext can be set on any FrameworkElement
  • d:DesignSource can be set on a CollectionViewSource
  • d:DesignData can be set on a DomainDataContext (RIA Services data object)

WPF Sample Data Scenarios 

Open either solution: CS-SampleDataScenarios or VB-SampleDataScenarios.

Rebuild solution.

The WPF samples are in the SampleDataScenarios project.

Demo-01 Single Customer

Open Demo01SingleCustomer.xaml.

This is an example of a single instance sample data file consumed by a form. The single instance of Customer has 2 instances of Address.

<m:Customer 
    xmlns:m="clr-namespace:SampleDataScenarios.Model" 
    FirstName="Alfons" LastName="Parovszky" 
    Photo="../Images/image01.png">
    <m:Customer.Addresses>
        <m:Address LineOne="125 North St" City="Greatville" State="CA" Zip="98004" />
        <m:Address LineOne="3000 1st St NE" City="Coolville" State="CA" Zip="98004" />
    </m:Customer.Addresses>
</m:Customer>

In the below form, the Customer type is available in the root Grid’s DataContext. This is important because the presence of d:DesignData and sample data not only feeds the DataContext to render data, but also enables the Designer tooling for creating and editing bindings using the Binding Builder.

Connecting Sample Data

In the below XAML the CustomerSampleData.xaml file is loaded and parsed by the d:DesignData Markup Extension and assigned to the d:DataContext for the Grid. Child controls of the Grid can data bind to properties on the DataContext and the Designer Binding Builder tooling is enabled.

<Grid d:DataContext="{d:DesignData Source=/SampleData/CustomerSampleData.xaml}">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>

    <TextBlock Text="Demo-01 Single Customer" Grid.ColumnSpan="2" FontWeight="Bold" FontSize="14" Margin="11" />

    <Grid Grid.Row="1" Margin="6">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>

        <TextBlock Text="First Name:" VerticalAlignment="Center" Width="75" />
        <TextBox Text="{Binding Path=FirstName}" VerticalAlignment="Center" Grid.Column="1"/>

        <TextBlock Text="Last Name:" VerticalAlignment="Center" Width="75" Grid.Row="1" />
        <TextBox Text="{Binding Path=LastName}" VerticalAlignment="Center" Grid.Row="1" Grid.Column="1" />

        <TextBlock Text="Ranking:" VerticalAlignment="Center" Width="75" Grid.Row="2" />
        <TextBlock Text="{Binding Path=Ranking}" VerticalAlignment="Center"  Grid.Row="2" Grid.Column="1" />

        <TextBlock Margin="7" Text="Addresses" FontWeight="Bold" Grid.Row="3" Grid.ColumnSpan="2" />

        <ListBox ItemsSource="{Binding Path=Addresses}" Grid.Row="4" Grid.ColumnSpan="2">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="100" />
                            <ColumnDefinition Width="75" />
                            <ColumnDefinition Width="30" />
                            <ColumnDefinition Width="Auto" />
                        </Grid.ColumnDefinitions>
                        <TextBlock Text="{Binding Path=LineOne}" />
                        <TextBlock Text="{Binding Path=City}" Grid.Column="1" />
                        <TextBlock Text="{Binding Path=State}" Grid.Column="2" />
                        <TextBlock Text="{Binding Path=Zip}" Grid.Column="3" />
                    </Grid>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

    </Grid>

    <Image VerticalAlignment="Top" Source="{Binding Path=Photo}" Grid.Row="1" Grid.Column="1" Margin="6" />
</Grid>

Demo-02 Single Not Creatable Customer

Open Demo02SingleNotCreatableCustomer.xaml and NotCreatableCustomer.cs.

This is an example of a single instance sample data file where the entity object is not creatable. The NotCreatableCustomer class has a private constructor. The single instance of NotCreatableCustomer has 2 instances of Address.

Non-creatable types are common scenario in .NET, making this feature a very important addition to the Designer tooling. For example, RIA Services Entity types or types that are created by factories cannot be instantiated. Without this feature sample data would not work and the Designer tooling would be unable to provide DataContext and property name lists for a type.

Important
Sample data files that contain non-creatable types must have their Build Action set to: DesignData and not DesignDataWithDesignTimeCreatableTypes.
<m:Customer 
    xmlns:m="clr-namespace:SampleDataScenarios.Model" 
    FirstName="Alfons" LastName="Parovszky" 
    Photo="../Images/image01.png" Ranking="101">
    <m:Customer.Addresses>
        <m:Address LineOne="125 North St" City="Greatville" State="CA" Zip="98004" />
        <m:Address LineOne="3000 1st St NE" City="Coolville" State="CA" Zip="98004" />
    </m:Customer.Addresses>
</m:Customer>

In the below form, the NotCreatableCustomer type is available in the root Grid’s DataContext. Again, even though the NotCreatableCustomer type has a private constructor the sample data displays and the Binding Builder works normally.

Connecting Sample Data

In the below XAML the NotCreatableCustomerSampleData.xaml file is loaded and parsed by the d:DesignData Markup Extension and assigned to the d:DataContext for the Grid. Child controls of the Grid can data bind to properties on the DataContext and the Designer Binding Builder tooling is enabled.

<Grid d:DataContext="{d:DesignData Source=/SampleData/NotCreatableCustomerSampleData.xaml}">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>

    <TextBlock Text="Demo-02 Single Not Creatable Customer" Grid.ColumnSpan="2" FontWeight="Bold" FontSize="14" Margin="11" />

    <Grid Grid.Row="1" Margin="6">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>

        <TextBlock Text="First Name:" VerticalAlignment="Center" Width="75" />
        <TextBox Text="{Binding Path=FirstName}" VerticalAlignment="Center" Grid.Column="1"/>

        <TextBlock Text="Last Name:" VerticalAlignment="Center" Width="75" Grid.Row="1" />
        <TextBox Text="{Binding Path=LastName}" VerticalAlignment="Center" Grid.Row="1" Grid.Column="1" />

        <TextBlock Text="Ranking:" VerticalAlignment="Center" Width="75" Grid.Row="2" />
        <TextBlock Text="{Binding Path=Ranking}" VerticalAlignment="Center"  Grid.Row="2" Grid.Column="1" />

        <TextBlock Margin="7" Text="Addresses" FontWeight="Bold" Grid.Row="3" Grid.ColumnSpan="2" />

        <ListBox ItemsSource="{Binding Path=Addresses}" Grid.Row="4" Grid.ColumnSpan="2">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="100" />
                            <ColumnDefinition Width="75" />
                            <ColumnDefinition Width="30" />
                            <ColumnDefinition Width="Auto" />
                        </Grid.ColumnDefinitions>
                        <TextBlock Text="{Binding Path=LineOne}" />
                        <TextBlock Text="{Binding Path=City}" Grid.Column="1" />
                        <TextBlock Text="{Binding Path=State}" Grid.Column="2" />
                        <TextBlock Text="{Binding Path=Zip}" Grid.Column="3" />
                    </Grid>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

    </Grid>

    <Image VerticalAlignment="Top" Source="{Binding Path=Photo}" Grid.Row="1" Grid.Column="1" Margin="3" />
</Grid>

Demo-03 Customer ViewModel

Open Demo03CustomerViewModel.xaml.

This is an example of using a design-time ViewModel as the d:DataContext. DesignTimeCustomerViewModel derives from CustomerViewModel. In its constructor it populates the ViewModel properties and collection. Since the DesignTimeCustomerViewModel’s properties are populated, they are rendered on the design surface.

The below code demonstrates creating sample data instead of using the typical sample data XAML file.

C#

namespace SampleDataScenarios.ViewModel {
  public class DesignTimeCustomerViewModel : CustomerViewModel {

    public DesignTimeCustomerViewModel()
      : base() {

      base.Customer = new Customer() {
        FirstName = "Alfons", LastName = "Parovszky", Photo = "../Images/image01.png"
      };
      base.Customer.CalculateRank();
      base.Customer.Addresses.Add(
          new Address() { LineOne = "125 North St", City = "Greatville", State = "CA", Zip = "98004" });
      base.Customer.Addresses.Add(
          new Address() { LineOne = "3000 1st St NE", City = "Coolville", State = "CA", Zip = "98004" });
    }
  }
}

VB.NET

Public Class DesignTimeCustomerViewModel
  Inherits CustomerViewModel

  Public Sub New()
    MyBase.New()

    MyBase.Customer = New Customer With {.FirstName = "Alfons", .LastName = "Parovszky", .Photo = "../Images/image01.png"}
    MyBase.Customer.CalculateRank()
    MyBase.Customer.Addresses.Add(New Address With {.LineOne = "125 North St", .City = "Greatville", .State = "CA", .Zip = "98004"})
    MyBase.Customer.Addresses.Add(New Address With {.LineOne = "3000 1st St NE", .City = "Coolville", .State = "CA", .Zip = "98004"})

  End Sub

End Class

Connecting Sample Data

The below XAML demonstrates using d:DesignInstance with IsDesignTimeCreatable set to true to have Visual Studio instantiate DesignTimeCustomerViewModel and assign the instance as the d:DataContext. Since the instantiated instance has properties populated with data, that data will render exactly like other XAML file sample data in the Designer. This works because the DesignTimeCustomerViewModel is creatable at design-time and the below DesignInstance has IsDesignTimeCreatable set to true. Child controls of the Grid can data bind to properties on the DataContext and the Designer Binding Builder tooling is enabled.

<Grid d:DataContext="{d:DesignInstance vm:DesignTimeCustomerViewModel, IsDesignTimeCreatable=True}">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>

    <TextBlock Text="{Binding Path=FormTitle}" Grid.ColumnSpan="2" FontWeight="Bold" FontSize="14" Margin="11" />

    <Grid Grid.Row="1" Margin="6" DataContext="{Binding Path=Customer}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>

        <TextBlock Text="First Name:" VerticalAlignment="Center" Width="75" />
        <TextBox Text="{Binding Path=FirstName}" VerticalAlignment="Center" Grid.Column="1"/>

        <TextBlock Text="Last Name:" VerticalAlignment="Center" Width="75" Grid.Row="1" />
        <TextBox Text="{Binding Path=LastName}" VerticalAlignment="Center" Grid.Row="1" Grid.Column="1" />

        <TextBlock Text="Ranking:" VerticalAlignment="Center" Width="75" Grid.Row="2" />
        <TextBlock Text="{Binding Path=Ranking}" VerticalAlignment="Center"  Grid.Row="2" Grid.Column="1" />

        <TextBlock Margin="7" Text="Addresses" FontWeight="Bold" Grid.Row="3" Grid.ColumnSpan="2" />

        <ListBox ItemsSource="{Binding Path=Addresses}" Grid.Row="4" Grid.ColumnSpan="2">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="100" />
                            <ColumnDefinition Width="75" />
                            <ColumnDefinition Width="30" />
                            <ColumnDefinition Width="Auto" />
                        </Grid.ColumnDefinitions>
                        <TextBlock Text="{Binding Path=LineOne}" />
                        <TextBlock Text="{Binding Path=City}" Grid.Column="1" />
                        <TextBlock Text="{Binding Path=State}" Grid.Column="2" />
                        <TextBlock Text="{Binding Path=Zip}" Grid.Column="3" />
                    </Grid>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

    </Grid>

    <Image VerticalAlignment="Top" Source="{Binding Path=Customer.Photo}" Grid.Row="1" Grid.Column="1" Margin="6" />
</Grid>

Demo-04 Northwind Master Details Details

Open Demo04NorthwindMasterDetailsDetails.xaml.

This is an example of using chained CollectionViewSources where the top level CollectionViewSource is the DataContext for a form. It is assumed that the CollectionViewSources will be populated at run-time from a code-behind method.

This example uses an EntityFramework model for the entity types.

The below sample data file has 2 instances of Customer each with 1 instance of Order and each Order has three instances of Order_Detail.

<sysCol:ArrayList xmlns:sysCol="clr-namespace:System.Collections;assembly=mscorlib"
                  xmlns:nw="clr-namespace:SampleDataScenarios.NorthwindModel">
    <nw:Customer Contact_Name="Jim Hance" Company_Name="Adatum" Contact_Title="Software Developer" Customer_ID="1">
        <nw:Customer.Orders>
            <nw:Order Order_Date="12/12/2009" Ship_Name="Jim Hance" Customer_ID="1" Order_ID="1"
                      Ship_Address="125 North St" Employee_ID="74">
                <nw:Order.Order_Details>
                    <nw:Order_Detail Product_ID="125" Discount="50" Order_ID="1" Quantity="5" 
                                     Unit_Price="75.99" />
                    <nw:Order_Detail Product_ID="742" Order_ID="1" Quantity="9" Unit_Price="5.99" />
                    <nw:Order_Detail Product_ID="2555" Order_ID="1" Quantity="50" Unit_Price="6.25" />
                </nw:Order.Order_Details>
            </nw:Order>
        </nw:Customer.Orders>
    </nw:Customer>
    <nw:Customer Contact_Name="Michael Patten" Company_Name="Contoso" Contact_Title="Sales Manager" Customer_ID="2">
        <nw:Customer.Orders>
            <nw:Order Order_Date="12/12/2009" Ship_Name="Michael Patten" Customer_ID="2" Order_ID="71"
                      Ship_Address="125 North St" Employee_ID="55">
                <nw:Order.Order_Details>
                    <nw:Order_Detail Product_ID="547" Discount="50" Order_ID="71" Quantity="5" 
                                     Unit_Price="75.99" />
                    <nw:Order_Detail Product_ID="62" Order_ID="71" Quantity="9" Unit_Price="5.99" />
                    <nw:Order_Detail Product_ID="11" Order_ID="71" Quantity="50" Unit_Price="6.25" />
                </nw:Order.Order_Details>
            </nw:Order>
        </nw:Customer.Orders>
    </nw:Customer>
</sysCol:ArrayList>

Connecting Sample Data

In the below XAML the NorthwindSampleData.xaml file is loaded and parsed by the d:DesignData Markup Extension and assigned to the d:DesignSource for the top level customersViewSource CollectionViewSource. The two remaining CollectionViewSources chain to collection properties on the customersViewSource.

Child controls of the Grid can data bind to properties on the DataContext and the Designer Binding Builder tooling is enabled. Notice the two DataGrid ItemsSource’s are the two chained CollectionViewSources. The two DataGrid’s also have their sample data populated and the Designer Binding Builder tooling is enabled.

<UserControl.Resources>
  <CollectionViewSource 
    x:Key="customersViewSource" 
    d:DesignSource="{d:DesignData Source=../SampleData/NorthwindSampleData.xaml}" />
  <CollectionViewSource 
    x:Key="customersOrdersViewSource" 
    Source="{Binding Path=Orders, Source={StaticResource customersViewSource}}" />
  <CollectionViewSource 
    x:Key="customersOrdersOrder_DetailsViewSource" 
    Source="{Binding Path=Order_Details, Source={StaticResource customersOrdersViewSource}}" />
</UserControl.Resources>
<Grid DataContext="{StaticResource customersViewSource}">
  <Grid.RowDefinitions>
    <RowDefinition Height="Auto" />
    <RowDefinition Height="*" />
    <RowDefinition Height="*" />
  </Grid.RowDefinitions>
  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="200" />
    <ColumnDefinition Width="*" />
  </Grid.ColumnDefinitions>

  <TextBlock Text="Demo-04 Northwind Master Details Details" Grid.ColumnSpan="2" FontWeight="Bold" FontSize="14" Margin="11" />

  <ListView 
    SelectedIndex="0" ItemsSource="{Binding}" Name="customersListView" SelectionMode="Single" 
    Margin="3.5,4" Grid.RowSpan="2" Grid.Row="1">
    <ListView.ItemContainerStyle>
      <Style>
        <Setter Property="Control.HorizontalContentAlignment" Value="Stretch" />
        <Setter Property="Control.VerticalContentAlignment" Value="Stretch" />
      </Style>
    </ListView.ItemContainerStyle>
    <ListView.View>
      <GridView>
        <GridViewColumn x:Name="company_NameColumn" Header="Company Name" Width="90">
          <GridViewColumn.CellTemplate>
            <DataTemplate>
              <TextBox 
                Margin="-6,-1" 
                Text="{Binding Path=Company_Name, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" />
            </DataTemplate>
          </GridViewColumn.CellTemplate>
        </GridViewColumn>
        <GridViewColumn x:Name="contact_NameColumn" Header="Contact Name" Width="90">
          <GridViewColumn.CellTemplate>
            <DataTemplate>
              <TextBox 
                Margin="-6,-1" 
                Text="{Binding Path=Contact_Name, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" />
            </DataTemplate>
          </GridViewColumn.CellTemplate>
        </GridViewColumn>
      </GridView>
    </ListView.View>
  </ListView>

  <Grid Grid.Column="1" Margin="3.5" Grid.Row="1">
    <DataGrid 
      AutoGenerateColumns="False" EnableRowVirtualization="True" 
      ItemsSource="{Binding Source={StaticResource customersOrdersViewSource}}" 
      Name="ordersDataGrid" RowDetailsVisibilityMode="VisibleWhenSelected" Margin="3.5">
      <DataGrid.Columns>
        <DataGridTextColumn 
          x:Name="order_IDColumn" Binding="{Binding Path=Order_ID}" Header="Order ID" Width="SizeToHeader" />
        <DataGridTextColumn 
          x:Name="customer_IDColumn" Binding="{Binding Path=Customer_ID}" 
          Header="Customer ID" Width="SizeToHeader" />
        <DataGridTextColumn 
          x:Name="employee_IDColumn" Binding="{Binding Path=Employee_ID}" 
          Header="Employee ID" Width="SizeToHeader" />
        <DataGridTextColumn 
          x:Name="ship_NameColumn" Binding="{Binding Path=Ship_Name}" 
          Header="Ship Name" Width="SizeToHeader" />
        <DataGridTextColumn 
          x:Name="ship_AddressColumn" Binding="{Binding Path=Ship_Address}" 
          Header="Ship Address" Width="SizeToHeader" />
        <DataGridTextColumn 
          x:Name="ship_CityColumn" Binding="{Binding Path=Ship_City}" 
          Header="Ship City" Width="SizeToHeader" />
        <DataGridTextColumn 
          x:Name="ship_RegionColumn" Binding="{Binding Path=Ship_Region}" 
          Header="Ship Region" Width="SizeToHeader" />
        <DataGridTextColumn 
          x:Name="ship_Postal_CodeColumn" Binding="{Binding Path=Ship_Postal_Code}" 
          Header="Ship Postal Code" Width="SizeToHeader" />
        <DataGridTextColumn 
          x:Name="ship_CountryColumn" Binding="{Binding Path=Ship_Country}" 
          Header="Ship Country" Width="SizeToHeader" />
        <DataGridTextColumn 
          x:Name="ship_ViaColumn" Binding="{Binding Path=Ship_Via}" 
          Header="Ship Via" Width="SizeToHeader" />
        <DataGridTemplateColumn 
          x:Name="order_DateColumn" Header="Order Date" Width="SizeToHeader">
          <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
              <DatePicker 
                SelectedDate="{Binding Path=Order_Date, Mode=TwoWay, 
                                ValidatesOnExceptions=true, NotifyOnValidationError=true}" />
            </DataTemplate>
          </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
        <DataGridTemplateColumn x:Name="required_DateColumn" Header="Required Date" Width="SizeToHeader">
          <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
              <DatePicker 
                SelectedDate="{Binding Path=Required_Date, Mode=TwoWay, 
                                ValidatesOnExceptions=true, NotifyOnValidationError=true}" />
            </DataTemplate>
          </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
        <DataGridTemplateColumn x:Name="shipped_DateColumn" Header="Shipped Date" Width="SizeToHeader">
          <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
              <DatePicker 
                SelectedDate="{Binding Path=Shipped_Date, Mode=TwoWay, 
                                ValidatesOnExceptions=true, NotifyOnValidationError=true}" />
            </DataTemplate>
          </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
        <DataGridTextColumn 
          x:Name="freightColumn" Binding="{Binding Path=Freight}" 
          Header="Freight" Width="SizeToHeader" />
      </DataGrid.Columns>
    </DataGrid>
  </Grid>
  <DataGrid 
    AutoGenerateColumns="False" EnableRowVirtualization="True" Grid.Column="1" Grid.Row="2" 
    ItemsSource="{Binding Source={StaticResource customersOrdersOrder_DetailsViewSource}}" 
    Name="order_DetailsDataGrid" RowDetailsVisibilityMode="VisibleWhenSelected" Margin="3.5">
    <DataGrid.Columns>
      <DataGridTextColumn 
        x:Name="order_IDColumn1" Binding="{Binding Path=Order_ID}" 
        Header="Order ID" Width="SizeToHeader" />
      <DataGridTextColumn 
        x:Name="product_IDColumn" Binding="{Binding Path=Product_ID}" 
        Header="Product ID" Width="SizeToHeader" />
      <DataGridTextColumn 
        x:Name="unit_PriceColumn" Binding="{Binding Path=Unit_Price}" 
        Header="Unit Price" Width="SizeToHeader" />
      <DataGridTextColumn 
        x:Name="quantityColumn" Binding="{Binding Path=Quantity}" 
        Header="Quantity" Width="SizeToHeader" />
      <DataGridTextColumn 
        x:Name="discountColumn" Binding="{Binding Path=Discount}" 
        Header="Discount" Width="SizeToHeader" />
    </DataGrid.Columns>
  </DataGrid>
</Grid>

Demo-05 Select Customer From List

Open Demo05SelectCustomerFromList.xaml.

This is an example of a multiple instance sample data file consumed by a form. The sample data consists of 3 Customers, each with 2 Addresses.

<m:Customers xmlns:m="clr-namespace:SampleDataScenarios.Model">
    <m:Customer FirstName="Alfons" LastName="Parovszky" Photo="../Images/image01.png">
        <m:Customer.Addresses>
            <m:Address LineOne="125 North St" City="Greatville" State="CA" Zip="98004" />
            <m:Address LineOne="3000 1st St NE" City="Coolville" State="CA" Zip="98004" />
        </m:Customer.Addresses>
    </m:Customer>
    <m:Customer FirstName="Lori" LastName="Penor" Photo="../Images/image02.png">
        <m:Customer.Addresses>
            <m:Address LineOne="126 East St" City="Greatville" State="CA" Zip="98004" />
            <m:Address LineOne="3001 2st St NE" City="Coolville" State="CA" Zip="98004" />
        </m:Customer.Addresses>
    </m:Customer>
    <m:Customer FirstName="Justin" LastName="Harrison" Photo="../Images/image03.png">
        <m:Customer.Addresses>
            <m:Address LineOne="127 West St" City="Greatville" State="CA" Zip="98004" />
            <m:Address LineOne="3002 3st St NE" City="Coolville" State="CA" Zip="98004" />
        </m:Customer.Addresses>
    </m:Customer>
</m:Customers>

In the below form, the collection of Customers is available in the root Grid’s DataContext. This is important because the presence of d:DesignData and sample data not only feeds the DataContext to render data, but also enables the Designer tooling for creating and editing bindings in the Binding Builder.

The data entry form to the right of the ListBox, has its DataContext set to the ListBox.SelectedItem. When ListBox selection changes the form data automatically changes.

Connecting Sample Data

In the below XAML the CustomersSampleData.xaml file is loaded and parsed by the d:DesignData Markup Extension and assigned to the d:DataContext for the Grid. Child controls of the Grid can data bind to properties on the DataContext and the Designer Binding Builder tooling is enabled.

<Grid d:DataContext="{d:DesignData Source=/SampleData/CustomersSampleData.xaml}">
  <Grid.RowDefinitions>
    <RowDefinition Height="Auto" />
    <RowDefinition Height="*" />
  </Grid.RowDefinitions>
  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="126" />
    <ColumnDefinition Width="*" />
    <ColumnDefinition Width="*" />
  </Grid.ColumnDefinitions>

  <TextBlock Text="Demo-05 Select Customer From List" Grid.ColumnSpan="3" 
                  FontWeight="Bold" FontSize="14" Margin="11" />

  <ListBox SelectedIndex="0" x:Name="lbCustomers" Grid.Row="1" Margin="6" ItemsSource="{Binding}">
    <ListBox.ItemTemplate>
      <DataTemplate>
        <StackPanel Orientation="Horizontal">
          <TextBlock Text="{Binding Path=FirstName}" Margin="0,0,4,0" />
          <TextBlock Text="{Binding Path=LastName}" />
        </StackPanel>
      </DataTemplate>
    </ListBox.ItemTemplate>
  </ListBox>

  <Grid Grid.Row="1" Margin="6" Grid.Column="1" DataContext="{Binding ElementName=lbCustomers, Path=SelectedItem}">
    <Grid.RowDefinitions>
      <RowDefinition Height="Auto" />
      <RowDefinition Height="Auto" />
      <RowDefinition Height="Auto" />
      <RowDefinition Height="Auto" />
      <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="Auto" />
      <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>

    <TextBlock Text="First Name:" VerticalAlignment="Center" Width="75" />
    <TextBox Text="{Binding Path=FirstName}" VerticalAlignment="Center" Grid.Column="1"/>

    <TextBlock Text="Last Name:" VerticalAlignment="Center" Width="75" Grid.Row="1" />
    <TextBox Text="{Binding Path=LastName}" VerticalAlignment="Center" Grid.Row="1" Grid.Column="1" />

    <TextBlock Text="Ranking:" VerticalAlignment="Center" Width="75" Grid.Row="2" />
    <TextBlock Text="{Binding Path=Ranking}" VerticalAlignment="Center"  Grid.Row="2" Grid.Column="1" />

    <TextBlock Margin="7" Text="Addresses" FontWeight="Bold" Grid.Row="3" Grid.ColumnSpan="2" />

    <ListBox ItemsSource="{Binding Path=Addresses}" Grid.Row="4" Grid.ColumnSpan="2">
      <ListBox.ItemTemplate>
        <DataTemplate>
          <Grid>
            <Grid.ColumnDefinitions>
              <ColumnDefinition Width="100" />
              <ColumnDefinition Width="75" />
              <ColumnDefinition Width="30" />
              <ColumnDefinition Width="Auto" />
            </Grid.ColumnDefinitions>
            <TextBlock Text="{Binding Path=LineOne}" />
            <TextBlock Text="{Binding Path=City}" Grid.Column="1" />
            <TextBlock Text="{Binding Path=State}" Grid.Column="2" />
            <TextBlock Text="{Binding Path=Zip}" Grid.Column="3" />
          </Grid>
        </DataTemplate>
      </ListBox.ItemTemplate>
    </ListBox>

  </Grid>

  <Image VerticalAlignment="Top" Source="{Binding Path=Photo}" Grid.Row="1" Grid.Column="2" Margin="6" />
</Grid>

Demo-06 Typed DataTemplate

Open Demo06TypedDataTemplate.xaml.

The example demonstrates the requirements for displaying sample data when that data is rendered using a typed DataTemplate in a Resource. The key point here is that the DataTemplate is typed and in a Resource.

<m:Customer 
    xmlns:m="clr-namespace:SampleDataScenarios.Model" 
    FirstName="Alfons" LastName="Parovszky" 
    Photo="../Images/image01.png">
    <m:Customer.Addresses>
        <m:Address LineOne="125 North St" City="Greatville" State="CA" Zip="98004" />
        <m:Address LineOne="3000 1st St NE" City="Coolville" State="CA" Zip="98004" />
    </m:Customer.Addresses>
</m:Customer>

Typed DataTemplates are looked up based on DataType. If WPF cannot match the DataTemplate.DataType property with the sample data type, the DataTemplate will not be used to render the sample data. Additionally, any mismatch will also affect using the Designer Binding Builder as it won’t be able to resolve properties in the DataContext. The results of a mismatch are pictured in the right column of the two below tables.

When the sample data file Build Action is DesignDataWithDesignTimeCreatableTypes, the DataTemplate must have the d:IsDesignTimeCreatable property set to True or not set at all.

Correct Setting on Data Template When
Build Action = DesignDataWithDesignTimeCreatableTypes
Incorrect Setting on the DataTemplate When
Build Action = DesignDataWithDesignTimeCreatableTypes
Notice that ListBox is not using the typed DataTemplate to render the Address items.
<DataTemplate DataType=”{x:Type m:Address}”

d:IsDesignTimeCreatable=”True” >

—or—

<DataTemplate DataType=”{x:Type m:Address}”>

<DataTemplate DataType=”{x:Type m:Address}”

d:IsDesignTimeCreatable=”False” >

When the sample data file Build Action is DesignData, the DataTemplate must have the d:IsDesignTimeCreatable property set to False.

Correct Setting on the DataTemplate
Build Action = DesignData
Incorrect Setting on the DataTemplate
Build Action = DesignData
Notice that ListBox is not using the typed DataTemplate to render the Address items.
<DataTemplate DataType=”{x:Type m:Address}”

d:IsDesignTimeCreatable=”False” >

<DataTemplate DataType=”{x:Type m:Address}”

d:IsDesignTimeCreatable=”True” >

—or—

<DataTemplate DataType=”{x:Type m:Address}”>

Connecting Sample Data

In the below XAML the CustomerSampleData.xaml file is loaded and parsed by the d:DesignData Markup Extension and assigned to the d:DataContext for the Grid. Child controls of the Grid can data bind to properties on the DataContext and the Designer Binding Builder tooling is enabled.

<UserControl.Resources>
  <!--Because the sample data is using the DesignDataWithDesignTimeCreatableTypes build action, the 
      DataTemplate must have the property d:IsDesignTimeCreatable="True" or not at all so that the  
      types will match and be resolved correctly by the designer.-->
  <DataTemplate DataType="{x:Type m:Address}" d:IsDesignTimeCreatable="True" >
    <Grid>
      <Grid.ColumnDefinitions>
        <ColumnDefinition Width="100" />
        <ColumnDefinition Width="75" />
        <ColumnDefinition Width="30" />
        <ColumnDefinition Width="Auto" />
      </Grid.ColumnDefinitions>
      <TextBlock Text="{Binding Path=LineOne}" />
      <TextBlock Text="{Binding Path=City}" Grid.Column="1" />
      <TextBlock Text="{Binding Path=State}" Grid.Column="2" />
      <TextBlock Text="{Binding Path=Zip}" Grid.Column="3" />
    </Grid>
  </DataTemplate>

</UserControl.Resources>
<Grid d:DataContext="{d:DesignData Source=/SampleData/CustomerSampleData.xaml}">
  <Grid.RowDefinitions>
    <RowDefinition Height="Auto" />
    <RowDefinition Height="*" />
  </Grid.RowDefinitions>
  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="*" />
    <ColumnDefinition Width="*" />
  </Grid.ColumnDefinitions>

  <TextBlock Text="Demo-06 Typed DataTemplate" Grid.ColumnSpan="2" FontWeight="Bold" FontSize="14" Margin="11" />

  <Grid Grid.Row="1" Margin="6">
    <Grid.RowDefinitions>
      <RowDefinition Height="Auto" />
      <RowDefinition Height="Auto" />
      <RowDefinition Height="Auto" />
      <RowDefinition Height="Auto" />
      <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="Auto" />
      <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>

    <TextBlock Text="First Name:" VerticalAlignment="Center" Width="75" />
    <TextBox Text="{Binding Path=FirstName}" VerticalAlignment="Center" Grid.Column="1"/>

    <TextBlock Text="Last Name:" VerticalAlignment="Center" Width="75" Grid.Row="1" />
    <TextBox Text="{Binding Path=LastName}" VerticalAlignment="Center" Grid.Row="1" Grid.Column="1" />

    <TextBlock Text="Ranking:" VerticalAlignment="Center" Width="75" Grid.Row="2" />
    <TextBlock Text="{Binding Path=Ranking}" VerticalAlignment="Center"  Grid.Row="2" Grid.Column="1" />

    <TextBlock Margin="7" Text="Addresses" FontWeight="Bold" Grid.Row="3" Grid.ColumnSpan="2" />

    <ListBox ItemsSource="{Binding Path=Addresses}" Grid.Row="4" Grid.ColumnSpan="2" />

  </Grid>

  <Image VerticalAlignment="Top" Source="{Binding Path=Photo}" Grid.Row="1" Grid.Column="1" Margin="6" />
</Grid>

Silverlight Sample Data Scenarios 

The above WPF scenarios are also valid for Silverlight and won’t be repeated here. The biggest difference between the two platforms with respect to sample data is the required pack syntax for images in sample data files.

Open either solution: CS-SampleDataScenarios or VB-SampleDataScenarios.

Rebuild solution.

The WPF samples are in the SLSampleDataScenarios project.

Demo-01 Single Customer

Open Demo01SingleCustomer.xaml.

This is an example of a single instance sample data file consumed by a form. The single instance of Customer has 2 instances of Address. Notice the assembly name; component syntax is used to identify an image in the project that has its Build Action set to Resource.

<m:Customer 
    xmlns:m="clr-namespace:SLSampleDataScenarios.Model" 
    FirstName="Alfons" LastName="Parovszky" 
    Photo="/SLSampleDataScenarios;component/Images/image01.png">
    <m:Customer.Addresses>
        <m:Address LineOne="125 North St" City="Greatville" State="CA" Zip="98004" />
        <m:Address LineOne="3000 1st St NE" City="Coolville" State="CA" Zip="98004" />
    </m:Customer.Addresses>
</m:Customer>

In the below form, the Customer type is available in the root Grid’s DataContext. This is important because the presence of d:DesignData and sample data not only feeds the DataContext to render data, but also enables the Designer tooling for creating and editing bindings in the Binding Builder.

Connecting Sample Data

In the below XAML the CustomerSampleData.xaml file is loaded and parsed by the d:DesignData Markup Extension and assigned to the d:DataContext for the Grid. Child controls of the Grid can data bind to properties on the DataContext and the Designer Binding Builder tooling is enabled.

<Grid d:DataContext="{d:DesignData Source=../SampleData/CustomerSampleData.xaml}">
  <Grid.RowDefinitions>
    <RowDefinition Height="Auto" />
    <RowDefinition Height="*" />
  </Grid.RowDefinitions>
  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="*" />
    <ColumnDefinition Width="*" />
  </Grid.ColumnDefinitions>

  <TextBlock Text="Demo-01 Single Customer" Grid.ColumnSpan="2" FontWeight="Bold" FontSize="14" Margin="11" />

  <Grid Grid.Row="1" Margin="6">
    <Grid.RowDefinitions>
      <RowDefinition Height="Auto" />
      <RowDefinition Height="Auto" />
      <RowDefinition Height="Auto" />
      <RowDefinition Height="Auto" />
      <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="Auto" />
      <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>

    <TextBlock Text="First Name:" VerticalAlignment="Center" Width="75" />
    <TextBox Text="{Binding Path=FirstName}" VerticalAlignment="Center" Grid.Column="1"/>

    <TextBlock Text="Last Name:" VerticalAlignment="Center" Width="75" Grid.Row="1" />
    <TextBox Text="{Binding Path=LastName}" VerticalAlignment="Center" Grid.Row="1" Grid.Column="1" />

    <TextBlock Text="Ranking:" VerticalAlignment="Center" Width="75" Grid.Row="2" />
    <TextBlock Text="{Binding Path=Ranking}" VerticalAlignment="Center"  Grid.Row="2" Grid.Column="1" />

    <TextBlock Margin="7" Text="Addresses" FontWeight="Bold" Grid.Row="3" Grid.ColumnSpan="2" />

    <ListBox ItemsSource="{Binding Path=Addresses}" Grid.Row="4" Grid.ColumnSpan="2">
      <ListBox.ItemTemplate>
        <DataTemplate>
          <Grid>
            <Grid.ColumnDefinitions>
              <ColumnDefinition Width="100" />
              <ColumnDefinition Width="75" />
              <ColumnDefinition Width="30" />
              <ColumnDefinition Width="Auto" />
            </Grid.ColumnDefinitions>
            <TextBlock Text="{Binding Path=LineOne}" />
            <TextBlock Text="{Binding Path=City}" Grid.Column="1" />
            <TextBlock Text="{Binding Path=State}" Grid.Column="2" />
            <TextBlock Text="{Binding Path=Zip}" Grid.Column="3" />
          </Grid>
        </DataTemplate>
      </ListBox.ItemTemplate>
    </ListBox>

  </Grid>

  <Image VerticalAlignment="Top" Source="{Binding Path=Photo}" Grid.Row="1" Grid.Column="1" Margin="6" />
</Grid>

Demo-02 Customers DataSources Window

Open Demo02CustomersDataSourcesWindow.xaml.

This is an example of using a CollectionViewSource that has sample data as the DataContext for a form. It is assumed that the CollectionViewSource will be populated at run-time from a code-behind method.

The below sample data file has 3 instances of Customer, each with 2 instances of Address. Notice the root collection.

<m:Customers xmlns:m="clr-namespace:SLSampleDataScenarios.Model">
<m:Customer FirstName="Alfons" LastName="Parovszky" 
            Photo="/SLSampleDataScenarios;component/Images/image01.png">
        <m:Customer.Addresses>
            <m:Address LineOne="125 North St" City="Greatville" State="CA" Zip="98004" />
            <m:Address LineOne="3000 1st St NE" City="Coolville" State="CA" Zip="98004" />
        </m:Customer.Addresses>
    </m:Customer>
    <m:Customer FirstName="Lori" LastName="Penor" 
                Photo="/SLSampleDataScenarios;component/Images/image02.png">
        <m:Customer.Addresses>
            <m:Address LineOne="126 East St" City="Greatville" State="CA" Zip="98004" />
            <m:Address LineOne="3001 2st St NE" City="Coolville" State="CA" Zip="98004" />
        </m:Customer.Addresses>
    </m:Customer>
    <m:Customer FirstName="Justin" LastName="Harrison" 
                Photo="/SLSampleDataScenarios;component/Images/image03.png">
        <m:Customer.Addresses>
            <m:Address LineOne="127 West St" City="Greatville" State="CA" Zip="98004" />
            <m:Address LineOne="3002 3st St NE" City="Coolville" State="CA" Zip="98004" />
        </m:Customer.Addresses>
    </m:Customer>
</m:Customers>

In the below form, the ComboBox is used to set the CurrentItem for the CollectionViewSource. The Grid that contains the Customer data entry form has its DataContext set to the CollectionViewSource. When the ComboBox selection changes the CollectionViewSource CurrentItem, the data entry form CurrentItem will automatically change. This is one technique for providing record selection.

Connecting Sample Data

In the below XAML, the CustomersSampleData.xaml file is loaded and parsed by the d:DesignData Markup Extension and assigned to the d:DesignSource for the CollectionViewSource.

<UserControl.Resources>
  <CollectionViewSource 
    x:Key="customerViewSource" 
    d:DesignSource="{d:DesignData Source=../SampleData/CustomersSampleData.xaml}" />
</UserControl.Resources>
<Grid>
  <Grid.RowDefinitions>
    <RowDefinition Height="Auto" />
    <RowDefinition Height="Auto" />
    <RowDefinition Height="*" />
  </Grid.RowDefinitions>

  <TextBlock 
    Text="Demo-02 Customers Data Sources Window" FontWeight="Bold" 
    FontSize="14" Margin="11" />

  <StackPanel 
    Margin="6" Orientation="Horizontal" Grid.Row="1" 
    DataContext="{StaticResource customerViewSource}">
    <TextBlock VerticalAlignment="Center" Text="Select Customer:" Margin="7,0"  />
    <ComboBox Width="200" VerticalAlignment="Center" ItemsSource="{Binding}">
      <ComboBox.ItemTemplate>
        <DataTemplate>
          <StackPanel Orientation="Horizontal">
            <TextBlock Text="{Binding Path=FirstName}" Margin="0,0,7,0" />
            <TextBlock Text="{Binding Path=LastName}" />
          </StackPanel>
        </DataTemplate>
      </ComboBox.ItemTemplate>
    </ComboBox>
  </StackPanel>

  <Grid Grid.Row="2" Margin="6" DataContext="{StaticResource customerViewSource}">
    <Grid.RowDefinitions>
      <RowDefinition Height="Auto" />
      <RowDefinition Height="Auto" />
      <RowDefinition Height="Auto" />
      <RowDefinition Height="Auto" />
      <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="Auto" />
      <ColumnDefinition Width="*" />
      <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>

    <TextBlock Text="First Name:" VerticalAlignment="Center" Width="75" />
    <TextBox Text="{Binding Path=FirstName}" VerticalAlignment="Center" Grid.Column="1"/>

    <TextBlock Text="Last Name:" VerticalAlignment="Center" Width="75" Grid.Row="1" />
    <TextBox Text="{Binding Path=LastName}" VerticalAlignment="Center" Grid.Row="1" Grid.Column="1" />

    <TextBlock Text="Ranking:" VerticalAlignment="Center" Width="75" Grid.Row="2" />
    <TextBlock Text="{Binding Path=Ranking}" VerticalAlignment="Center"  Grid.Row="2" Grid.Column="1" />

    <TextBlock Margin="7" Text="Addresses" FontWeight="Bold" Grid.Row="3" Grid.ColumnSpan="2" />

    <ListBox ItemsSource="{Binding Path=Addresses}" Grid.Row="4" Grid.ColumnSpan="2">
      <ListBox.ItemTemplate>
        <DataTemplate>
          <Grid>
            <Grid.ColumnDefinitions>
              <ColumnDefinition Width="100" />
              <ColumnDefinition Width="75" />
              <ColumnDefinition Width="30" />
              <ColumnDefinition Width="Auto" />
            </Grid.ColumnDefinitions>
            <TextBlock Text="{Binding Path=LineOne}" />
            <TextBlock Text="{Binding Path=City}" Grid.Column="1" />
            <TextBlock Text="{Binding Path=State}" Grid.Column="2" />
            <TextBlock Text="{Binding Path=Zip}" Grid.Column="3" />
          </Grid>
        </DataTemplate>
      </ListBox.ItemTemplate>
    </ListBox>

    <Image VerticalAlignment="Top" Source="{Binding Path=Photo}" Grid.RowSpan="5" Grid.Column="2" Margin="6" />
  </Grid>

</Grid>

WCF RIA Services Sample Data Scenario 

The below scenario will concentrate on surfacing design-time sample data in the Designer.

Open solution: ContosoSales.Mix10.

Rebuild solution.

Open \Views\Home.xaml.

This is an example form from the PDC 2010 RIA Services Demo. This demo has been upgraded to display design-time sample data.

The sample data file contains 2 Store records that each contains 2 Contacts.

Important
In WCF RIA Services, types deriving from Entity are not creatable. As a result, all sample data files must have their Build Action set to: DesignData and not DesignDataWithDesignTimeCreatableTypes.
Note
Blend does not support the DomainDataSource d:DesignData property. As a result, sample data applied to the DomainDataSource will not render in Blend on the art board (design surface).
<ria:DesignRIAEntitySampleDataCollection 
    xmlns:web="clr-namespace:ContosoSales.Web"
    xmlns:ria="clr-namespace:ContosoSales.SampleData">

  <web:Store City="Bellevue" StateProvince="CA" StoreID="1" StoreName="A. Datum Corporation"
            StoreImage="/ContosoSales;component/SampleDataImages/StoreFront.png" >
    <web:Store.StoreContacts>
      <web:StoreContact ContactID="55" Position="Artist" StoreID="1">
        <web:StoreContact.Contact>
          <web:Contact ContactPhoto="/ContosoSales;component/SampleDataImages/jeffhand.jpg" 
                       ContactID="55" FirstName="Alfons" LastName="Parovszky" SalesTarget="900" 
                       WorkEmail="alfons@adatum.com" WorkPhone="411" />
        </web:StoreContact.Contact>
      </web:StoreContact>
      <web:StoreContact ContactID="655" Position="Artist" Store="A. Datum Corporation" StoreID="1">
        <web:StoreContact.Contact>
          <web:Contact ContactPhoto="/ContosoSales;component/SampleDataImages/dineshku.jpg" 
                       ContactID="655" FirstName="Lori" LastName="Penor" SalesTarget="900" 
                       WorkEmail="lori@adatum.com" WorkPhone="411" />
        </web:StoreContact.Contact>
      </web:StoreContact>
    </web:Store.StoreContacts>
  </web:Store>
  <web:Store City="Bellevue" StateProvince="CA" StoreID="12" StoreName="Adventure Works"
               StoreImage="/ContosoSales;component/SampleDataImages/StoreFront.png" >
    <web:Store.StoreContacts>
      <web:StoreContact ContactID="15" Position="Sales" StoreID="2" Store="Adventure Works">
        <web:StoreContact.Contact>
          <web:Contact ContactPhoto="/ContosoSales;component/SampleDataImages/jeffhand.jpg" 
                       ContactID="15" FirstName="Justin" LastName="Harrison" SalesTarget="000" 
                       WorkEmail="justin@adventure-works.com" WorkPhone="411" />
        </web:StoreContact.Contact>
      </web:StoreContact>
      <web:StoreContact ContactID="655" Position="Artist" Store="Adventure Works" StoreID="1">
        <web:StoreContact.Contact>
          <web:Contact ContactPhoto="/ContosoSales;component/SampleDataImages/dineshku.jpg"
                       ContactID="655" FirstName="Mark" LastName="Harrington" SalesTarget="900" 
                       WorkEmail="mark@adventure-works.com" WorkPhone="411" />
        </web:StoreContact.Contact>
      </web:StoreContact>
    </web:Store.StoreContacts>
  </web:Store>
</ria:DesignRIAEntitySampleDataCollection>

Another important distinction is that the root collection must derive from List<Entity>. This is a requirement of RIA Services. Developers must create a class similar to the below class to act as a container for RIA Services sample data objects. Note, this collection does not actually care which type of entity is in the collection so long as the object derives from Entity.

namespace ContosoSales.SampleData {
    public class DesignRIAEntitySampleDataCollection : 
          List<System.ServiceModel.DomainServices.Client.Entity> {

        public DesignRIAEntitySampleDataCollection() { }
    }
}

This Store class comes from the code that Visual Studio generates in the Silverlight client application. This is contained in the hidden Generated_Code folder.

public sealed partial class Store : Entity

Connecting Sample Data

Sample data in a RIA Services application is applied to the d:DesignData property of the DomainDataSource.

<riaControls:DomainDataSource 
    SubmittedChanges="storeDomainDataSource_SubmittedChanges"  Name="storeDomainDataSource" AutoLoad="True"
    LoadedData="storeDomainDataSource_LoadedData" 
    d:DesignData="{d:DesignData Source=../SampleData/RIASampleData.xaml}"
    QueryName="GetStoresQuery" FilterOperator="Or">
    <riaControls:DomainDataSource.DomainContext>
        <my:ContactContext />
    </riaControls:DomainDataSource.DomainContext>
    ...
</riaControls:DomainDataSource>

The Home.xaml file listing is long, nested and complex so I won’t display the XAML here.

The way the Home UserControl works at design-time is very similar to the previous WPF or Silverlight examples. The major difference is that the DomainDataSource is the control that receives the sample data. From here, other CollectionViewSources can “dot” into the data exposed by the Data property to populate their CollectionView and ultimately the bound UI objects.

Have a look at the below storeStoreContactsViewSource CollectionViewSource. Its Source is set to the Data.StoreContacts. In this case, Data is actually pointing to the selected Store from the left hand ListBox in the UI. The below Grid contains the data entry form on the right hand side of the form. When the ListBox selection changes the DataContext of the data entry form changes to the SelectedItem in the ListBox.

<CollectionViewSource 
    x:Key="storeStoreContactsViewSource" 
    Source="{Binding Path=Data.StoreContacts, ElementName=storeDomainDataSource}" />

 

<ListBox 
    ItemsSource="{Binding Source={StaticResource storeStoreContactsViewSource}}" 
    Name="storeContactsListBox" Style="{StaticResource ContactListBox}" />

 

<Grid BindingValidationError="Home_BindingValidationError" 
    DataContext="{Binding Source={StaticResource storeStoreContactsViewSource}}" Name="grid1">

This UI synchronization was accomplished without a single line of code.

Choosing Sample Data Loading Technique 

From the document you can see there are a number of ways to structure your applications and thus load sample data. One of the goals for the Design-Time Sample Data Feature for Visual Studio 2010 was to not limit or box developers in from using a technique that made business sense for the type of application they are writing. For example, many developers like the power of CollectionViewSources while other developers prefer to have their XAML files DataContext set to a ViewModel. This feature combined with the above techniques easily handles these and most other scenarios.

Using d:DesignData with a corresponding XAML Sample Data file is the recommended technique for surfacing sample data in WPF and Silverlight line of business applications. This technique surfaces design-time instances of your data classes and enables the Designer Binding Builder tooling. None of the sample data files or design-time XAML is compiled into your applications, making this technique simple and clean.

Choosing to surface sample data using d:DesignData leaves open endless possibilities for your application architecture and in-fact decouples sample data from the rest of your application.

However, as a developer you are not limited to just d:DesignData as the WPF Demo-03 Customer ViewModel demonstrated.

Comments 

Microsoft values your opinion about our products and documentation. In addition to your general feedback it is very helpful to understand:

  • How the above features enable your workflow
  • What is missing from the above features that would be helpful to you

Thank you for your feedback and have a great day,

Fonte: http://blogs.msdn.com/b/wpfsldesigner/archive/2010/06/30/sample-data-in-the-wpf-and-silverlight-designer.aspx

Autor: Karl Shifflett
Expression Team

Você está pronto para o HTML 5 ?

Quem acompanhou o começo da web deve lembrar do quanto as primeiras páginas eram feias. O design de páginas com HTML puro era cinza, quadradão, feito na base de frames e tabelas, as animações eram arquivos GIF toscos e restava ao webmaster fazer graça com scripts inúteis. Nesses últimos anos, vários padrões e tecnologias surgiram para ajudar a linguagem, como o CSS, o Flash e o XHTML. Mesmo assim, chegou a hora de mais mudança. A nova versão do padrão HTML está mais sólida, com os principais navegadores suportando suas inovações e facilitando assim a vida do designer, que poderá dispensar bibliotecas e pacotes auxiliares.

Vale lembrar que nem tudo funciona em todos os browsers, já que, na falta de uma especificação definitiva (que está prevista para 2012), os empresas adicionam os recursos do HTML 5 nos navegadores a conta-gotas. Conheça, a seguir, as principais mudanças que já estão aprovadas pela W3C e pelo WHATWG, as entidades que decidem o futuro da linguagem HTML.

Multimídia sem plug-in

O conteúdo em áudio e vídeo na web é refém dos plug-ins, como o Flash, para ser exibido. O HTML 5 prevê uma forma de contornar isso com as tags <video> e <:audio>. Falta ainda definir os tipos de codecs a ser utilizados universalmente com essas tags. Hoje, Chrome e Safari conseguem exibir filmes em H.264 e tocar áudio AAC, encapsulados num arquivo MP4. Já o Firefox, fiel aos padrões abertos, mostra só vídeos Theora e som Vorbis, dentro de um arquivo Ogg. O impasse não preocupa tanto, pois as tags <video> e <:audio> podem receber mais de um arquivo, com o browser selecionando qual é a opção compatível. Para adicionar um vídeo à página, basta usar o código:

<video src="meuvideo.mp4 width="320" height="240" controls></video>

CSS arrumadinho

O novo HTML promete aposentar frames e tabelas das páginas, com o CSS efetivado como responsável para esse fim. Além disso, a versão 5 conta com tags para definir seções dos sites, facilitando a integração com as folhas de estilo. Atualmente, o normal é usar um elemento <div>, com seu nome indicando o tipo de seção. As novas tags são <header>, <footer>, <article>, <section>, <nav> e <aside>. Elas definem o cabeçalho, o rodapé, um artigo, uma seção (de um artigo), a barra de navegação e anotações sobre o conteúdo. Com esses elementos, é criada uma padronização que facilita a localização de conteúdo pelos buscadores e o reaproveitamento dos arquivos CSS.

Gráficos nascidos na web

O elemento <canvas> permite criar desenhos usando JavaScript. Assim é possível, por exemplo, transformar dados do site em gráficos dinâmicos. A tag também serve para usar um texto ou imagem como substituto do desenho, caso o browser não tenha suporte aos gráficos dinâmicos. Nesse caso, o conteúdo alternativo fica entre e <canvas> e </canvas>.

Calendários sem erro

Qual é a data definida por 10/2/2010? Pode ser 10 de fevereiro, no padrão usado no Brasil, e, ao mesmo tempo, 2 de outubro, no modelo americano. O HTML 5 pode contornar essas situações com tags que definem o tipo de dados e sua formatação no texto da página web. A tag <time> marca hora e data e evitaria o problema descrito acima usando o código <timedatetime=”2010-02-10″> </time>, que poderia identificar as informações do navegador e decidir qual seria a data correta, para que ela possa ser exibida no padrão do usuário.

Versão offline

Já ouviu falar no Google Gears? Ele transforma aplicativos web em programas que rodam no browser mesmo em máquinas sem conexão com a web. Essa mágica é feita pelo recurso DOM Storage, que poderá ser usado por qualquer site em HTML 5. Um ponto essencial dessa forma de armazenamento local é que o servidor remoto não pode acessar diretamente o conteúdo (diferentemente dos cookies). Somente o browser e os scripts da página acessada podem modificar o conteúdo offline. Hoje, cada browser usa um limite de espaço. O Firefox aloca no máximo 5 MB por domínio web acessado. Já o Internet Explorer libera 10 MB por base de dados criada, independentemente do domínio.

Muito além dos cliques

Existem várias bibliotecas para habilitar o suporte ao recurso de arrastar e soltar objetos em sites. Mas no HTML 5 a coisa fica bem mais fácil. Basta definir valores para três eventos em JavaScript: dragenter, dragover e drop. Eles indicam, respectivamente, a entrada e a passagem de um elemento sobre outro, além do evento para o momento em que um item é solto. Definir um elemento da página como item que pode ser arrastado é mais fácil ainda. Basta adicionar a definição draggable=”true” a ele.

Fonte: Info

Comentário: O HTML 5 vem pra reorganizar o festival de TAGs que são utilizadas hoje para exibir vídeos, animações ou personalizar nosso layout, criadas a partir da evolução da Internet. Creio que a nova linguagem vai ajudar e muito os desenvolvedores e novatos a criarem seus sites mais facilmente e ao mesmo tempo compatível com a maioria dos navegadores (isto se os usuários atualizarem suas máquinas).

Creating an ASP.NET report using Visual Studio 2010 – Part 3

We continue building our report in this three part series.

Creating an ASP.NET report using Visual Studio 2010 – Part 1

Creating an ASP.NET report using Visual Studio 2010 – Part 2

Adding the ReportViewer control and filter drop downs.Open the source code for index.aspx and add a ScriptManager control. This control is required for the ReportViewer control. Add a DropDownList for the categories and suppliers. Add the ReportViewer control. The markup after these steps is shown below.

<div>

    <asp:ScriptManager ID="smScriptManager" runat="server">

    </asp:ScriptManager>

    <div id="searchFilter">

        Filter by: Category :

        <asp:DropDownList ID="ddlCategories" runat="server" />

        and Supplier :

        <asp:DropDownList ID="ddlSuppliers" runat="server" />

    </div>

    <rsweb:ReportViewer ID="rvProducts" runat="server">

    </rsweb:ReportViewer>

</div>

 

The design view for index.aspx is shown below. The dropdowns will display the categories and suppliers in the database. The report will be filtered by the selections in the dropdowns. You will see how to do this in the next steps.
image 
Attaching the RDLC to the ReportViewer control by clicking on the top right of the control, going to Report Viewer tasks and selecting Products.rdlc.  
image
Resize the ReportViewer control by dragging at the bottom right corner. I set mine to 800px x 500px. You can set this value in source view also.

image

Defining the data sources.
We will now define the Data Source used to populate the report. Go back to the “ReportViewer Tasks” and select “Choose Data Sources”
image
Select a “New data source..”
image

Select “Object” and name your Data Source ID “odsProducts”

image 
In the next screen, choose “ProductRepository” as your business object.
image
Choose “GetProductsProjected” in the next screen.

image 
The method requires a SupplierID and CategoryID. We will have the data source use the selected values of the drop down lists we defined earlier. Set the parameter source to be of type “Control” and set the ControlIDs to be ddlSuppliers and ddlCategories respectively. Your screen will look like this:
image
We are now going to define the data source for our drop downs. Select the ddlCategory drop down and pick “Choose Data Source”.

image
Pick “Object” and give it an id “odsCategories”
image 
In the next screen, choose “ProductRepository”
image
Select the GetCategories() method in the next screen.
image 
Select “CategoryName” and “CategoryID” in the next screen. We are done defining the data source for the Category drop down.
image
Perform the same steps for the Suppliers drop down.

image
image
image 
Select each dropdown and set the AppendDataBoundItems to true and AutoPostback to true.
image   
The AppendDataBoundItems is needed because we are going to insert an “All“ list item with a value of empty. This will be the first item in each drop down list. Go to each drop down and add this list item markup as shown below.
image

Double click on each drop down in the designer and add the following code in the code behind. This along with the “Autopostback= true” attribute refreshes the report anytime the selection in the drop down is changed.

protected void ddlCategories_SelectedIndexChanged(object sender, EventArgs e)

{

    rvProducts.LocalReport.Refresh();

}

 

protected void ddlSuppliers_SelectedIndexChanged(object sender, EventArgs e)

{

    rvProducts.LocalReport.Refresh();

}

Compile your report and run the page. You should see the report rendered. Note that the tool bar in the ReportViewer control gives you a couple of options including the ability to export the data to Excel, PDF or word.

 image

Conclusion

Through this three part series, we did the following:

  • Created a data layer for use by our RDLC.
  • Created an RDLC using the report wizard and define a dataset for the report.
  • Used the report design surface to design our report including adding a chart.
  • Used the ReportViewer control to attach the RDLC.
  • Connected our ReportWiewer to a data source and take parameter values from the drop downlists.
  • Used AutoPostBack to refresh the reports when the dropdown selection was changed.

RDLCs allow you to create interactive reports including drill downs and grouping. For even more advanced reports you can use Microsoft® SQL Server™ Reporting Services with RDLs. With RDLs, the report is rendered on the report server instead of the web server. Another nice thing about RDLs is that you can define a parameter list for the report and it gets rendered automatically for you. RDLCs and RDLs both have their advantages and its best to compare them and choose the right one for your requirements.

Creating an ASP.NET report using Visual Studio 2010 – Part 2

We continue building our report in this three part series.

Creating the Client Report Definition file (RDLC)image 
Right click on the RDLC folder, select “Add new item..” and add an “RDLC” name of “Products”. We will use the “Report Wizard” to walk us through the steps of creating the RDLC.
image 
In the next dialog, give the dataset a name called “ProductDataSet”. Change the data source to “NorthwindReports.DAL” and select “ProductRepository(GetProductsProjected)”.

The “Data Source” may show up empty. To get it populated, make sure your project is compiled and there is an index.aspx file in the root folder. This may be a bug.
 
The fields that are returned from the method are shown on the right. Click next.
image 
Drag and drop the ProductName, CategoryName, UnitPrice and Discontinued into the Values container. Note that you can create much more complex grouping using this UI. Click Next.

 

image 
Most of the selections on this screen are grayed out because we did not choose a grouping in the previous screen. Click next.
image
Choose a style for your report. Click next.
image
The report graphic design surface is now visible. Right click on the report and add a page header and page footer.
image
With the report design surface active, drag and drop a TextBox from the tool box to the page header. Drag one more textbox to the page header. We will use the text boxes to add some header text as shown in the next figure.

image
You can change the font size and other properties of the textboxes using the formatting tool bar (marked in red). You can also resize the columns by moving your cursor in between columns and dragging.
image

Adding Expressions

Add two more text boxes to the page footer. We will use these to add the time the report was generated and page numbers. Right click on the first textbox in the page footer and select “Expression”.
image
Add the following expression for the print date (note the = sign at the left of the expression in the dialog below)
image

"© Northwind Traders " & Format(Now(),"MM/dd/yyyy hh:mm tt")

Right click on the second text box and add the following for the page count.

 
Globals.PageNumber & " of " & Globals.TotalPages

Formatting the page footer is complete.
 
We are now going to format the “Unit Price” column so it displays the number in currency format.  Right click on the [UnitPrice] column (not header) and select “Text Box Properties..”

image
Under “Number”, select “Currency”. Hit OK.
image

Adding a chart

With the design surface active, go to the toolbox and drag and drop a chart control. You will need to move the product list table down first to make space for the chart contorl. The document can also be resized by dragging on the corner or at the page header/footer separator.

image
In the next dialog, pick the first chart type. This can be changed later if needed. Click OK. The chart gets added to the design surface.
image 
Click on the blue bars in the chart (not legend). This will bring up drop locations for dropping the fields. Drag and drop the UnitPrice and CategoryName into the top (y axis) and bottom (x axis) as shown below. This will give us the total unit prices for a given category. That is the best I could come up with as far as what report to render, sorry 🙂 Delete the legend area to get more screen estate.
image
Resize the chart to your liking. Change the header, x axis and y axis text by double clicking on those areas.

image
We made it this far. Let’s impress the client by adding a gradient to the bar graph 🙂 Right click on the blue bar and select “Series properties”.
image

Under “Fill”, add a color and secondary color and select the Gradient style.
image

We are done designing our report. In the next section you will see how to add the report to the report viewer control, bind to the data and make it refresh when the filter criteria are changed.

Creating an ASP.NET report using Visual Studio 2010 – Part 1

Creating an ASP.NET report using Visual Studio 2010 – Part 2

Creating an ASP.NET report using Visual Studio 2010 – Part 3

Add a folder called “RDLC”. This will hold our RDLC report.

Tutorial 1: Introdução ao SketchFlow

Para prototipação de projetos de TI o SketchFlow da Microsoft é uma excelente ferramenta.

Um recurso bem interessante é a publicação do protótipo em ambiente web e a coleta de feedback. O cliente pode navegar pelas páginas do protótipo e entrar com seus comentários. Os comentários podem ser exportados para um arquivo de feedback e enviados para a área envolvida pelo desenvolvimento do projeto.

A DANRESA Consultoria de Informatica utiliza esta ferramenta em seus projetos com clientes. Os protótipos ajudam na visualização de telas, de processos, e de fluxos de trabalhos tornando tudo menos abstrato para os clientes. Na hora de por a mão na massa não há dúvidas nem para o cliente, nem para a DANRESA dos trabalhos a serem desenvolvidos, melhorando a comunicação e as interações a cada etapa do projeto.

Abaixo segue um pequeno tutorial sobre a ferramenta e alguns links interessantes.

 SketchFlow é uma ferramenta de prototipagem presente no Expression Blend. Esta ferramenta é muito boa para criar protótipos de aplicações para mostrar aos compradores da aplicação. Assim evita-se muito tempo perdido ao alterar constantemente uma aplicação pois podemos, a partir de um sketch book, incoporar acções e eventos. Ou seja, temos uma aplicação completamente funcional mas com o aspecto de um livro de rascunhos sendo que esta aplicação é facilmente modificável.

Neste primeiro tutorial não vamos avançar muito nas capacidades do SktechFlow. Vamos criar uma aplicação muito simples em que o utilizador vai ter uma página para fazer o login. Caso falhe será levado para um ecrã vermelho e no caso positivo será levado para um ecrã verde. 

Para criar um projecto SketchFlow basta escolher criar um novo projecto e depois escolher Silverlight 3 SketchFlow Project ou WPF SketchFlow Project dependendo do tipo de projecto que pretenda. No nosso caso pretendemos criar um projecto de SketchFlow para Silverlight 3.

Após a criação do projecto aparece-nos o nosso workspace. Como podemos ver do lado esquerdo temos o nosso projecto, os “assets” e os estados. Na tab de projectos temos todos os ficheiros que constituem o nosso projecto recentemente criado. Na tab “assets” temos todos os elementos que podemos inserir no nosso projecto, entre os quais controlos, ecrãs, estilos, comportamentos, efeitos, etc. De todos estes só vamos abordar os controlos neste primeiro tutorial.

Um projecto de SketchFlow permite-nos inserir controlos normais mas uma das coisas que mais me chamou a atenção é o facto de termos controlos do tipo esboço. Ou seja, controlos em que o template faz com que estes pareçam desenhados com lápis. Para aceder a estes controlos basta aceder à categoria “SketchStyles” como está na imagem em baixo.

Outra coisa que este SketchFlow traz é o mapa de SketchFlow. Aqui podemos criar muito facilmente transições entre os vários ecrãs. Mas iremos abordar com mais profundidade este tema mais à frente neste mesmo tutorial. 

Agora que já sabemos onde estão os nossos controlos vamos criar um simples formulário onde o utilizador irá preencher o seu nome de utilizador e password e depois carrega num botão para proceder à validação. De notar que neste tutorial não vamos tratar da parte de comportamentos. Será um tema para um tutorial mais avançado. 

O resultado final do formulário é apresentado na imagem em baixo. 

Agora que já temos o nosso formulário criado temos que criar os ecrãs seguintes e as respectivas transições. Para isso vamos utilizar o mapa. 

Ao passar o cursor do rato por cima do “Screen 1” (o nosso ecrã principal) aparecem-nos várias opções: Criar um ecrã ligado, ligar a um ecrã existente, criar e inserir uma componente de ecrã e alterar a tag visual. Se decidirmos criar um ecrã ligado vai ser criado um novo ecrã ligado a este. Se decidirmos ligar a um ecrã existente, este irá ficar ligado ao outro ecrã que escolhermos. A terceira opção permite-nos ter elementos que são comuns a todos os ecrãs (ex: Logótipo da empresa). E a última opção permite-nos alterar a cor do objecto para ser assim mais fácil identificar que tipo de objecto é. 

No nosso caso, como é possível ver na imagem em baixo, criámos 3 ecrãs. O “Screen 1” que é o nosso ecrã principal onde está o formulário, o “Sucesso” caso as credenciais estejam correctas e “Falha” caso a password ou nome de utilizador estejam errados. De reparar que alterámos as cores para melhor compreender o diagrama. Neste caso não era muito dificil de perceber mas em esquemas mais complexas torna-se mais complicado. 

De reparar, na imagem acima, que do “Screen 1” para o ecrã “Falha” temos uma seta para a frente e outra para trás. Isto porque no caso de existir um erro na introdução das credenciais queremos dar a possibilidade ao utilizador de voltar a tentar como podemos ver no ecrã em baixo. Para o caso de sucesso temos um ecrã bastante semelhante ao apresentado em baixo mas sem nenhum botão e com a cor verde. 

Agora já temos os ecrãs. Mas então e como navegamos entre eles. Muito facilmente!!!…como podemos ver em baixo. Basta pressionar sobre o objecto com o botão direito do rato e escolher o ecrã para o qual pretendemos ir. 

Agora já temos o nosso projecto terminado. Vamos testá-lo. Para isso basta pressionar F5 para compilar e correr o mesmo utilizando o SketchFlow Player. Tal como podemos ver no ecrã apresentado em baixo temos assim acesso a todos os ecrãs que estão ligados ao ecrã principal. É portanto muito fácil navegar entre os ecrãs. 

Por exemplo, ao navegar para o ecrã “Falha”, tal como podemos ver em baixo, temos o ecrã vermelho com o botão que nos permite navegar outra vez para o inicio. 

O objectivo deste post está concluido. De referir que o SketchFlow é uma ferramenta com muitas capacidades e não abordámos quase nenhuma neste post. Ficam para os próximos tutoriais. 😉 

Fonte do artigo: http://gozoomin.com/blogs/tbarbosa/archive/2009/10/03/tutorial-1-introdu-231-227-o-ao-sketchflow.aspx

Para assistir à vídeos tutoriais sobre a ferramenta acesse: http://expression.microsoft.com/en-us/ee426886.aspx

Stay tuned!!

JQuery Autocomplete

Autocomplete é um recurso muito interessante a ser usado em formulários web quando precisamos de um campo que de início seria um dropdownlist, mas, que se torna inviável pelo número de registros a ser carregado. Quem já não se deparou com a situação de ter que carregar mais de 50 u 100 registros em uma dropdownlist?

Segue abaixo um recurso que estamos utilizando bastante em formulários web em nossos desenvolvimentos na fábrica de softwares da DANRESA Consultoria de Informatica e que tem agradado nossos clientes com uma boa experiência de usuário.

Autocomplete

Autocomplete, when added to an input field, enables users to quickly find and select from a pre-populated list of values as they type, leveraging searching and filtering.

By giving an Autocomplete field focus or entering something into it, the plugin starts searching for entries that match and displays a list of values to choose from. By entering more characters, the user can filter down the list to better matches.

This can be used to enter previous selected values, for example you could use Autocomplete for entering tags, to complete an address, you could enter a city name and get the zip code, or maybe enter email addresses from an address book.

You can pull data in from a local and/or a remote source: Local is good for small data sets (like an address book with 50 entries), remote is necessary for big data sets, like a database with hundreds or millions of entries to select from.

Autocomplete can be customized to work with various data sources, by just specifying the source option. A data source can be:

  • an Array with local data
  • a String, specifying a URL
  • a Callback

The local data can be a simple Array of Strings, or it contains Objects for each item in the array, with either a label or value property or both. The label property is displayed in the suggestion menu. The value will be inserted into the input element after the user selected something from the menu. If just one property is specified, it will be used for both, eg. if you provide only value-properties, the value will also be used as the label.

When a String is used, the Autocomplete plugin expects that string to point to a URL resource that will return JSON data. It can be on the same host or on a different one (must provide JSONP). The request parameter “term” gets added to that URL. The data itself can be in the same format as the local data described above.

The third variation, the callback, provides the most flexibility, and can be used to connect any data source to Autocomplete. The callback gets two arguments:

  • A request object, with a single property called “term”, which refers to the value currently in the text input. For example, when the user entered “new yo” in a city field, the Autocomplete term will equal “new yo”.
  • A response callback, which expects a single argument to contain the data to suggest to the user. This data should be filtered based on the provided term, and can be in any of the formats described above for simple local data (String-Array or Object-Array with label/value/both properties).

The demos all focus on different variations of the source-option – look for the one that matches your use case, and take a look at the code.

 Exemplo de Código

Faça um teste em: http://jqueryui.com/demos/autocomplete/#remote-jsonp 

<meta charset="UTF-8" />

<script type="text/javascript">
$(function() {
function log(message) {
$("<div/>").text(message).prependTo("#log");
$("#log").attr("scrollTop", 0);
}

$("#city").autocomplete({
source: function(request, response) {
$.ajax({
url: "http://ws.geonames.org/searchJSON",
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function(data) {
response($.map(data.geonames, function(item) {
return {
label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
value: item.name
}
}))
}
})
},
minLength: 2,
select: function(event, ui) {
log(ui.item ? ("Selected: " + ui.item.label) : "Nothing selected, input was " + this.value);
},
open: function() {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function() {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
});
</script>
<style>
.ui-autocomplete-loading { background: url(indicator.gif) no-repeat right; }
#city { width: 25em; }
</style>

<div>

<div>
<label for="city">Your city: </label>
<input id="city" />
Powered by <a href="http://geonames.org">geonames.org</a>
</div>

<div style="margin-top:2em; font-family:Arial">
Result:
<div id="log" style="height: 200px; width: 300px; overflow: auto;"></div>
</div>

</div><!-- End demo -->

<div>
<p>
The Autocomplete widgets provides suggestions while you type into the field. Here the suggestions are cities, displayed when at least two characters are entered into the field.
</p>
<p>
In this case, the datasource is the <a href="http://geonames.org">geonames.org webservice</a>. While only the city name itself ends up in the input after selecting an element, more info is displayed in the suggestions to help find the right entry. That data is also available in callbacks, as illustrated by the Result area below the input.
</p>
</div><!-- End demo-description -->