Thursday, July 1, 2010

SEO Tip - Dynamic Meta Tag for Blogger

Search Engine Optimization is necessary to bring traffic to a website. Meta tag is one of the element that Search engines use while crawling as according to some SEO guides and most important is Description meta tag. So I spent some time to add Description meta tag to my blog which is powered by Blogger. After that I realized that we can only add static meta tag through out the whole blog in normal way by using edit HTML template. As per SEO guides, adding same meta tag through out the blog is not a good practice and we should avoid the same. Some workarounds are there for adding dynamic description meta tag for blogger by checking some conditions. But for achieving that we need to add condition for each and every post. So I tried some alternatives and I believe I got a nice workaround.

  • Go to Edit HTML template page of Blogger.
  • I added page title itself as meta content. Paste the below code in the head section,
    <meta expr:content='data:blog.pageTitle' name='keywords'/>
    <meta expr:content='data:blog.pageTitle' name='Description'/>
    <meta expr:content='data:blog.pageTitle' name='Subject'/>
This will add the page title as the meta content which is far better than adding same static content for the entire blog.
Happy blogging.

Thursday, June 10, 2010

CodeProject Monthly Competition

Yesterday I saw that my latest article is listed for Voting under the section Best ASP.NET Article of May 2010. Its a beginner article about a simple Silverlight RSS Reader and I am happy to see that it helped some beginners.

If you like the article and think that it'll help some beginners then Vote for it.

http://www.codeproject.com/script/Surveys/VoteForm.aspx?srvid=1045

Thanks for your time.

[UPDATE]
Article won the CodeProject's monthly competition for Best ASP.NET Article of May 2010.
Thanks to you all for supporting me.

Wednesday, May 26, 2010

A Silverlight RSS Reader

A Silverlight RSS Reader

This article shows how to create a simple RSS Reader in silverlight.We can start creating a silverlight application from the Visual studio templates and it'll automatically create a silverlight project and a Web application into which silverlight is hosted.We need to fetch data from the feed url that a user is entered and for that purpose, we are going to use a WCF service so that the silverlight client can make asynchronous calls and can fetch the response.So Lets start by adding a WCF service to the Web application, here in my sample its RSSReaderService.svc.If we add WCF service directly to the Web application instead of creating a new service project, then the service will be hosted in the web application itself when we start the application. I  created a ServiceContract IRSSReaderService and added an OperationContract GetFeed(string uri), a method which defines an operation for the service contract.

namespace RSSReader.Web
{
  [ServiceContract]
  public interface IRSSReaderService
  {
    [OperationContract]
    IEnumerable<RSSItem> GetFeed(string uri);
  }
}

We need to implement the operation contract GetFeed(string uri) in our service code behind which is implementing IRSSReaderService.We are using  System.ServiceModel.Syndication, a namespace using for Syndication object model, for loading the syndication feed from the XmlReader instantiated with the specified feed url. For sending the properties from the feed to the client we created a DataContract RSSItem with DataMembers like Title,Summary,PublishDate and Permalink. We can customize the data members according to our requirement but here i am simply using these much information to send to the client.

[DataContract]
public class RSSItem
{
  [DataMember]
  public string Title { get; set; }

After creating this DataContract we create an XmlReader with the specified url and load the SyndicationFeed items from this XMLReader. Now we can use LINQ for iterating through this syndication items and for fetching the required information from those items.We are populating the RSSItem that we created and sending an IEnumerable of this object from the service to the client.So our GetFeed(string url) method implementation looks like,

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class RSSReaderService : IRSSReaderService
{

  public IEnumerable<RSSItem> GetFeed(string uri)
  {
    XmlReader reader = XmlReader.Create(uri);
    SyndicationFeed rssFeed = SyndicationFeed.Load(reader);

    var items = from p in rssFeed.Items
                select new RSSItem
                {
                   Title = p.Title.Text,
                   Summary = p.Summary.Text.Trim(),
                   Permalink = (p.Links.FirstOrDefault() != null) ? p.Links.FirstOrDefault().GetAbsoluteUri() : null,
                   PublishDate = p.PublishDate.LocalDateTime.ToString("dd/MMM/yyyy")
                };
    return items;
  }

}

So our service is completed and ready for consumption by the client.Now we need to create the silverlight client.Add service reference to the Silverlight project and then create a user control in the silverlight project, in the sample you can see the user control UC_RSSReader.xaml. I added some controls like ListBox in this usercontrol, templated and added binding for those controls.We edited the ItemTemplate for the ListBox and added custom data template which consist of TextBlocks and ListBox to display the feed data as required.We can customize this as per our requirement or as per the amount of data to be displayed.Now we are having the usercontrol that is binded to the corresponding properties. ListBox is displaying the feed data from the URL and the XAML looks like,

<ListBox x:Name="RSSFeed"
VerticalAlignment="Stretch"
HorizontalAlignment="Stretch"
Grid.Row="2"
Grid.ColumnSpan="2">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid MinWidth="{Binding ElementName=LayoutRoot, Path=ActualWidth}"
MaxWidth="{Binding ElementName=LayoutRoot, Path=ActualWidth}">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock Text="{Binding Title}"
FontFamily="Verdana"
FontSize="13" />
<TextBlock Grid.Row="2"
Text="{Binding PublishDate}"
HorizontalAlignment="Left"
FontFamily="Verdana"
FontSize="11" />
<HyperlinkButton Grid.Row="2"
Content="Read Article>>"
NavigateUri="{Binding Permalink}"
HorizontalAlignment="Center"
FontFamily="Verdana"
FontSize="11"
FontStyle="Italic"
ToolTipService.ToolTip="{Binding Title}"
TargetName="__blank" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

I am not using MVVM for this application as this is a very basic sample.Event subscribtion is straight forward and we have all the logic in the code behind itself.While clicking the fetch Button we are sending the request to the service with the feed url entered, fetching the data from the service and binding that result with ListBox. ListBox will display the Title, PublishDate and also a permalink to the original feed item.


private void FetchRSS_Click(object sender, RoutedEventArgs e)
{
  if (!string.IsNullOrEmpty(RSSFeedUrlTextBox.Text.Trim()) 
     && Uri.IsWellFormedUriString(RSSFeedUrlTextBox.Text.Trim(), UriKind.Absolute))
  {
    LoadingTextBlock.Visibility = Visibility.Visible;
    RSSFeed.Items.Clear();
    RSSReaderServiceClient RSSReaderServiceClient = new RSSReaderServiceClient();
    RSSReaderServiceClient.GetFeedCompleted += new EventHandler<GetFeedCompletedEventArgs>(RSSReaderServiceClient_GetFeedCompleted);
    RSSReaderServiceClient.GetFeedAsync((new Uri(RSSFeedUrlTextBox.Text)).ToString());                
  }
}

void RSSReaderServiceClient_GetFeedCompleted(object sender, GetFeedCompletedEventArgs e)
{
  RSSFeed.ItemsSource = e.Result;
  LoadingTextBlock.Visibility = Visibility.Collapsed;
}

Add this usercontrol to the main page and compile it.Before running the application don't forget to put the cross domain policy file in the web application root.Otherwise silverlight client can't communicate with the WCF service.If you get any run time errors for the sample application then delete and add the service reference again in the silverlight project.

Wednesday, March 31, 2010

Slideshow using Javascript

Slideshow using Javascript

This is a web application for displaying a slideshow using Asynchronous javascript and XML or AJAX, a simple SlideshowClient web application having next/previous manual image switching and normal Start/Stop slideshow options.This application basically using client side scripting using javascript and XMLHTTPRequest.Our ultimate aim is to show the images and switch them without posting the page back.So definitely we should use any client side scripting language for this asynchronous behavior and ofcourse javascript do the job.
If we are only using images, then we can directly change image control source within the javascript. But here we want some description or some display information for each image.So i choose a simple xml file to store the data required for the slideshow. I only added description here as informational data but we can add more details as per the requirement.
<?xml version="1.0" encoding="utf-8" ?>
<SlideshowClient>
<Slideshow>
<SlideshowId>1200</SlideshowId>
<ImagePath>/Images/IMG_1573.jpg</ImagePath>/>
<Description>Colors of Life</Description>
</Slideshow>
<Slideshow>
<SlideshowId>1201</SlideshowId>
<ImagePath>/Images/IMG_1209.jpg</ImagePath>/>
<Description>Leaf on the Floor</Description>
</Slideshow>
<Slideshow>
<SlideshowId>1202</SlideshowId>
<ImagePath>/Images/IMG_1229.jpg</ImagePath>/>
<Description>Street Light</Description>
</Slideshow>
<Slideshow>
<SlideshowId>1203</SlideshowId>
<ImagePath>/Images/IMG_1295.jpg</ImagePath>/>
<Description>Sunset</Description>
</Slideshow>
<Slideshow>
<SlideshowId>1204</SlideshowId>
<ImagePath>/Images/IMG_1201.jpg</ImagePath>/>
<Description>BackWater</Description>
</Slideshow>
</SlideshowClient>
In the web page i added some HTML controls required for the slideshow. So now comes the question. How it actually works? its not much complicated.I am using the hero XMLHttpRequest for getting the data from the server each time user interacts with the application.

//cross browser object for XMLHttpRequest
var xmlHttpRequest = (window.XMLHttpRequest) ? new window.XMLHttpRequest()
: new ActiveXObject('Microsoft.XMLHTTP');
xmlHttpRequest.open("GET", "/Data/SlideshowClientData.xml", false);
xmlHttpRequest.send(null);
//fetching the responseXML from the request
xmlDoc = xmlHttpRequest.responseXML;

We are fetching the response from responseXML attribute of the request object.So how we are going to parse this xml data? For parsing the xml data we use element.selectSingleNode("ElementName")and showing Next/Previous image and its description. But when i checked this behavior in different browsers i found this method is not supported in some browsers. So i tried for some workarounds and finally found Wrox's article
XPath support in Firefox. I added selectSingleNode prototype for Element for cross browser compatibility. If selectSingleNode method is not supported i am prototyping the method.

function ElementProtoType() {
if (document.implementation.hasFeature("XPath", "3.0")) {
//Some of the browsers not supporting selectSingleNode
Element.prototype.selectSingleNode = function(xPath) {
var evaluator = new XPathEvaluator();
var result = evaluator.evaluate(xPath, this, null,XPathResult.FIRST_ORDERED_NODE_TYPE, null);
if (result != null && result.singleNodeValue != null) {
result.singleNodeValue.nodeTypedValue = result.singleNodeValue.textContent;
return result.singleNodeValue;
}
else {
return null;
}
}
}
}

So now everything looks good and Next/previous will work in almost all browsers. So our basic logic for changing the image looks like,

function ShowNextImage() {
if (xmlDoc != null) {
var flag = false;
//Getting Previous image from data xml.
for (var i = 0; i < xmlDoc.documentElement.childNodes.length; i++) {
var element = xmlDoc.documentElement.childNodes[i];
if (element.nodeType == 1 && element.selectSingleNode("SlideshowId") != null &&
element.selectSingleNode("SlideshowId").nodeTypedValue == currentSlideshowId + 1) {
document.getElementById('slideshowimg').src = element.selectSingleNode("ImagePath").nodeTypedValue;
document.getElementById('description').innerHTML = element.selectSingleNode("Description").nodeTypedValue;
currentSlideshowId = currentSlideshowId + 1;
flag = true;
break;
}
}

if (!flag && interval != null && anchor != null) {
StopSlideshow(anchor);
}
}
}
I tested this application in almost all latest browsers including IE, Firefox, Google Chrome, Safari and it is working good.

PS : If we use larger size images adjust the timer according to the loading time for image otherwise in some browsers while playing the slideshow it wont get time to load the image and it'll only slide through the description.


Download Source Code,

Thursday, February 11, 2010

Visual Studio 2010 RC Released

Visual Studio 2010 RC is released with lot of cool features. I installed it but i don’t know when’ll i get time to experiment that as am busy with my projects. Anyway I want to try Charting Controls for ASP.NET & Windows Forms first. Charting control is looking nice. I hope I can post more code snippets for Visual Studio 2010 soon.
Splash Screen
 visualstudio_splash

Thursday, February 4, 2010

Getting Property Name using LINQ

Sometimes we want to compare the property names like,

if (e.PropertyName == "FirstName")
{
//Do Something

}


But this is not type safe. If we change the property name then this won’t work as expected and also it won’t throw compile time error. For getting property name for Type safe operations we can use LINQ. So if you change property name in future, you’ll get compile time error.
public string GetPropertyName<T>(Expression<Func<T>> expression)
{
   MemberExpression memberExpression=(MemberExpression)expression.Body;
   return memberExpression.Member.Name;
}
We can call this method using Expression Lambdas like,
if (e.PropertyName == GetPropertyName(() => Customer.FirstName))
{
  //Do Something
}

Monday, January 18, 2010

IdentityMine's Retail Map on Microsoft Surface at NRF 2010

Saturday, September 19, 2009

XML to Class in .NET – XML Schema Definition Tool(XSD.exe)

Most of us faced the scenario that we need to deserialize the xml data got from a service or some other source to an object.So how can we do that?Lets have a look at that.
First of all i have an XML like,
<?xml version="1.0" encoding="UTF-8" ?>
<Orders>
<Customer Id="001">
<Name>Customer1</Name>
<Address>Address1</Address>
<EmailId>EmailId</EmailId>
<Items>
<Item Id="100" Name="Item1"/>
<Item Id="101" Name="Item2"/>
</Items>
</Customer>
<Customer Id="002">
<Name>Customer2</Name>
<Address>Address1</Address>
<EmailId>EmailId</EmailId>
<Items>
<Item Id="103" Name="Item3"/>
<Item Id="103" Name="Item4"/>
</Items>
</Customer>
</Orders>
So we need to generate a class from this XML.Here comes XML Schema Definition Tool or XSD.exe.So we are creating an XML Schema definition first from the above XML.
  • Go to Visual Studio>Visual Studio Tools>Visual Studio Command Prompt.
  • Navigate to the folder where we have the XML data or we can directly target the xml path.I am navigating to the folder having above xml and type the command xsd.exe Customer.xml and this'll generate a schema definition file Customer.xsd.

    XML Schema Definition looks like,
<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="Orders" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xs:element name="Orders" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
<xs:complexType>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="Customer">
<xs:complexType>
<xs:sequence>
<xs:element name="Name" type="xs:string" minOccurs="0" msdata:Ordinal="0" />
<xs:element name="Address" type="xs:string" minOccurs="0" msdata:Ordinal="1" />
<xs:element name="EmailId" type="xs:string" minOccurs="0" msdata:Ordinal="2" />
<xs:element name="Items" minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="Item" minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:attribute name="Id" type="xs:string" />
<xs:attribute name="Name" type="xs:string" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="Id" type="xs:string" />
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
</xs:element>
</xs:schema>
  • Now use command, xsd.exe Customer.xsd /c, for generate class from the schema definition file. It'll generate a class with default language as C#,customer.cs is generated in the folder and its having partial class Orders,
     /// <remarks/>
     [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
   public partial class Orders {
Please note : you can see type OrdersCustomerItemsItem[][] for Items property and for its private variable.Change it as OrdersCustomerItemsItem[],Otherwise while Deserializing it'll show error.
  • By Using System.Xml.Serialization.XmlSerializer we can Deserialize the XML to Order object.

    private void PopulateData()
    {
        StreamReader stream = new StreamReader("Customer.xml");
        XmlSerializer serializer = new XmlSerializer(typeof(Orders));
        Orders orders = (Orders)serializer.Deserialize(stream);
    OrdersList.ItemsSource = orders.Items;
    }
  • Build and Run the application you can see the Customers displayed in the UI.

Friday, August 14, 2009

Implementing INotifyPropertyChanged

If an object implementing INotifyPropertyChanged Interface it’ll raise a property changed event when its property changes.Lets create a sample application to know how we can implement INotifyPropertyChanged Interface. I am creating a Silverlight application which demonstrates the data binding with both an object implementing INotifyPropertyChanged and also a normal DependencyProperty.
  • Open Visual Studio and select a new silverlight application.
  • Create a class named Customer in the silverlight project and implement INotifyPropertyChanged.
public class Customer : INotifyPropertyChanged
{
  • Define INotifyPropertyChanged Members,
public event PropertyChangedEventHandler PropertyChanged;

public void OnPropertyChanged(PropertyChangedEventArgs e)
{
   if (PropertyChanged != null)
   {
     PropertyChanged(this, e);
   }
}
  • In property setter invoke OnPropertyChanged by passing property name like,
private string _Name;

public string Name
{
  get
  {
     return _Name;
  }
  set
  {
    _Name = value;
    OnPropertyChanged(new PropertyChangedEventArgs("Name"));
  }
}
  • In MainPage.xaml.cs add an ObservableCollection of customer object as Dependency
    property inorder to make sure that UI is updating while we assigning that customer list
    to another list or object.If we are making it as a normal property UI will update only if
    we add new object to customerlist or any change occurs to the underlying properties.
public ObservableCollection<Customer> CustomerList
{
  get { return (ObservableCollection<Customer>)
GetValue(CustomerListProperty); }
  set { SetValue(CustomerListProperty, value); }
}

// Using a DependencyProperty as the backing store for MyProperty.
This enables animation, styling, binding, etc...
public static readonly DependencyProperty CustomerListProperty =
DependencyProperty.Register("CustomerList",
typeof(ObservableCollection<Customer>), typeof(MainPage),
    new PropertyMetadata(new ObservableCollection<Customer>()));
  • I also added a DependencyProperty FirstName in MainPage.xaml.cs just to show the binding of a simple DependencyProperty.
public string FirstName
{
  get { return (string)GetValue(FirstNameProperty); }
  set { SetValue(FirstNameProperty, value); }
}

// Using a DependencyProperty as the backing store for MyProperty.
This enables animation, styling, binding, etc...
public static readonly DependencyProperty FirstNameProperty =
  DependencyProperty.Register("FirstName", typeof(string), typeof(MainPage),
  new PropertyMetadata(string.Empty)); 
  • In MainPage.XAML add a datagrid and textbox and bind it to the ObservableCollection and DependencyProperty respectively.
<data:DataGrid AutoGenerateColumns="True"
 Width="400"
 Height="300"
 ItemsSource="{Binding ElementName=TestUC,
                                Path=CustomerList}"/>
<TextBox x:Name="NameTextBox"
Text="{Binding ElementName=TestUC, Path=FirstName, Mode=TwoWay}"
Width="100"
Height="25"
Margin="0,10,0,10" />
  • For Understanding PropertyChanged event, I added a button and just updating the customer object in the click event so that you can see the changes in the datagrid.When you change the property of Customer object from click event you can see that the UI is updating accordingly.
  • Download Sample Application.

Thursday, July 30, 2009

Silverlight With WCF Service

How to use a WCF Service from a silverlight client?Let us discuss how we can achieve that.Sample application is also attached in the bottom of this article.
    • Open Visual Studio and Create a new Silverlight application by selecting any of the available project templates in visual studio.Here i am selecting Silverlight Navigation Application,
image
image
This will create a silverlight project and a Web project in the solution.
    • Right Click the solution and Add a New WCF Service Application,
image
    • Create service methods in the WCF Service Application.
    • Add Service Reference to the Silverlight application by right clicking it and select Add Service Reference.
image
    • Add crossdomain.xml file to the WCF Service Project for enabling silverlight application to access the WCF Service.If WCF service is hosted in a web application then add policy file to the web application.
    • Try to access the service methods in silverlight application using the service reference added.
    • Download Silverlight & WCF Service Sample Application.If you get any run time errors for the sample application then delete and add the service reference again in the silverlight project.


Another sample application - A Silverlight RSS Reader

Thursday, July 23, 2009

Microsoft Tag Reader

Today i installed Microsoft Tag Reader in my Mobile - N73 Symbian S60 3rd Edition.Application will decode a tag printed some where by using the mobile camera and also open the related web content.
Download Tag Reader for your mobile and try it out.Its cool.

Silverlight 3 Features

Resources for Silverlight 3 ,

Monday, June 29, 2009

Immediate Loading Relational Data in LINQ to SQL

In LINQ to SQL the relational data is loading only when we refer that data, other terms its lazy loading of data.But we can load relational data ,suppose we have an Employee Table and also having an Employee details table related to Employee Table, we can load that relational data using DataLoadOptions while querying the context.
DataLoadOptions options = new DataLoadOptions();
options.AssociateWith<Employee>(p => p.EmployeeDetails.
Where(q => q.IsActive == false));
options.LoadWith<Employee>(p => p.EmployeeDetails);
Context.LoadOptions = options;
var emp = from p in DataContext.Employee
where p.EmployeeID == employeeID &&
p.IsDeleted == false
select p

Thursday, May 28, 2009

Microsoft Surface Videos

Watch some cool Microsoft Surface Videos here.
Hope you’ll enjoy.

Wednesday, May 27, 2009

AjaxControlToolkit New Version

AjaxControlToolkit version 3.0.30512 is released with  3 new controls,
  • HTMLEditor
  • ComboBox
  • ColorPicker

Friday, May 22, 2009

Visual Studio 2010 Professional Beta 1

Finally here comes what we’ve been waiting.Next Generation of Visual Studio is on move.Visual Studio 2010 Professional Beta 1 is now available for Download.
Enjoy

Tuesday, May 19, 2009

ElementMenu in Microsoft Surface

Microsoft Surface 1.0 SP1 introduced a new control named ElementMenu.ElementMenu in surface SDK provides you a new way to display the data in a new hierarchical manner.ElementMenu implementing SurfaceItemsControl and its a collection of ElementMenuItem.I created a sample application using this ElementMenu just to checking out how its looking.Of course its pretty cool.

Create a Surface Project.In surfaceWindow1 add ElementMenu Control from Toolbox.

<s:ElementMenu Name="MainMenu">

</
s:ElementMenu>
Add child ElementMenuItem controls.

<s:ElementMenu Name="MainMenu"
VerticalAlignment="Bottom">
<
s:ElementMenuItem Header="Honda">
<
s:ElementMenuItem x:Name="MenuItem1"
Header="Civic"
Click="MenuItem1_Click" />
<
s:ElementMenuItem Header="CRV"
Command="local:SurfaceWindow1.MenuItemCommand" />
<
s:ElementMenuItem Header="City"
Click="MenuItem1_Click" />
<
s:ElementMenuItem Header="Accord"
Command="local:SurfaceWindow1.MenuItemCommand" />
</
s:ElementMenuItem>
</s:ElementMenu>
Here i added two levels of ElementMenuItem for the ElementMenu.We can handle the click event by either using Click Event handler or using Command.Here i am using both for different Element Menu Items.Using Click Event handler is straight forward.But if we are using command first create a RoutedCommand in the code behind,

public static readonly RoutedCommand MenuItemCommand = new RoutedCommand();
Then add this command to the Window’s CommandBindings.Here am using XAML for adding the command to the command collection,

<Window.CommandBindings>
<
CommandBinding Command="local:SurfaceWindow1.MenuItemCommand"
Executed="CommandBinding_Executed" />
</
Window.CommandBindings>
where local is the reference to the current assembly,

xmlns:local="clr-namespace:MySurfaceApplication"
SurfaceWindow1 is the Class name.Add this command to the Element Menu Item as in the above code snippet.Add CommandBinding_Executed in the code behind,

private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
CarDetails.Text = (e.OriginalSource as ElementMenuItem).Header.ToString();
}
So now my whole XAML looks like,

<s:SurfaceWindow x:Class="MySurfaceApplication.SurfaceWindow1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:s="http://schemas.microsoft.com/surface/2008"
xmlns:local="clr-namespace:MySurfaceApplication"
Title="MySurfaceApplication">
<
Window.CommandBindings>
<
CommandBinding Command="local:SurfaceWindow1.MenuItemCommand"
Executed="CommandBinding_Executed" />
</
Window.CommandBindings>

<
Grid>
<
Grid.RowDefinitions>
<
RowDefinition />
<
RowDefinition />
</
Grid.RowDefinitions>
<
TextBlock x:Name="Comparison"
Grid.Row="0"
Text="Car Comparison"
VerticalAlignment="Bottom"
HorizontalAlignment="Center"
Foreground="White"
Background="Blue">
<
s:ElementMenu Name="MainMenu"
VerticalAlignment="Bottom"
ActivationMode="HostInteraction"
ActivationHost="{Binding ElementName=Comparison}">
<
s:ElementMenuItem Header="Honda">
<
s:ElementMenuItem x:Name="MenuItem1"
Header="Civic"
Click="MenuItem1_Click" />
<
s:ElementMenuItem Header="CRV"
Command="local:SurfaceWindow1.MenuItemCommand" />
<
s:ElementMenuItem Header="City"
Click="MenuItem1_Click" />
<
s:ElementMenuItem Header="Accord"
Command="local:SurfaceWindow1.MenuItemCommand" />
</
s:ElementMenuItem>
</
s:ElementMenu>
</
TextBlock>
<
TextBlock x:Name="CarDetails"
Height="200"
Width="200"
Grid.Row="1"
Text="Car Details"
VerticalAlignment="Center"
Background="DarkRed"
HorizontalAlignment="Center" />
</
Grid>
</
s:SurfaceWindow>
and code behind like(using directives removed),

namespace MySurfaceApplication
{
/// <summary>
///
Interaction logic for SurfaceWindow1.xaml
/// </summary>
public partial class SurfaceWindow1 : SurfaceWindow
{
public static readonly RoutedCommand MenuItemCommand = new RoutedCommand();
/// <summary>
///
Default constructor.
/// </summary>
public SurfaceWindow1()
{
InitializeComponent();
// Add handlers for Application activation events
AddActivationHandlers();

}


/// <summary>
///
Occurs when the window is about to close.
/// </summary>
/// <param name="e"></param>
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);

// Remove handlers for Application activation events
RemoveActivationHandlers();
}

/// <summary>
///
Adds handlers for Application activation events.
/// </summary>
private void AddActivationHandlers()
{
// Subscribe to surface application activation events
ApplicationLauncher.ApplicationActivated += OnApplicationActivated;
ApplicationLauncher.ApplicationPreviewed += OnApplicationPreviewed;
ApplicationLauncher.ApplicationDeactivated += OnApplicationDeactivated;
}

/// <summary>
///
Removes handlers for Application activation events.
/// </summary>
private void RemoveActivationHandlers()
{
// Unsubscribe from surface application activation events
ApplicationLauncher.ApplicationActivated -= OnApplicationActivated;
ApplicationLauncher.ApplicationPreviewed -= OnApplicationPreviewed;
ApplicationLauncher.ApplicationDeactivated -= OnApplicationDeactivated;
}

/// <summary>
///
This is called when application has been activated.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnApplicationActivated(object sender, EventArgs e)
{
//TODO: enable audio, animations here
}

/// <summary>
///
This is called when application is in preview mode.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnApplicationPreviewed(object sender, EventArgs e)
{
//TODO: Disable audio here if it is enabled

//TODO: optionally enable animations here
}

/// <summary>
///
This is called when application has been deactivated.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnApplicationDeactivated(object sender, EventArgs e)
{
//TODO: disable audio, animations here
}

private void MenuItem1_Click(object sender, RoutedEventArgs e)
{
CarDetails.Text = (e.OriginalSource as ElementMenuItem).Header.ToString();
}

private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
CarDetails.Text = (e.OriginalSource as ElementMenuItem).Header.ToString();
}
}
}

Build and Run the application.thumbs_up

Friday, May 15, 2009

Tagged Objects in Microsoft Surface – TagVisualizer,TagVisualization,TagVisualizationDefinition

Microsoft introduced a new concept called Tag driven application or Tagged Objects in Surface SDK through which the surface can identify Objects placed over the surface table.Object is printed with some tags that surface engine can read.Tags are either Byte Tags or Identity Tags.

How we can achieve this using Surface SDK?Let’s have a look at that.
I tried a sample by using Tagged Objects in Surface SDK.

Tag Visualization is possible by using these three classes,

  • TagVisualizer – is what actually responding to the Tagged Object and showing up the TagVisualization when placing a tag.
  • TagVisualization - is what we are showing in the surface when a tag is placed in the surface.
  • TagVisualizationDefinition – is using for defining the tag value to which the TagVisualizer will respond and also source, physical location,orientation and other properties of the visualization.

So Let’s try a sample.

  • Create a Surface project from the Visual Studio 2008 Template.
  • In the SurfaceWindow1 add a TagVisualizer.
<s:TagVisualizer Name="TagVisualizer">


</s:TagVisualizer>
  • Add a TagVisualization to the project.Add New Item>TagVisualization.I created TagVisualization SampleTagVisualization,

<s:TagVisualization x:Class="MySurfaceApplication.SampleTagVisualization"        
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:s="http://schemas.microsoft.com/surface/2008"
Loaded="SampleTagVisualization_Loaded">
<
Grid Height="400"
Width="600"
Background="White">
<
TextBlock Text="Some Tagged Object UI here."
VerticalAlignment="Center"
HorizontalAlignment="Center"
Foreground="Red" />
</
Grid>
</
s:TagVisualization>
  • Add TagVisualizationDefinition to SurfaceWindow1 for TagVisualizer.We can add this either by XAML or from code behind,

Either From XAML,


<s:TagVisualizer Name="TagVisualizer">
<
s:TagVisualizer.Definitions>
<
s:ByteTagVisualizationDefinition Value="192"
Source="SampleTagVisualization.xaml"
UsesTagOrientation="True"
TagRemovedBehavior="Fade"
PhysicalCenterOffsetFromTag="7.5,4.5"/>
</
s:TagVisualizer.Definitions>
</
s:TagVisualizer>
or From code behind,(add it in the constructor)

ByteTagVisualizationDefinition tagVisualizationDefinition = new 
ByteTagVisualizationDefinition
();
tagVisualizationDefinition.Value = 192;
tagVisualizationDefinition.Source = new Uri("SampleTagVisualization.xaml",
UriKind.Relative);
tagVisualizationDefinition.UsesTagOrientation = true;
tagVisualizationDefinition.TagRemovedBehavior = TagRemovedBehavior.Fade;
tagVisualizationDefinition.PhysicalCenterOffsetFromTag = new
Vector
(7.5, 4.5);
TagVisualizer.Definitions.Add(tagVisualizationDefinition);
Build and Run the application in Surface Simulator.Tag Value is here 192.So give Tag Value as C0 (Hexadecimal).

Thursday, April 30, 2009

ScatterView in Microsoft Surface SDK

Microsoft SDK provides a control named ScatterView which acts like a container and we can move,resize or rotate the object which is placed inside the ScatterView Container.There is no need to create events or code for doing this.ScatterView will automatically handle all the Events.Definitely users will find this as a very cool feature.I created my first Surface application with ScatterView.Its pretty simple doing this and of course cool.

  • Create a Surface Project from Visual Studio Template.
  • Add ScatterView Control.

ScatterView contains collection of ScatterViewItem.Add Objects to ScatterView either inside a ScatterViewItem or we can directly add objects to the ScatterView.

The ScatterView looks either like,

<s:ScatterView>
<s:ScatterViewItem Width="200" Height="200" Center="500,300"
Orientation="315" >
<Image Source="Images/Forest.jpg" Stretch="Fill"></Image>
</s:ScatterViewItem>
</s:ScatterView>

OR like,

<s:ScatterView>
<Image Source="Images/Forest.jpg" Stretch="Fill"></Image>
</s:ScatterView>

I am adding an Image to the ScatterView so that we can manipulate like resize,rotate or move the image.




Monday, April 27, 2009

IValueConverter in WPF

Converters are mainly using in WPF when there is a need to convert a value to another value just like converting a Boolean to Visibility.

public class CustomConverter : IValueConverter
{
#region IValueConverter Members

public object Convert(object value, Type targetType, object parameter,
CultureInfo culture)
{
if (value ==null)
return false;
return true;

}

public object ConvertBack(object value, Type targetType, object parameter,
CultureInfo culture)
{
throw new NotImplementedException();
}

#endregion
}

Here CustomConverter is implementing IValueConverter.We can use this converter in the XAML.First add this Converter in the resources,
<local:CustomConverter x:Key="CustomConverter" />
where local is the reference to the assembly where CustomConverter is defined.
Use this Converter in Controls DataBinding like,
IsEnabled="{Binding ElementName=ListBoxName, Path=SelectedItem,
Converter={StaticResource CustomConverter}}"