After using notepad++ for many years, I recently switched over to HippoEDIT as my preferred text editor. I find HippoEdit to be snappier than other text editor and the UI also looks appealing. Just wanted to give them a plug here.

Download HippoEDIT and see it for yourself.

HippoEDIT Overview

Tagged with:
 

ASP.NET 4 allows developers to customize Client Id which gets generated by ASP.NET. Up until now Client Id generated by ASP.NET has been ummm just plain ugly. Other than aesthetics they are also hard to work with in client side scripts. ASP.NET solves this issue to a degree by providing ClientIDMode property. In this post we will look at different ways to work with this new feature of ASP.NET 4.

ClientIDMode can be set at Page level or at Control level. Let’s follow with an example of a GridView control. We will set it’s ClientIdMode property to all available options and view the markup. We will bind our GridView to a collection of cities. A city class looks like this.

public class City
{
  public string Name { get; set; }
  public string Country { get; set; }
}

 

The collection itself can be initialized using this code.

List<City> cities =
        new List<City>
        {
            new City{ Name = "Sydney", Country = "Australia" },
            new City{ Name = "New York", Country = "USA" },
            new City{ Name = "Paris", Country = "France" },
            new City{ Name = "Milan", Country = "Spain" },
            new City{ Name = "Melbourne", Country = "Australia" },
            new City{ Name = "Auckland", Country = "New Zealand" },
            new City{ Name = "Tokyo", Country = "Japan" },
            new City{ Name = "New Delhi", Country = "India" },
            new City{ Name = "Hobart", Country = "Australia" }
        };

 

Source for our GridView looks like this.

<asp:GridView runat="server" ID="gridViewCities" AutoGenerateColumns="False">
  <Columns>
    <asp:TemplateField>
      <ItemTemplate>
        <asp:Label runat="server" ID="Label1" Text='<%# Bind("Name") %>' />
      </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField>
      <ItemTemplate>
        <asp:Label runat="server" ID="Label2" Text='<%# Bind("Country") %>' />
      </ItemTemplate>
    </asp:TemplateField>
  </Columns>
</asp:GridView>

 

ClientIDMode = “AutoID”

Using this mode will generate the IDs as it has in earlier versions of ASP.NET.

<asp:GridView
        runat="server"
        ID="gridViewCities"
        AutoGenerateColumns="False"
        ClientIDMode="AutoID">

 

HTML generated by AutoID (showing only relevant part).

image

 

ClientIDMode = “Static”

Static mode outputs the same ID in HTML as specified in ASP.NET source.

<asp:GridView
        runat="server"
        ID="gridViewCities"
        AutoGenerateColumns="False"
        ClientIDMode="Static">

image

Static Mode is not the best for controls such as GridView or any other data control which displays lists of data. As you can see above that all span tags have same IDs. Static Mode is best to be used with other common controls or User Controls.

 

ClientIDMode = “Predictable”

Predictable mode concatenates the ID of parent control with the bound value supplied by assigning ClientIDRowSuffix property.

<asp:GridView
        runat="server"
        ID="gridViewCities"
        AutoGenerateColumns="False"
        ClientIDMode="Predictable"
        ClientIDRowSuffix="Name">

 

image

Here we see that our span elements have been named by concatenating the name of GridView + value of Name property. Rather than setting ClientIDRowSuffix to Name property a better candidate would have been an ID property which could be some sort of unique field. But you get the idea, right?

 

ClientIDMode = “Inherit”

Inherit is the default mode for all controls. Assigning this mode a control will use the same setting as its parent control. This gives us an idea that we can have different settings for parent and children. Here we are setting ClientIDMode for our first label to be static while the GridView is using AutoID.

<asp:GridView runat="server" ID="gridViewCities" AutoGenerateColumns="False" 
  ClientIDMode="AutoID">
  <Columns>
    <asp:TemplateField>
      <ItemTemplate>
        <asp:Label runat="server" ID="Label1" Text='<%# Bind("Name") %>' 
          ClientIDMode="Static" />
      </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField>
      <ItemTemplate>
        <asp:Label runat="server" ID="Label2" Text='<%# Bind("Country") %>' />
      </ItemTemplate>
    </asp:TemplateField>
  </Columns>
</asp:GridView>

image

We see that our first span uses static client ID but the second span uses inherited scheme for client ID.

 

Conclusion

In this post we saw a new feature of ASP.NET 4 which let’s you customize IDs generated in HTML elements. This feature is useful when we need to access controls from client scripts. ASP.NET has been lacking such a feature. Not any more.

Tagged with:
 

Channel 9 which happens to be my favourite media station now has a section for courses. And if you have downloaded Visual Studio 2010 then this is the place to get yourself some VS 2010 training. Topics covered in this online course are:

  1. Managed Languages
  2. ASP.NET 4.0
  3. Data Platform
  4. WCF & WF
  5. Parallel Computing
  6. ALM

Link to Visual Studio 2010 and .NET Framework Training Course.

Tagged with:
 

This post shows you how to use Breakpoints in Visual Studio with a hit count. Breakpoints can be described as bread and butter of debugging. They allow you to stop execution at any statement in your code. By doing this you can examine values in your variables, look at call stack, change values in variables and much more. 

Let’s follow this post with an example of a simple program which uses a loop to add a number to a List<int>.

static void Main(string[] args)
{
  List<int> numbers = new List<int>();
  for (int i = 0; i < 100; i++)
  {
    numbers.Add(i);
  }
}
 

We will now add a breakpoint to numbers.Add(i) line. A breakpoint can be added by clicking on gray area on the left side of code editor or by pressing F9.

Visual Studio Breakpoint

Here we have added a simple breakpoint. Our program will break when we hit the breakpoint for the first time. Let’s say that we want our breakpoint to hit at 50 iteration of our loop. To do this we can right click on the breakpoint circle on left hand side and click Hit Count.

Visual Studio Breakpoint 

When we click on Hit Count we get a dialog where we can set the conditions when our breakpoint should be hit.

Visual Studio Breakpoint

In our case we will select “break when the hit count is equal to” and enter 50.

Visual Studio Breakpoint

If we now run our program we will hit the breakpoint when value of i = 49. Remember that we started i at 0 so when i is equal to 49 we are on the 50th iteration.

This comes in handy when debugging large loops and we are only interested in breaking when we have processed X number of iterations.

Tagged with:
 

This is a very smart commercial for Windows 7. A clever way to praise a product without taking a dig on others. Maybe Apple will learn a thing or two from this. Enjoy.

Tagged with:
 

These days I am working on a personal project which I call “my precious”. This projects involves transforming XML documents into HTML using XSLT. Things were going smooth till I decided to output DOCTYPE from XSLT. This is what I did.

 XSLT 

XSLT parser does not like the code above and gives me this error.

XSLT

After scratching my head for a while and navigating through intellisense few times I found the right solution. The way to output DOCTYPE in XSLT is by placing in inside a CDATA. The following code works like a charm.

XSLT

This I thought was worth sharing.

Tagged with:
 

Keynote for TechEd Australia started a bit slow with too much concentration on words such as innovation, excitement and productivity. Keynote was saved by awesome presentations by Sara Ford and Sarah Vaughan. Rest of the day was fantastic. A combination of excellent topics and superb presentation skills made it a worthy learning day.

The best presentation of the day which I attended was by Damian Edwards on ASP.NET MVC. Well structured and full of useful information. ASP.NET MVC is my current focus and that made the presentation even more interesting for me . Well done Damian.

I also attended a talk on BizSpark by Rog42 and Christian Longstaff. Biz Spark is a great program for startups and if you are one then you should definitely look at it. Where else can you get a suite of world class software at $100 which is payable in third year. I’m thinking that I might consider it for my company.

I also enjoyed Sharepoint presentation by Andrew Coates and Jeremy Thake. Their presentation was well synchronised and full of Sharepoint goodness. I’m not too much into Sharepoint but even I picked up points which I could use if god forbid I have to do any Sharepoint work again.

Tagged with:
 

Some of you may know that author of this site (that’s me in case you are thinking) is attending his first ever TechEd. TechEd to me is like woodstock for developers and other IT people who come in masses for this amazing and full of geek energy event. Over next few posts I will write about my experience of TechEd.

Day 1

Technically today was not the first day of TechEd but it was for me. I arrived at Gold Coast after a pleasant 1 point something hour flight. Meeting familiar people at Gold Coast airport who were also headed to TechEd got me into TechEd groove right away. I checked into my hotel which is in front of Convention Centre and the best part is that I can get a panoramic view of Convention Centre from my window. Wasting no time I went straight to Convention Centre for registration and picked up my Netbook, picked up my delegate bag (to be reviewed soon) and headed to exhibition hall where I caught up with Rob Farley and finally met Deeps. For those who have confused me with Deeps I can now logically prove that we are two different people. Exhibition hall was buzzing with activity and you could feel geek vibes all over the place.

I took some pictures which you can view down below. But before you do that I have a WTF to report on. Drums please. WTF for today was found inside delegate bag within HP folder. There is a pamphlet which says HP recommends Vista Business.

Registration booths at TechEd Australia.

IMG_0167

Me holding my HP Netbook. Still in the box.

IMG_0170

My friend Rob Farley holding my Netbook.

IMG_0168

Netbook right out of the box. Not booted yet.

IMG_0172

More tomorrow…

Tagged with:
 

This post shows you how to output data to a Console in a Windows Forms Application. I use this technique religiously when developing Windows Forms applications. Debugging is much simpler when you can see information on what your application is doing in a Console. Of course the onus is on you as developer to output data which will help you.

In this post I will use a simple Windows Forms application which adds two numbers.

Windows Forms

By default a Windows Forms application does not output to a Console even if you write a Console.Write() or Console.WriteLine(). This shortcoming can be addressed by using Win32 API. In your Windows Forms application you can declare a class which provides a wrapper around Win32 functions.

public class Win32
{
  /// <summary>
  /// Allocates a new console for current process.
  /// </summary>
  [DllImport("kernel32.dll")]
  public static extern Boolean AllocConsole();

  /// <summary>
  /// Frees the console.
  /// </summary>
  [DllImport("kernel32.dll")]
  public static extern Boolean FreeConsole();
}

A Console must be started to accept input and display our messages. This can be done by calling Win32.AllocConsole() function. For my example I will start the console in my form’s constructor.

public Form1()
{
  InitializeComponent();

  Win32.AllocConsole();
}

Now when I write to Console, I will see data appear in the console window which was started in my constructor.

private void Add(int num1, int num2)
{
  int result = num1 + num2;

  Console.WriteLine(
    string.Format("{0} + {1} = {2}", num1, num2, result));
}

Console

As a good practice you should also close the console window by calling Win32.FreeConsole() method before your application exits.

Tagged with:
 

In this post we will look at Logical Operators in ADO.NET Data Services. These operators can be used as filter expressions in our requests and ADO.NET Data Services applies the filter before results are returned. We will use Data Services generated over Adventureworks Lite database. If you are new to ADO.NET Data Services and would like to know how to generate ADO.NET Data Service then please see this article.

One thing to keep in mind is that filter expressions are case sensitive. And the syntax of applying filters in ADO.NET Data Services is

<url>?$filter=<your filter>

Let’s now look at all logical operators

Equal To

Parameter: eq

Equal To evaluates true when both operands have the same value. Here I am retrieving products where the value of Color matches “Yellow”.

http://localhost:6803/DataService.svc/Product?$filter=Color eq ‘Yellow’

Logical operator can also be applied in code through a LINQ query.

AdventureWorksEntities context = new AdventureWorksEntities(uri);
DataServiceQuery<Product> products = context.CreateQuery<Product>(@"/Product");

var query = from p in products
  where p.Color == "Yellow"
  select p;

foreach (var item in query)
{
  Console.WriteLine(item.ProductID + "\t" + item.Color);
}

 

Not Equal To

Parameter: ne

Not equal is opposite of equal to and evaluates true when both operands do not have the same value. Here I am retrieving products where the value of Color is NOT “Yellow”.

http://localhost:6803/DataService.svc/Product?$filter=Color ne ‘Yellow’

Following code will also achieve the same result through a LINQ query.

AdventureWorksEntities context = new AdventureWorksEntities(uri);
DataServiceQuery<Product> products = context.CreateQuery<Product>(@"/Product");

var query = from p in products
  where p.Color != "Yellow"
  select p;

foreach (var item in query)
{
  Console.WriteLine(item.ProductID + "\t" + item.Color);
}

 

Less than

Parameter: lt

Less than evaluates true when first operand is less than second. In this example I get all products where ListPrice is less than 20.

http://localhost:6803/DataService.svc/Product?$filter=ListPrice lt 20

Here is the C# version of Less than operator.

AdventureWorksEntities context = new AdventureWorksEntities(uri);
DataServiceQuery<Product> products = context.CreateQuery<Product>(@"/Product");

var query = from p in products
  where p.ListPrice < 20
  select p;

foreach (var item in query)
{
  Console.WriteLine(item.ProductID + "\t" + item.ListPrice);
}

Less than or equal to

Parameter: le

Less than or equal to evaluates true when first operand is either less than or equal to second operand. In this example I am retrieving all products where ListPrice is less than or equal to 9.5

http://localhost:6803/DataService.svc/Product?$filter=ListPrice le 9.5

And C# equivalent will look like this.

AdventureWorksEntities context = new AdventureWorksEntities(uri);
DataServiceQuery<Product> products = context.CreateQuery<Product>(@"/Product");

var query = from p in products
  where p.ListPrice <= 9.5m
  select p;

foreach (var item in query)
{
  Console.WriteLine(item.ProductID + "\t" + item.ListPrice);
}

Greater than

Parameter: gt

Greater than evaluates true if the first operand is greater than the second. In this example I am retrieving all products where ListPrice is greater than 9.5

http://localhost:6803/DataService.svc/Product?$filter=ListPrice gt 9.5

Greater than is a no brainer with a LINQ query.

AdventureWorksEntities context = new AdventureWorksEntities(uri);
DataServiceQuery<Product> products = context.CreateQuery<Product>(@"/Product");

var query = from p in products
  here p.ListPrice > 9.5m
  select p;

foreach (var item in query)
{
  Console.WriteLine(item.ProductID + "\t" + item.ListPrice);
}

Greater than or equal to

Parameter: ge

Greater than or equal to evaluates true if the first operand is greater than or equal to second. Here is  an example. I am retrieving all products where ListPrice is greater than or equal to 9.5

http://localhost:6803/DataService.svc/Product?$filter=ListPrice ge 9.5

C# example

AdventureWorksEntities context = new AdventureWorksEntities(uri);
DataServiceQuery<Product> products = context.CreateQuery<Product>(@"/Product");

var query = from p in products
  where p.ListPrice >= 9.5m
  select p;

foreach (var item in query)
{
  Console.WriteLine(item.ProductID + "\t" + item.ListPrice);
}

 

And

Parameter: and

“And” evaluates true when both operands are true. In this example I am retrieving all products where the Color is Black and ListPrice is greater than 1000.

http://localhost:6803/DataService.svc/Product?$filter=(Color eq ‘Black’) and (ListPrice gt 1000)

Same results can be retrieved in C# with this code.

AdventureWorksEntities context = new AdventureWorksEntities(uri);
DataServiceQuery<Product> products = context.CreateQuery<Product>(@"/Product");

var query = from p in products
  where (p.Color == "Black")
    && (p.ListPrice > 1000)
  select p;

foreach (var item in query)
{
  Console.WriteLine(item.Color + "\t" + item.ListPrice);
}

 

Or

Parameter: or

“Or” evaluates true when either operand is true. In this example I am retrieving all products where either the Color is Black or ListPrice is greater than 1000.

http://localhost:6803/DataService.svc/Product?$filter=(Color eq ‘Black’) or (ListPrice gt 1000)

Now with C#.

AdventureWorksEntities context = new AdventureWorksEntities(uri);
DataServiceQuery<Product> products = context.CreateQuery<Product>(@"/Product");

var query = from p in products
  where (p.Color == "Black")
    || (p.ListPrice > 1000)
  select p;

foreach (var item in query)
{
  Console.WriteLine(item.Color + "\t" + item.ListPrice);
}

 

Not

Parameter: not

“Not” evaluates true if operand is false. An example can be retrieving all products where the Color is not Black.

http://localhost:6803/DataService.svc/Product?$filter=not (Color eq ‘Black’)

While this can be achieved using not equal to operator they are not the same. I’ll leave C# code for this one for you :)

 

Conclusion

This article demonstrated all logical operators available for ADO.NET Data Services. In a future post I will cover other types of operators for ADO.NET Data Services.

Tagged with:
 

Introduction

In an earlier article I looked at how DO.NET Data Services can be used with ASP.NET. In this post I will talk about using ADO.NET Data Services to retrieve data via SQL Server stored procedure. Doing this is simple and I will follow a similar approach to hook everything up as I did in my earlier post.

I have created a stored procedure which retrieves data from Employees table in Northwind database based on city name. Here is the script I used to create the procedure.

CREATE PROCEDURE [dbo].[GetEmployeesByCity] 

    @City NVARCHAR(15)
AS

BEGIN

    SELECT *
    FROM Employees
    WHERE City = @City

END

Creating Data Model

ADO.NET Data Services sits between the client and a data source, so the first thing I’ll need is a data source. I will use Entity Framework to create my data source.

image

To make things simple I will select Employees table only for my Entity Data Model.

image

Mapping Stored Procedure in EDM

My objective here is to retrieve data from a stored procedure. To this I need to expose the procedure through my data layer which I have created using Entity Framework. Mapping a stored procedure in Entity Framework can be done by following these steps.

Open Model Browser (View –> Other Windows –> Model Browser). Right click on Stored Prodecures under NorthwindModel.Store and click Update Model from Database.

image

Select the stored procedure (GetEmployeesByCity in this case) and click Finish.

image

Go back to Model Browser and under stored procedure right click the stored procedure and click Create Function Import.

image

Select Employees entity as the return type and click OK.

image

Entity Model is now setup to execute the stored procedure and return results. It can be called like this.

NorthwindEntities entities = new NorthwindEntities();
var employees = entities.GetEmployeesByCity("London");

My goal however is to retrieve data via ADO.NET Data Services so I’ll start creating my service.

And Now With a Service

Because I’d like to access this data through my ADO.NET Data Service so the first thing I’ll do is create a service called NorthwindEmployeeService. I will add a new item to my project of type ADO.NET Data Service.

image

Visual Studio creates a blank service with some scaffolding for me to get started. First thing I need to do is let my service know about my data source class and then configure appropriate rights to my entities and operations. To be simple I will just allow everything. Below is the code for my service after making changes.

public class NorthwindEmployeeService : DataService<NorthwindEntities>
{
  // This method is called only once to initialize service-wide policies.
  public static void InitializeService(IDataServiceConfiguration config)
  {
    config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
    config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);
  }
}

By default my service does not know that it should also work with a stored procedure. To do this i can write a method which will execute the procedure and return results. Such a method can look like this.

[WebGet]
public ObjectResult<Employees> GetEmployeesByCity(string cityName)
{
  NorthwindEntities entities = new NorthwindEntities();
  return entities.GetEmployeesByCity(cityName);
}

Method above tells the service to expose a GetEmployeesByCity method which can be called by clients. Note that the method is decorated with a WebGet attribute which indicates that this is a GET method which can be called by a web client.

Running Service and Calling Stored Procedure

To see my service in action I can hit F5

image

To see the results from the stored procedure I can use the following URL.

http://localhost:16147/NorthwindEmployeeService.svc/GetEmployeesByCity?cityName=’London’

Here I am passing in the parameter as a query string which is accepted by my service and appropriate results are returned.

image

Conclusion

In this article I used ADO.NET Data Services to execute a stored procedure and return results. I am not in favour of implementing a direct mapping between services and database and the design can be a little better whereby data layer can be sensibly abstracted away by service. However the idea was to demonstrate a concept. I hope you enjoyed reading this article.

Tagged with:
 

Riviera is a sample application for Windows Azure available on MSDN Code Gallery for download. Riviera has been developed by Platform Evangelism group in collaboration with Cumulx who are a Cloud ISV partner. Key features of Riviera are:

  • Multi-tenant data store based on Azure Table Storage as well as SQL Azure.
  • Per tenant customization of data model
  • Per tenant customization of business logic (using Windows Workflow in Windows Azure)
  • Per tenant customization of user interface using Silverlight 3.0. Customization can be multi-level – custom theme, custom XAML, and custom XAP.
  • Automated tenant provisioning
  • Windows Azure web role->Azure Queue->worker role pattern for high volume transaction processing that can scale on demand
  • Claims aware web service and web application using Geneva Framework
  • Active and Passive Federation using Geneva Framework, Geneva Server and .NET Access Control Service (ACS)
  • Windows Live ID authentication for consumer facing web site
  • Use of Patterns & Practices Enterprise Library Caching and Logging application blocks in Windows Azure

 

As you can see from the list above that Riviera uses many features of Azure. This makes it an excellent sample to learn from. Assuming that Windows Azure is not too far from RTM, developers should start sharpening their Cloud Computing skills.

Link To Riviera home page.

Tagged with: