Showing a sorted list of the entities

When you want to show a list of entities, then you'd need the MetadataService. The code is not that hard to fetch a list of these entities. There's even an example in the SDK. The code to get all entities including custom entities would be:


MetadataService.MetadataService service = new MetadataService.MetadataService();
service.Credentials = System.Net.CredentialCache.DefaultCredentials;
Metadata md = service.RetrieveMetadata(MetadataFlags.EntitiesOnly);
ArrayList alEntities = new ArrayList();

foreach (EntityMetadata em in md.Entities)
{
if (em != null)
alEntities.Add(em);
}


But if you do have this list, then how do you show this in a sorted way? Usually you could just say alEntities.Sort()... Too bad that doesnt work here because the collection exists out of a list of EntityMetadata instances. So how do we do this? Well, just create a EntityMetadataComparer based on the IComparer interface. Here's the code that you'll need:


using System;
using System.Collections;
using MetadataService;

/// <summary>
/// The class EntityMetadataComparer allows a collection of instances of the class EntityMetaData to be compared.
/// Use this Comparer class to sort for instance an ArrayList
///
/// Author: Ronald Lemmen
/// Company: Avanade
/// Date: 19 Jan 2007
/// </summary>

public class EntityMetadataComparer : IComparer
{
public enum SortOrder {
Ascending = 1,
Descending = -1
}

private int _modifier;

/// <summary>
/// EntityMetadataComparer constructor without sorting option. The default sorting option will be used: Ascending
/// </summary>
public EntityMetadataComparer()
{
_modifier = (int)SortOrder.Ascending;
}

/// <summary>
/// EntityMetadataComparer constructor with sorting option.
/// </summary>
/// <param name="order">Sort Order. Set this by using EntityMetadataComparer.SortOrder.[Ascending|Descending]</param>
public EntityMetadataComparer(SortOrder order)
{
_modifier = (int)order;
}

/// <summary>
/// Compare the two EntityMetadata objects based on their DisplayName
/// </summary>
/// <param name="o1">Object 1</param>
/// <param name="o2">Object 2</param>
/// <returns>The int return value of the string.CompareTo function</returns>

public int Compare(Object o1, Object o2)
{
EntityMetadata em1 = (EntityMetadata)o1;
EntityMetadata em2 = (EntityMetadata)o2;

if (em1.DisplayName == null)
em1.DisplayName = "";

if (em2.DisplayName == null)
em2.DisplayName = "";

return em1.DisplayName.CompareTo(em2.DisplayName) * _modifier;
}
}


Now you can sort your ArrayList with the command:

alEntities.Sort(new EntityMetadataComparer());


Or to sort with a sort option set:
alEntities.Sort(new EntityMetadataComparer(EntityMetadataComparer.SortOrder.Descending));


Good luck!

1 comment:

Divya said...

hi,
how to get the display name of attributes of an entity in.net using sdk.i want to get those attributes display names in a dropdown list using metadata web service in .net
Thankx
Divya