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