Archive

Posts Tagged ‘Extension Methods’

LINQ to Tridion

January 8, 2010 4 comments

Contents

Introduction

Its Friday evening, a good time to share a little something I’ve been working on.

.NET 3.0 brought with it a fantastic new language (VB, C#) extension called LINQ which stands for Language-Integrated Query.

Microsoft describes it as “a set of extensions to the .NET Framework that encompass language-integrated query, set, and transform operations. It extends C# and Visual Basic with native language syntax for queries and provides class libraries to take advantage of these capabilities.”

In short it gives the developer a more general syntax for querying sets or collections of data.

The beautiful thing about LINQ is that it can be used over any collection whether its XML, Database or even objects so long as they support the IEnumerable<T> interface.

For more information see the resources section of this article or simply google/bing it.

Read more…

A Few Useful Tridion Extension Methods

October 26, 2009 8 comments

Following my recent blog about extension methods. Here are a few useful extension methods I’ve created recently for working with Tridion’s TOM API.

.NET Interops – COM API (5.2 and onwards)

Here are a few useful methods to use with the older TOM API (interops), these can come in handy when writing custom tools, event system code, etc.

Publish

The publish method for both Page and Component objects require quite a few parameters which in many cases are always set the same within a single application scope. If you want to use defaults for these values you can use these extension methods to predetermine the values of the parameters leaving a shorter and more convenient way for sending the items to be published:

For Components:

1
2
3
4
5
6
7
8
/// <summary>
/// Offers a simple call to publish a components using defaults
/// for all of the publish parameters  
/// </summary>
/// <param name="targets">one or more pucliation targets or target
/// types to publish to
/// </param>
public static void Publish(this Component component, object targets, 
                                          EnumPublishPriority priority)
{
     component.Publish(targets, false, false, false, DateTime.Now, 
            DateTime.MinValue, DateTime.Now, true, priority, true, 100);
}

For Pages:

1
2
3
4
5
6
7
8
/// <summary>
/// Offers a simple call to publish a components using defaults
/// for all of the publish parameters
/// </summary>
/// <param name="targets">one or more pucliation targets or
/// target types to publish to
/// </param>
public static void Publish(this Page page, object targets,
                                   EnumPublishPriority priority)
{
page.Publish(targets, false, false, false, DateTime.Now,
        DateTime.MinValue, DateTime.Now, true, priority, true, 100);
}

UnPublish

Very similarly to the publish method, here’s an example for creating a shorter way to call un-publish on a page object:

1
2
3
4
public static void UnPublish(this Page page, object targets,
                                     EnumPublishPriority priority)
{
     page.UnPublish(targets, true, false, false, DateTime.Now, 
                                                 false, priority);
}

IsPublished

Tridion provides a method to check whether a page is published to a specific Target Type or Publication Target but what if you just want to check whether the page is published or not?
You need to check each target.
Here’s a way to add a method to the page type that will check whether a page is published by providing a list of targets to the method call:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/// <summary>
/// Assert whether a page is published or not
/// </summary>
/// <param name="page">The page in question</param>
/// <param name="targets">A list of target types or
/// publication targets to check
/// </param>
/// <returns>True if the page is published to at least
/// one of the provided targets</returns>
public static bool IsPublished(this Page page, IEnumerable<string> targets)
{
    foreach (var t in targets)
    {
        if (page.IsPublishedTo(t)) return true;
    }

    return false;
}

Release

Its very important to make sure you correctly dispose of the Tridion COM objects exposed by the interops.

Here’s an example of how to easily do that for components and pages without having to add: “using System.Runtime.InteropServices;” to every code file:

For Component:

1
2
3
4
5
6
7
/// <summary>
/// Releases the COM Component object
/// </summary>
public static void Release(this Component component)
{
    Marshal.ReleaseComObject(component);
}

For Page:

1
2
3
4
5
6
7
/// <summary>
/// Releases the COM Page object
/// </summary>
public static void Release(this Page page)
{
    Marshal.ReleaseComObject(page);
}

TOM.NET (5.3 and onwards)

Fields

One of the things I was quite astonished to find when i first started working with the TOM.NET API was that the Component object no longer exposed a fields collection as a property. Instead to get an instance of those fields you are required to write code which is not very intuitive and definitely shouldnt be required for such a basic property.
I’ve since filed a formal request to our R&D department to change this but there’s no guarantee that this is going to change anytime soon.

If you are using Tridion 2009 and .NET 3.5 or brave enough to write your .NET templates on 5.3 or 5.3 SP1 with .NET 3.5 you might be interested in using the following extension method:

1
2
3
4
5
6
7
/// <summary>
///  Returns an ItemFields collection for the Component
/// </summary>
public static ItemFields Fields(this Component component)
{
     return new ItemFields(component.Content, component.Schema);
}

With this method in place to get the fields collection of a component you only need the following: comp.Fields()…

Root StructureGroup

Another oddity in the relatively new API is that the publication object doesnt expose a RootStructureGroup property while it does expose a RootFolder property. Slightly annoying but easily fixed with… you guessed it! An extension method:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/// <summary>
/// Returns the root structure group for this publication
/// </summary>
public static StructureGroup RootSG(this Repository publication)
{
    Filter filter = new Filter();
    filter.Conditions["ItemType"] = ItemType.StructureGroup;
    IList<RepositoryLocalObject> items = publication.GetItems(filter);

    if (items.Count == 0)
       return null;
    else
       return (StructureGroup)items[0];
}

Conclusion

These are just a few useful methods that can make your Tridion development quicker and more convenient.
Undoubtedly there’s many more such methods people can think of, if you do have some that you use please share them and if we have enough I will create an extension on World with all of them!

Code

You can download the methods ive shown in this article here: code.

for all of the

A few useful String extension methods

October 26, 2009 1 comment

There are a couple of actions I find myself doing over and over again when it comes to strings and frankly, its becoming rather annoying writing the same lines of code over and over again for every application I create.

So, I have created a few of useful (at least for me) Extension Methods that encapsulate the reoccurring logic.

If you are not familiar with extension methods, its a great way introduced in .NET 3.5 to add functionality to an already existing type.
You typically use these methods to attach functionality to types you dont have access to their source code, those could be types in the .NET’s BCL, in a 3rd party library or even your own code you dont think this addition merits a change to the source.

So here are mine:

IsEmpty

This is a simple one born from pure laziness :) . While i was working on an application recently I got tired writing

if (String.IsNullOrEmpty(str))…

for the hundredth time so I created an Extension method for the String type that does just that, now i can write it in shorter way:

If (str.IsEmpty())…


/// <summary>
/// Executes the String.IsNullOrEmpty on the current string
/// </summary>
/// <returns>True if either empty or null</returns>
public static bool IsEmpty(this String str)
{
return String.IsNullOrEmpty(str);
}

CsvToList

Working with configuration files quite allot I noticed that many times im passing a collection of (usually) comma separated values in a single string and then to parse this list im using the String.Split method.
What you usually need to do with the split method is provide a separator character or an array of these separators and optionally use the StringSplitOptions enumeration.

Doing this once is fine but what if you need to do this more than that? here’s my solution:

/// <summary>
/// Parses the String into a list of values separated by a comma (',')
/// </summary>
public static IEnumerable<string> CsvToList(this String str)
{
return CsvToList(str, ',');
}

/// <summary>
/// Parses the String into a list of values separated by the provided delimiter character
/// </summary>
/// <param name="delimiter">A character used in the String to separate between the values</param>
public static IEnumerable<string> CsvToList(this String str, char delimiter)
{
var delString = delimiter.ToString();

var delimiters = new[] { String.Format(" {0} ", delimiter), String.Format("{0} ", delimiter), delString };

return str.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
}

Take

Probably could have found a better name for it. This method lets you specify the start and end index of the sub-string to extract from the original string.
When manipulating strings and extracting sub-strings from other strings this method could come quite handy.

/// <summary>
/// Extension method allowing to state the start and end positions of the sub string to get from another string
/// </summary>
/// <param name="start">The start index of the sub-string</param>
/// <param name="end">The end index of the sub-string</param>
public static string Take(this String str, int start, int end)
{
return str.Substring(start, (end - start));
}

Conclusion

None of these methods I presented in this article are revolutionary by any means, their purpose is to make life a bit easier, especially when like with these examples you find yourself writing the same couple lines of code over and over again.
If at first it seems unnecessary, I promise that after making use of such extension methods youll find them both time saving and convenient to use.

So what extension methods are you using?

Source Code

You can download these methods here: code. I even included a method that creates a CSV String from an IEnumerable<string> :)

Follow

Get every new post delivered to your Inbox.

Join 302 other followers

%d bloggers like this: