Alistair Findlay logo

VB.NET C# Comparison Cheat Sheet Part 3: Generics, Lambdas, Extensions and LINQ

The following is the third part of a cheat sheet to help give an overview of the differences in syntax between VB.NET and C#, in .NET 4.0. Most of the examples touch on much deeper concepts, so I’ve included a few references at the end to help you out! In particular, the LINQ section seems quite brief but this is mainly because the syntax is very similar between the two languages.

Part 3:

Previous parts:

In addition to these cheat sheets, you can also use Developer Fusion’s online conversion tool to make some comparisons of your own.

Generics

VB.NET C#
Public Class GenericClass(Of T)

	Public Sub GenericMethod(param As T)
		Debug.WriteLine("Type = " &
				param.GetType().ToString())
	End Sub

End Class
public class GenericClass<T>
{
	public void GenericMethod(T param) {
		Debug.WriteLine("Type = " +
			param.GetType().ToString());
	}
}
Dim integerGeneric As New  _
	GenericClass(Of Integer)()

' Outputs "Type = System.Int32"
integerGeneric.GenericMethod(0)
GenericClass<int> integerGeneric =
	new GenericClass<int>();

// Outputs "Type = System.Int32"
integerGeneric.GenericMethod(0);
Public Class ConstrainedClass(Of T As Control)
	Public Sub GenericMethod(param As T)
		Debug.WriteLine(param.Text)
	End Sub
End Class
public class ConstrainedClass<T> where T : Control
{
	public void GenericMethod(T param)
	{
		Debug.WriteLine(param.Text);
	}
}
Dim txt As New TextBox() With {
	.Text = "Hello!"
}

Dim tbGeneric As New  _
	ConstrainedClass(Of TextBox)
' Outputs the contents of the TextBox
tbGeneric.GenericMethod(txt)
TextBox txt = new TextBox() {
	Text = "Hello!"
};

ConstrainedClass<TextBox> tbGeneric =
	new ConstrainedClass<TextBox>();
// Outputs the contents of the TextBox
tbGeneric.GenericMethod(txt);
Public Class PaintMixer(Of T As IPaintColour)

	Public Function MixThreeColours(
		p1 As T, p2 As T, p3 As T) As T
		Return p1.Mix(p2).Mix(p3)
	End Sub

End Class
public class PaintMixer<T> where T : IPaintColour
{
	public T MixThreeColours(T p1, T p2, T p3)
	{
		return p1.Mix(p2).Mix(p3);
	}
}
Public Class ReverseSorter(Of T As List(Of Integer))

	Public Sub ReverseSort(param As T)
		param.Sort()
		param.Reverse()
	End Sub

End Class
public class ReverseSorter<T> where T : List<int>
{
	public void ReverseSort(T param)
	{
		param.Sort();
		param.Reverse();
	}
}
Public Class MultiConstrained(
	Of T As Control,
	U As {New, TextBox})

End Class
public class MultiConstrained<T, U>
	where T : Control
	where U : TextBox, new()
{

}
Dim genericList As List(Of Integer)
List<int> genericList;
Dim genericDictionary As Dictionary(Of Guid, Integer)
Dictionary<Guid, int> genericDictionary;
Dim genericLookup As Lookup(Of Guid, Integer)
Lookup<Guid, int> genericLookup;

Lambda Expressions

VB.NET C#
Delegate Sub LogTime()

Shared Sub LogTimeNow()

	Dim del As LogTime = _
		Sub() Debug.WriteLine(DateTime.Now)

	del() ' This invokes the function

End Sub
delegate void LogTime();

static void LogTimeNow()
{
	LogTime del =
		() => Debug.WriteLine(DateTime.Now);

	del(); // This invokes the function
}
Delegate Function StartsWith(param As String) As Boolean

Function StartsWithA(param As String) As Boolean

	Dim del As StartsWith = Function(x) x.StartsWith("A")
	Return del(param)

End Function
delegate bool StartsWith(string param);

bool StartsWithA(string param)
{
	StartsWith del = x => x.StartsWith("A");
	return del(param);
}
'  Alternative to above, without using delegate variable
Function StartsWithA(param As String) As Boolean

	Dim del As Func(Of String, Boolean) =
			Function(x) x.StartsWith("A")
	Return del(param)

End Function
// Alternative to above, without using delegate variable
bool StartsWithA(string param)
{
	Func<string, bool> del =
			x => x.StartsWith("A");
	return del(param);
}
Dim grub As String() =
	{"Mars bar", "Toffee Crisp", _
	"Pork pie", "Bounty"}

Dim sweets = grub.Where( _
	Function(x) x <> "Pork Pie")
string[] grub =
	{"Mars bar", "Toffee Crisp",
	"Pork pie", "Bounty"};

var sweets = grub.Where(
		x => x != "Pork pie");
' Using del lamdba from above
Dim grubBeginningWithA = grub.Where(del)
// Using del lamdba from above
var grubBeginningWithA = grub.Where(del);

Extension methods

VB.NET C#
' This is the definition of the extension

Imports System.Runtime.CompilerServices

Namespace CustomExtensions

    Public Module StringExtensions

        <Extension()>
        Public Function StartsWithA(
                ByVal param As String) As Boolean

            Return param.StartsWith("A")

        End Function

    End Module

End Namespace
// This is the definition of the extension

namespace CustomExtensions
{
    public static class StringExtensions
    {
        public static bool StartsWithA(this string param)
        {
            return param.StartsWith("A");
        }
    }
}
' Usage of the extension above

Imports CustomExtensions.StringExtensions

Public MustInherit Class MainClass

    Public Shared Function StartsWithA(
		param As String) As Boolean
        Return param.StartsWithA()
    End Function

End Class
// Usage of the extension above

using CustomExtensions;

public static class MainClass
{
    public static bool StartsWithA(string param)
    {
        return param.StartsWithA();
    }
}
Dim numbers As Integer() = {0, 1, 2, 3, 4, 5}
Dim listOfNumbers As List(Of Integer) = numbers.ToList()
int[] numbers = { 0, 1, 2, 3, 4, 5 };
List<int> listOfNumbers = numbers.ToList();
Dim first As Integer = numbers.FirstOrDefault()
int first = numbers.FirstOrDefault();

LINQ

VB.NET C#
Dim query = From n As Integer In numbers
			Where n > 3
			Select n
var query = from int n in numbers
			where n > 3
			select n;
Dim samequerywithlambda =
    numbers.Where(Function(n) n > 3)
var samequerywithlamdba =
	numbers.Where(n => n > 3);
' LINQ to XML
Dim xCrisps = <Crisps>
				  <Crisp>Ready salted</Crisp>
				  <Crisp>Salt n vinegar</Crisp>
				  <Crisp>Hedgehog</Crisp>
			  </Crisps>

Dim first As XElement =
	xCrisps.<Crisp>.FirstOrDefault()
// LINQ to XML
XElement xCrisps = new XElement("Crisps",
	new XElement("Crisp", "Ready salted"),
	new XElement("Crisp", "Salt n vinegar"),
	new XElement("Crisp", "Hedgehog")
);

XElement first = (from x in xCrisps.Elements()
					select x).FirstOrDefault();
Dim hedgehog As XElement =
	(From x In xCrisps...<Crisp>
	 Where x.Value = "Hedgehog"
	 Select x).FirstOrDefault()
XElement hedgehog =
	(from x in xCrisps.Descendants("Crisp")
	where x.Value == "Hedgehog"
	select x).FirstOrDefault();
Dim lastoneis As String =
	(From x In xCrisps...<Crisp>
	 Select "Last = " & x.Value).Last()
string lastoneis =
	(from x in xCrisps.Descendants("Crisp")
	 select "Last =  " + x.Value).Last();
Dim txtWithFirstEntry As TextBox =
	(From x In xCrisps...<Crisp>
		Select New TextBox() With
		{.Text = x.Value}).First()
TextBox txtWithFirstEntry =
	(from x in xCrisps.Descendants("Crisp")
	 select new TextBox()
	 { Text = x.Value }).First();
' LINQ to SQL or Entity Framework
Using context As New SweetsEntities()

	Dim marsBarPrice As Decimal? =
		(From c In context.Chocolates
		 Where c.Name = "Mars bar"
		 Select c.Price).FirstOrDefault()

End Using
// LINQ to SQL or Entity Framework
using (SweetsEntities context = new SweetsEntities())
{
	decimal? marsBarPrice =
		(from Chocolate c in context.Chocolates
		where c.Name == "Mars bar"
		select c.Price).FirstOrDefault();
}

References

The following links go into a bit more depth with some of the concepts above:

  • No Comments »

VB.NET C# Comparison Cheat Sheet Part 2: Object-oriented programming

The following is the second part of a cheat sheet to help give an overview of the differences in syntax between VB.NET and C#, in .NET 4.0. Some of the examples are more complicated than those in part 1 (particularly the events examples), so I’ve included a few references at the end to help you out!

Part 2:

You can find Part 1 here: The Basics. Yet to come:

In addition to these cheat sheets, you can also use Developer Fusion’s online conversion tool to make some comparisons of your own.

Class declarations and Constructors/Destructors

VB.NET C#
Imports System.Text
using System.Text;
Namespace ApplicationNamespace
    Public Class Class1

    End Class
End Namespace
namespace ApplicationNamespace
{
    public class Class1
    {
    }
}
Public Partial Class PartialClass

End Class
public partial class PartialClass
{
}
Public Module Module1

End Module
public static class StaticClass
{
}
Public Class SimpleClass
	Public Sub New()

	End Sub
	Protected Overrides Sub Finalize()
		MyBase.Finalize()
	End Sub
End Class
public class SimpleClass
{
	public SimpleClass()
	{
		// Constructor
	}

	~SimpleClass(); // Destructor
}
Public Class AnotherClass

	Public Sub New(a As String)

	End Sub
	Public Sub New(a As String, b As String)
		Me.New(a)
	End Sub

	Protected Overrides Sub Finalize()
		MyBase.Finalize()
	End Sub

End Class
public class AnotherClass
{
	public AnotherClass(string a)
	{
		Debug.WriteLine("Simple constructor");
	}
	public AnotherClass(string a, string b) :
		this(a)
	{
		Debug.WriteLine("Complex constructor");
	}

	~AnotherClass();
}

Class Inheritance and OO concepts

VB.NET C#
Public Class ExtendedTextBox
	Inherits TextBox

	Public Sub New()
		MyBase.New()
	End Sub

	Protected Overrides Sub Finalize()
		MyBase.Finalize()
	End Sub

End Class
public class ExtendedTextBox : TextBox
{
	public ExtendedTextBox()
		: base()
	{

	}

	~ExtendedTextBox();
}
Public MustInherit Class AbstractClass

	Public Shared Sub StaticSub()
		Debug.WriteLine("Static Function!")
	End Sub

	Public MustOverride Sub AbstractSub()

End Class
public abstract class AbstractClass {

	public static void StaticFunction()
	{
		Debug.WriteLine("Static Function!");
	}

	public abstract void AbstractFunction();

}
Public Class ClassWithOverridable

	Public Overridable Sub OverridableSub()
		Debug.WriteLine("Default!")
	End Sub

End Class

Public Class OverridingClass
	Inherits ClassWithOverridable

	Public Overrides Sub OverridableSub()
		' MyBase.OverridableSub()
		Debug.WriteLine("Overriden!")
	End Sub

End Class
public class ClassWithOverridable
{
	public virtual void OverrideableFunction()
	{
		Debug.WriteLine("Default!");
	}
}

public class OverridingClass : ClassWithOverridable
{
	public override void OverrideableFunction()
	{
		// base.OverrideableFunction();
		Debug.WriteLine("Overriden!");
	}
}
Public Class ShadowingClass
	Inherits ClassWithOverridable

	Public Shadows Sub OverridableSub()
		Debug.WriteLine("Shadows!")
	End Sub

End Class
public class ShadowingClass : ClassWithOverridable
{
	public new void OverrideableFunction()
	{
		Debug.WriteLine("Shadows!");
	}
}
Public NotInheritable Class SealedClass

End Class
public sealed class SealedClass
{
}

Interfaces

VB.NET C#
Public Interface SimpleInterface

	Sub InterfaceSub()

End Interface

Public Class SimpleImplementer
	Implements SimpleInterface

	Public Sub InterfaceSub() _
		Implements SimpleInterface.InterfaceSub

	End Sub

End Class
public interface SimpleInterface
{
	void InterfaceFunction();
}

public class SimpleImplementer : SimpleInterface
{
	public void InterfaceFunction()
	{

	}
}
Public Interface Interface1
	Sub Function1()
End Interface

Public Interface Interface2
	Sub Function2()
End Interface

Public Class MultipleImplementer
	Implements Interface1, Interface2

	Public Sub Function1() _
		Implements Interface1.Function1
		Debug.WriteLine("Concrete func 1")
	End Sub

	Public Sub Function2() _
		Implements Interface2.Function2
		Debug.WriteLine("Concrete func 2")
	End Sub
End Class
public interface Interface1
{
	void Function1();
}
public interface Interface2
{
	void Function2();
}

public class MultipleImplementer :
	Interface1, Interface2
{
	public void Function1()
	{
		Debug.WriteLine("Concrete func 1");
	}
	public void Function2()
	{
		Debug.WriteLine("Concrete func 2");
	}
}

Delegates and Event Handlers

VB.NET C#
Public Class Delegates

	Delegate Sub Delegate1(ByVal param As String)

	Public Sub InvokeDelegate(del As Delegate1)
		del.Invoke("Invoke!")
	End Sub

End Class
public class Delegates
{
	delegate void Delegate1(string param);

	public void InvokeDelegate(Delegate1 del)
	{
		del.Invoke("Invoke!");
	}
}
''' <summary>
''' Calling DoRaise raises the event
''' </summary>
Public Class EventRaiser

	Public Event OnRaise(ByVal param As String)

	Public Sub DoRaise(ByVal param As String)
		RaiseEvent OnRaise(param)
	End Sub

End Class
/// <summary>
/// C# uses a delegate that can be seen
/// by the raising and handling classes
/// </summary>
public delegate void EventDelegate(string param);

/// <summary>
/// Calling DoRaise raises the event
/// </summary>
public class EventRaiser
{
	public event EventDelegate OnRaise;

	public void DoRaise(string param)
	{
		OnRaise(param); // Invoke
	}
}
''' <summary>
''' Class handles raised events from EventRaiser
''' </summary>
Public Class EventHandlerClass

	Private mEvt As EventRaiser

	Public Sub New()
		mEvt = New EventRaiser()
		AddHandler mEvt.OnRaise, _
				AddressOf HandleIt
	End Sub

	Private Sub HandleIt(ByVal param As String)
		Debug.WriteLine(param)
	End Sub

	Protected Overrides Sub Finalize()
		MyBase.Finalize()
		RemoveHandler mEvt.OnRaise, _
				AddressOf HandleIt
	End Sub

End Class
/// <summary>
/// Class handles raised events from EventRaiser
/// </summary>
public class EventHandlerClass
{
	private EventRaiser mEvt;

	public EventHandlerClass()
	{
		mEvt = new EventRaiser();
		mEvt.OnRaise += new EventDelegate(
					HandleIt);
	}

	void HandleIt(string param)
	{
		Debug.WriteLine(param);
	}

	~EventHandlerClass()
	{
		mEvt.OnRaise -= new EventDelegate(
					HandleIt);
	}
}
Public Class EntryForm

    Public WithEvents mTextBox As TextBox

    Public Sub New()
        mTextBox = New TextBox()
    End Sub

    Private Sub mTextBox_KeyDown(sender As Object,
		e As KeyEventArgs) _
		Handles mTextBox.KeyDown

        Debug.WriteLine("Handle key down")

    End Sub

End Class
public class EntryForm
{
	private TextBox mTextBox;

	public EntryForm()
	{
		mTextBox.KeyDown +=
			new KeyEventHandler(mTextBox_KeyDown);
	}

	void mTextBox_KeyDown(object sender,
				KeyEventArgs e)
	{
		Debug.WriteLine("Handle key down");
	}

	~EntryForm()
	{
		mTextBox.KeyDown -=
			new KeyEventHandler(mTextBox_KeyDown);
	}
}

References

The following links go into a bit more depth with some of the concepts above:

  • No Comments »

VB.NET C# Comparison Cheat Sheet Part 1: The Basics

The following is the first part of a cheat sheet to help give an overview of the differences in syntax between VB.NET and C#, in .NET 4.0. It’s by no means exhaustive but will hopefully highlight the essentials! Please note that the table misses out some of the simpler operators, such as +, – etc, to save space.

Part 1:

The next parts:

In addition to these cheat sheets, you can also use Developer Fusion’s online conversion tool to make some comparisons of your own.

Variables, Enums, Properties

VB.NET C#
Dim s As String = "Hello!"
string s = "Hello!";
Dim txt As New TextBox() With {
	.Text = "Hello!"
}
TextBox txt = new TextBox()
{
	Text = "Hello!"
};
Private mStr1 As String
private string mStr1;
Protected mStr2 As String
protected string mStr2;
Protected Friend mStr3 As String
protected internal mStr3;
Friend mStr4 As String
internal string mStr4;
Public mStr5 As String
public string mStr5;
Private Const CONST_STRING As String = "Constant"
private const string CONST_STRING = "Constant";
Private Enum Options
	None = 0
	LemonAndLime = 1
	Vimto = 2
	Creamichoc = 3
End Enum
private enum Options
{
	None = 0,
	LemonAndLime = 1,
	Vimto = 2,
	Creamichoc = 3
}
<Flags()>
Private Enum BitWiseFlags
	One
	Two
	Four
	Eight
End Enum
[Flags]
private enum BitWiseFlags {
	One,
	Two,
	Four,
	Eight
}
Public Property Title As String
public string Title;
Private mForename As String
Public ReadOnly Property Forename As String
	Get
		Return mForename
	End Get
End Property
string mForename;
public string Forename
{
	get
	{
		return mForename;
	}
}
Private mSurname As String
Public WriteOnly Property Surname As String
	Set(value As String)
		mSurname = value
	End Set
End Property
string mSurname;
public string Surname
{
	set
	{
		mSurname = value;
	}
}

Function declarations

VB.NET C#
Private Sub SetForename(ByVal forename As String)

End Sub
private void SetForename(string forename) {

}
Private Function GetForename() As String
	Return "Jim"
End Function
private string GetForename()
{
	return "Jim";
}
Public Sub OutAndByRef(ByRef outParam As String,
			ByRef refParam As String)
        refParam = "In and out"
        outParam = "In and out (no difference!)"
End Sub
public void OutAndByRef(out string outParam,
			ref string refParam)
{
	outParam = "Out only";
	refParam = "In and out";
}
Public Sub SubWithOptional(
	Optional ByVal optParam As String = "Default")

End Sub
public void FunctionWithOptional(
	string optParam = "Default")
{

}
Public Shared Function DoIt() As String
	Return "Shared!"
End Function
public static string DoIt()
{
	return "static!";
}

Common Types and Operators

VB.NET C#
Dim obj As New Object()
object obj = new object();
Dim obj As Object = Nothing
object obj = null;
Dim i As Integer = 1
int i = 1;
Dim s As String = ""
string s = "";
Dim f As Single = 3.142F
float f = 3.142F;
Dim d As Double = 3.142
double d = 3.142;
Dim hex As Integer = &HA
int hex = 0xA;
Dim equal As Boolean = 1 = 1
bool equal = 1 == 1;
Dim notEqual As Boolean = 0 <> 1
bool notEqual = 1 != 1;
Dim truth As Boolean = True Or False
bool truth = true | false;
Dim fallacy As Boolean = True And False
bool fallacy = true & false;
Dim conditionalAnd As Boolean = True AndAlso False
bool conditionalAnd = true && false;
Dim conditionalElse As Boolean = True OrElse False
bool conditionalElse = true || false;
Dim modZero As Integer = 10 Mod 2
int modZero = 10 % 2;
i += 1
i++;
No prefix increment
++i;

Arrays, Strings and Characters

VB.NET C#
Dim emptyArray As Integer() = {}
int[] emptyArray = {};
Dim intArray As Integer() = {0, 1, 2, 3, 4}
int[] intArray = {0, 1, 2, 3, 4};
Dim twoDArray As Integer()() =
	{New Integer() {0, 1}, New Integer() {2, 3}}
int[][] twoDArray =
	{ new int[] { 0, 1 }, new int[] { 2, 3 } };
Dim fixedSizeArray(10) As Integer
ReDim Preserve fixedSizeArray(20)
int[] fixedSizeArray = new int[10];
int[] biggerArray = new int[20];
Array.Copy(fixedSizeArray, biggerArray,
		fixedSizeArray.Length);
Dim charArray As Char() = "Hello!"
char[] charArray = {'H','e','l','l','o','!'};
Dim thirdChar As Char = nameString(3)
char thirdChar = nameString[3];
Dim empty As String = String.Empty
string empty = string.Empty;
Dim concat As String = "Hello " & "There!"
string concat = "Hello " + "There!";
Dim newLine As String = Environment.NewLine
string newLine = Environment.NewLine;
Dim escape As String =
	"How to ""escape"" a double quote!"
string escape =
	"How to \"escape\" a double quote!";

Control statements (if, switch)

VB.NET C#
If temperature > 20 Then
	Debug.WriteLine("Hot!")
ElseIf temperature < 10 Then
	Debug.WriteLine("Cold!")
Else
	Debug.WriteLine("Mild")
End If
if (temperature > 20)
{
	Debug.WriteLine("Hot!");
}
else if (temperature < 10)
{
	Debug.WriteLine("Cold!");
}
else { Debug.WriteLine("Mild"); }
Dim hot As Boolean =
	IIf(temperature > 20, True, False)
bool hot =
	temperature > 20 ? true : false;
Dim nullableTemp As Integer? = Nothing
Dim nonNullableTemp As Integer = 30
Dim concreteTemp As Integer =
	If(nullableTemp, nonNullableTemp)
int? nullableTemp = null;
int nonNullableTemp = 30;
int concreteTemp =
	nullableTemp ?? nonNullableTemp;
Select Case temperature
	Case 0
		Debug.WriteLine("Freezing!")
	Case Is > 20
		Debug.WriteLine("Hot!")
	Case Is < 10
		Debug.WriteLine("Cold!")
	Case Else
		Debug.WriteLine("Mild")
End Select
switch (temperature)
{
	case 0:
		Debug.WriteLine("Freezing!");
		break;
	default:
		if (temperature > 20) {
			Debug.WriteLine("Hot!"); }
		else if (temperature < 10) {
			Debug.WriteLine("Cold!"); }
		else {
			Debug.WriteLine("Mild"); }
		break;
}
Select Case crisps
	Case "plain", "cheese", "salt n vinegar"
		Debug.WriteLine("Normal")
	Case "hedgehog"
		Debug.WriteLine("Refined")
End Select
switch (crisps)
{
	case "plain":
		Debug.WriteLine("Normal");
		break;
	case "cheese":
		goto case "plain";
	case "salt n vinegar":
		goto case "plain";
	case "hedgehog":
		Debug.WriteLine("Refined");
		break;
}

Iterators (for, foreach, while)

VB.NET C#
Dim total As Integer = 10
For j As Integer = 0 To total
	Debug.WriteLine(j)
Next
int total = 10;
for (int j = 0; j <= total; j++)
{
	Debug.WriteLine(j);
}
Dim k As Integer = 0
While k < total
	Debug.WriteLine(k)
	k += 1
End While
int k = 0;
while (k < total)
{
	Debug.WriteLine(k);
	k++;
}
Dim sweets As String() =
	{"Mars bar", "Toffee Crisp", _
	"Pork pie", "Bounty"}

For Each sweet As String In sweets
	If sweet = "Bounty" Then
		Debug.WriteLine("The taste of paradise!")
		Exit For ' Leave the for loop
	ElseIf sweet = "Pork pie" Then
		Continue For ' Ignore!
	Else
		Debug.WriteLine(sweet)
	End If
Next
string[] sweets =
	{"Mars bar", "Toffee Crisp",
	"Pork pie", "Bounty"};

foreach (string sweet in sweets) {
	if (sweet == "Bounty") {
		Debug.WriteLine("The taste of paradise!");
		break;
	}
	else if (sweet == "Pork pie") {
		continue;
	}
	else {
		Debug.WriteLine(sweet);
	}
}

Error handling (try, catch, finally)

VB.NET C#
Try
	Throw New Exception("Custom error!")
Catch ex As Exception
	Debug.WriteLine(ex.Message)
Finally
	Debug.WriteLine("This line always hit")
End Try
try
{
	throw new Exception("Custom error!");
}
catch (Exception ex)
{
	Debug.WriteLine(ex.Message);
}
finally
{
	Debug.WriteLine("This line always hit");
}
Try
	Throw New Exception("Throw this up!")
Catch ex As Exception
	Throw
End Try
try
{
	throw new Exception("Throw this up!");
}
catch
{
	throw;
}
  • No Comments »

Consuming a Facebook Page RSS feed in .NET

Recently I was tasked with integrating a company’s Facebook Page feed into their website, providing a quick way for them to keep their customers up to date with their latest and greatest offerings. “Simple!” I thought, “All I have to do is take the ‘Get updates via RSS’ link and consume it how I so wish!”

Get updates via RSS screenshot

It was almost that simple.

Here is the RSS feed I was using as a test; depending on your browser you’ll either see the raw XML or a prettified version of the feed.

So far so good.

However, when I tried to consume the feed directly in code it could not be accessed. After a bit of digging around, I found that the RSS feed can only be consumed by legitimate readers such as Google Reader and not the likes of “Test Business Website”. All was not lost however, thanks to Feedburner.

Feedburner allows you to consume an RSS feed and then spit it back out, all wrapped up in a friendly URL and available to any reader without restriction. Since Feedburner is considered a legitimate reader by Facebook, we can effectively make the Facebook feed public!

The next step is to write a little bit of code to consume the feed and provide a nice wrapper for the data to easily slot into the HTML (for example, via a Repeater in WebForms or a View in MVC):

private List<FeedItem> GetFeed()
{
	XDocument rssFeed = XDocument.Load(
				"http://feeds.feedburner.com/PlaceholderBusinesssFacebookWall");

	int intLimit = 3;
	int intCount = 0;
	List<FeedItem> lstItems = new List<FeedItem>();

	foreach (XElement xItem in (from item in rssFeed.Descendants("item") select item))
	{
		lstItems.Add(new FeedItem {
			Title = xItem.Element("title").Value,
			Url = xItem.Element("link").Value,
			Description = (xItem.Element("description") != null) ?
						xItem.Element("description").Value : "",
			PostDate = DateTime.Parse(xItem.Element("pubDate").Value)
		});
		intCount += 1;

		if (intCount == intLimit) {
			break;
		}
	}

	return lstItems;

}

private class FeedItem
{
	public string Title { get; set; }
	public string Url { get; set; }
	public string Description { get; set; }
	public DateTime PostDate { get; set; }
}

No iframes, no Javascript required – plain and simple!

  • No Comments »

Welcome

Hello and welcome to my blog.

I’m a software developer who has worked in both Windows and web development for the past nine years or so and thought it was about time I shared some of my knowledge and experiences!

The scope of the blog will be broad but mostly I’ll be writing about web development, particularly in ASP.NET WebForms and MVC. From time to time I may drop in some Javascript, particularly the likes of backbone, spine and other MVC based frameworks. A lot of my development experience has been in building complex business applications for Windows so I’m particularly interested in how these would translate to the new world order of HTML5 and Javascript.

Above all, I hope this little corner of the internet will be fun to read.

Thanks for viewing.

Alistair

  • No Comments »