Poem: Memories from the Green Mill October 27, 2009
Posted by yoavniran in Poetry.Tags: Chicago, hebrew, Jazz, loss, love, music, poem, Poetry
add a comment
This one i wrote in June of 2005. Strangely enough, I haven’t marked down the exact date of its writing even though I’ve started doing that long before.
I was reminded of this poem just the other day from speaking to a friend about being in Chicago and visiting its Jazz clubs.
I have to say that I have very fond memories of Chicago, it was a wonderful time and I found a really great city to experience and enjoy as well as meeting very interesting people while being there.
So here it is:
The standard disclaimers apply, the poem was originally written in Hebrew therefore the translation may lose or change some of the meanings, rhyming, wordplay, etc.
~ Memories from the Green Mill ~
“We are all born crazy,
Its just that some of us stay that way”.
Says the writing on the mens bathroom wall.
I return to my seat
The band is still playing the same song
A happy tune that reminds me of you
Everything reminds me of you.
I’ve already lost control of my mind
My thoughts control me without mercy
The memories hold me like a stringed puppet
I try to fight them
But I never had a chance.
I am drawn to pictures of the past
The melody is left behind
Its you that I see over and over again
I see the reflection of myself
Staring at me from the memory of your eyes.
A feeling of pain brings me back
The candle’s wax drips on my hand
But I do not stop it, I use it,
If only for a moment it distracts me
I savor the realness of the pain.
The guitar plays on my heart’s strings
The bass shakes a tear from my eye
It falls into my empty glass
My voice shakes as I call for another drink.
The players are already playing a new song
And I am left only to surrender
So I lean back in my seat,
I let the pure music run through my body,
The alcohol numb my senses
As the memories sweep the whole of me.
The original Hebrew version:
~ זיכרונות מהטחנה הירוקה ~
“כולנו נולדנו משוגעים,
רק חלקנו נשארנו כך”.
אומרת ההודעה שעל קיר שרותי הגברים.
אני חוזר למקומי
הלהקה עדיין מנגנת את אותו השיר
שיר שמח שמזכיר לי אותך
הכול מזכיר לי אותך.
איבדתי כבר שליטה על מוחי
המחשבות שולטות בי בלי רחמים
הזיכרונות מחזיקים בי כבובה על חוטים
אני מנסה להלחם בהם
אך לא היה לי סיכוי מעולם.
אני נשאב אל תמונות העבר
המנגינה נשארת ברקע
רואה אותך שוב ושוב
מסתכל על השתקפות עצמי
שמביטה בי מתוך זיכרון עיניך.
כאב מחזירני אל ההווה
שעוות הנר מטפטפת על ידי
אך אינני מפסיקה, משמשת אותי,
אם רק לרגע מסיחה היא דעתי
מתענג לזמן קצר על הכאב המוחשי.
הגיטרה פורטת על תווי נשמתי
הבאס מרעיד את הדמעה מעיני
נופלת היא לתוך כוסי הריקה,
קולי רועד כשאני קורא לעוד משקה.
הנגנים כבר עוברים לשיר הבא
ולי לא נותר אלא להיכנע
אז אני נשען אחורה בכיסאי,
נותן למוזיקה הטהורה לעבור דרכי,
לאלכוהול להקהות חושיי
ולזיכרונות שוב לסחוף את כול כולי.
A Few Useful Tridion Extension Methods October 26, 2009
Posted by yoavniran in Programming, Tridion.Tags: .NET, Event System, Extension Methods, interops, modular templating, templates, Tridion, tutorial
4 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:
/// <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:
/// <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:
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:
/// <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:
/// <summary>
/// Releases the COM Component object
/// </summary>
public static void Release(this Component component)
{
Marshal.ReleaseComObject(component);
}
For Page:
/// <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:
/// <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:
/// <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.
A few useful String extension methods October 26, 2009
Posted by yoavniran in Programming.Tags: .NET, BCL, configuration, Extension Methods, Strings
1 comment so far
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>
Poem: The Horizon August 25, 2009
Posted by yoavniran in Poetry.Tags: dream, hebrew, life, memory, poem, Poetry
2 comments
This one i wrote on July 2nd, 2009.
The standard disclaimers apply, the poem was originally written in Hebrew therefore the translation may lose or change some of the meanings, rhyming, wordplay, etc.
~ The Horizon ~
I found myself sitting before the horizon
Looking at that distant line
The border between a memory and a touch
A divider between my past and the dream.
I found myself for one moment content
for an instant gazing at it aloof
It – that cuts the imagination to broken shards of glass
The ever threatening wave that is reluctant to come.
As I sat there, I found a tree nearby
Old it was, barren limbs, leafs no longer growing
like me its gaze is full of wonder
but the tree is staying here and I’m already disappearing.
I found myself thinking about that disconcerting horizon
Does more life exist beyond its colors?
Is it covering an internal light, or rather,
Is it holding back the darkness from blanketing my world?
Does the horizon also have searching eyes?
Does it see my already fading footsteps?
For a moment it pleased me to sit here
but I’m rising to go, I’m already disappearing.
The original Hebrew version:
~ האופק ~
מצאתי עצמי יושב מול האופק
מביט אל אותו קו מרוחק
הגבול בין זכרון ובין נגיעה
חוצץ שעובר בין עברי והחלום.
מצאתי עצמי לרגע מרוצה
לרגע באדישות לעברו בוהה
הוא שחותך דמיון לזכוכית שבורה
הגל המאיים אך שלא מגיע.
בעודי יושב שם מצאתי לידי עץ
עץ זקן, ענפיו ריקים ועליו לא צומחים
כמוני הוא מסתכל לעבר האופק ומשתהה
אך הוא נשאר כאן ואני כבר נעלם.
מצאתי עצמי חושב על אותו אופק מתעתע
האם מעבר לצבעיו יישנם עוד חיים?
האם הוא מסתיר אור נצחי, או שמא,
מחזיק מבעד החושך לכסות עולמי?
האם גם לאופק עיניים מחפשות?
האם רואה את עקבותיי שכבר מטשטשות?
לרגע קט הישיבה נעמה לי
אך אני קם והולך, אני כבר נעלם.
Favorite Poems of the Day Up to Date: 21/08/2009 August 21, 2009
Posted by yoavniran in Poetry.Tags: life, loss, love, poem, Poetry, poets, twitter
1 comment so far
As some of you know I’ve taken upon myself to try and publish a link to a poem i like per day on Twitter: #PoemOfTheDay.
Admittedly, I havent been able to keep it up everyday since I started but I did manage to share quite a few over the past few months.
I’d like to take the opportunity to collect some of my personal recent favorites in this post.
Enjoy!
August 19th 2009 – “Metallic Wing” by Efrat Mishori: http://tinyurl.com/mdlv57 – “Metallic wing in its socket, beating unseen.”
August 18th 2009 – “Pleasure for Pleasure” by Peter Stavropoulos: http://bit.ly/3Y7S4O – “…Pleasure for pleasure will surely start”
August 13th 2009 – “Night Heron” by Samuel Peralta: http://bit.ly/rtZ1m – “rising from the waters / like a dream.”
August 11th 2009 – “Sonnet 56” by William Shakespeare: http://bit.ly/hPEcw – “Sweet love, renew thy force! Be it not said…”
August 10th 2009 – “from: Prayers of Atonement” by Lea Goldberg http://bit.ly/klx4t -”If there were torments–then they voyaged toward you”
August 3rd 2009 – “Endless Poem” by Yehuda Amichai: http://bit.ly/jGQ7o – “Within me / My heart / Within my heart / A museum”
July 30th 2009 – “Listening” by Amy Lowell: http://bit.ly/1K8pK – “‘T is you that are the music, not your song…”
July 27th 2009 – “The Garden” by Mark Strand: http://bit.ly/rSKuf – “it shines: even now in the moment before it disappears.”
July 26th 2009 – “Song of Hope” by Thomas Hardy: http://bit.ly/n4rlU – “To-morrow shines soon -Shines soon!”
July 21st 2009 – “On Pain” by Khalil Gibran: http://bit.ly/vmHgr – “…your pain would not seem less wondrous than your joy…”
July 17th 2009 - “Petals” by Amy Lowell: http://twurl.nl/s5v6ai – “…Petal by petal the flower of our heart…”
July 16th 2009 – “When the Eyes Open” by Dahlia Ravikovitz: http://bit.ly/Z8Re0 -”as the soul returns to the body when the eyes open.”
July 15th 2009 – “Touched by an Angel” by Maya Angelou: http://bit.ly/uAerx – “Yet it is only love which sets us free.”
July 12th 2009 – “A Pearl, a Girl” by Robert Browning: http://bit.ly/6rDpB -”…Through the love in a girl!”
July 10th 2009 – “Valentine” by Carol Ann Duffy: http://bit.ly/YMoIj -”I give you an onion. It is a moon wrapped in brown paper…”
July 4th 2009 – “Moonwalk” by Samuel Peralta : http://bit.ly/4sbHqx -”…The words begin to form a song / The melody begins to burn…”
July 3rd 2009 – “Wild Nights” by Emily Dickinson: http://bit.ly/qOMhk -”…Wild nights should be Our luxury!…”
July 1st 2009 – “If You Forget Me” by Pablo Neruda: http://bit.ly/1j9EgT -”if each day,each hour,you feel that you are destined for..”
Poem: Distant Thoughts August 6, 2009
Posted by yoavniran in Poetry.Tags: hebrew, loss, love, poem, Poetry
add a comment
This one i wrote in June 2004:
The standard disclaimers apply, the poem was originally written in Hebrew therefore the translation may lose or change some of the meanings, rhyming, wordplay, etc.
~ Distant Thoughts ~
Lost,
Cannot find her
She won’t come back to me
No gentle word will be enough.
Drowning,
Air is no longer found
The will to breathe gone as well
My life is where she is
And she is gone.
Blind,
No light is strong enough
No scream in the dark is heard
It is just the wind blowing in the gaping hole
She was mine but no more.
Stumbling,
Step after step
Direction unknown
She will not be there when I arrive
Where will that be – doesn’t matter.
Dreaming,
The Images a blur
Like leafs a moment before the storm
What was – that was no dream
As real as pain
Pain of loss and longing
The dream slowly dissipates
Not Breaking,
Not whole either
A piece is distant and missing
Even when the wound heals
The scar will remain to remind me
And she, she will also be with me.
The original Hebrew version:
~ מחשבות רחוקות ~
אבדתי,
אינני מוצא אותה
שוב אלי היא לא תחזור
שום מילה עדינה לא תספיק.
טובע,
האוויר גם הוא לא בנמצא
והרצון לנשום גם הוא נעלם
חיי היכן שהיא תהיה
והיא איננה.
עיוור,
אף אור לא חזק מספיק
אף צעקה בחושך איננה נשמעת
רק הרוח המנשבת בחלל שנפער
שלי הייתה אך לא עוד.
מועד,
צעד אחר צעד
הכיוון אינו ידוע
אך היא לא תהיה שם כשאגיע
גם לא תהיה שם לפני שאלך
לאן – זה כבר לא משנה.
חולם,
התמונות מסתחררות
כמו העלים רגע לפני שהסערה מגיעה
אך מה שהיה לא חלום הוא
אמיתי כמו הכאב
כאב של אובדן וגעגוע
אט אט מתפוגג לו החלום.
לא נשבר,
אך גם לא שלם באמת
משהו חסר ותמיד רחוק
גם שהפצע יחלים
הצלקת תשאר להזכיר לי
והיא, גם היא תשאר איתי.
Creating a Webservice Proxy with jQuery August 2, 2009
Posted by yoavniran in Programming.Tags: .NET, AJAX, how to, javascript, jquery, REST, RSS, The 404, tutorial, WCF, Web Services
1 comment so far
Contents
Introduction
In a previous post I’ve shown how to use WCF, jQuery and jTemplates to retrieve information from the server and lay it out on the page using jTemplates’ templating engine.
The code example in that article used the Microsoft Ajax client library and the proxy it creates at run time to ease the javascript code needed to call the methods of the webservice I created.
In this article I would like to show an easy way of creating a similar proxy to the Microsoft one in pure javascript and the help of jQuery’s AJAX abilities. This makes a lot of sense if you do not have the option to use the MS library on the client or simply don’t want to.
I will be relying mostly on the code examples and concepts I described in the previous article so I’d recommend reading it first before continuing to read this post.
Server Side
The good news: no need to change anything on the server side, the web service can continue to work as it always did. All we’re doing in this exercise is to replace the client side logic and so we will not touch the server code.
Client Side
Using the same website ive shown how to create in the previous article we will create the new proxy for our WCF webservice.
In the System folder create a javascript file and call it ServiceProxy.js, To the file add the following code:
ServiceProxy = function() //constructor for the proxy
{
this._baseURL = "Services/TutorialService.svc/";
};
ServiceProxy.prototype =
{_defaultErrorHandler: function(xhr, status, error)
{
alert(xhr.statusText);
},
_doAjax: function(method, data, fnSuccess, fnError)
{
if (!data) data = {};
if (!fnError) fnError = this._defaultErrorHandler;
$.ajax({
type: "GET",
url: this._baseURL + method,
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: fnSuccess,
error: fnError,
dataFilter: function(data)
{
var response;
if (typeof (JSON) !== "undefined" && typeof (JSON.parse) === "function")
response = JSON.parse(data);
else
response = val("(" + data + ")");
if (response.hasOwnProperty("d"))
return response.d;
else
return response;
}
});
}
};
Lets examine the code:
The first section is the constructor of the proxy object, in there we define the base URL of the service we will be calling.
The second method is _defaultErrorHandler, this is a default error handler, its strictly a developer friendly method, allowing the calling method to leave the pointer to an error handling method empty. Of course the implementation of this default error handler should be changed in a real life scenario as its not wise to show any raw error information to a website’s visitor.
The third and most important method is _doAjax, this is where the “magic” happens which takes care of the back and forward communication with the server.
The first two lines take care of the defaults, if there is no data passed to the webservice we assign an empty object and if there is no pointer supplied to an error handler we assign our default method.
Next is the where we use jQuery’s incredibly convenient Ajax method, lets examine this call, jQuery’s ajax method accepts an object that sets all the needed information:
‘type’: The HTTP verb: could be GET, POST, etc. In this example we use GET since we’re only retrieving from the server.
For a more robust scenario we would probably want to make this into a parameter of the method.
‘url’: The URL of the webservice method, in this case the base URL defined in the constructor and the name of the method.
‘data’: The parameters passed to the service method, constructed as a JSON object.
‘contentType’: the content type of the data being sent to the server. In our case we’re communicating with the webservice using JSON and therefore we use: “application/json; charset=utf-8”
‘success’: A pointer to the method to be called when the asynchronous call has finished successfully.
‘error’: A pointer to the method to be called when the asynchronous call finished with an error.
‘dataFilter’: I’ve taken the code block in this example from Dave Ward’s Encosia blog. I will add the links to a couple of his articles at the end of this post.
The dataFilter is used whenever there is a successful response from the server and allows us to modify the response in any way we like before its passed to the success method.
In this example there are two uses to the filter: The first one is to turn the response into a JSON object from the string result coming from the server. It will first check whether the current browser supports JSON parsing natively (Firefox 3.5, IE8 for example). If it does it will use the native JSON object and if not will use the less optimized and less secure eval() function.
The second part is to check whether the response is enclosed within a ‘d’ property, this ‘d’ property is added automatically by Microsoft’s WCF service and since we want to abstract this fact from the caller we only return the relevant response if this is the case.
Now that we have everything we need for our base proxy functionality all we need to do is add the methods that match the exposed methods on the webservice. To the prototype of the ServiceProxy object add these two methods:
getArticles: function(success, error)
{
this._doAjax("GetArticles", null, success, error);
},
getArticle: function(link, success, error)
{
var data = {link: link};
this._doAjax("GetArticle", data, success, error)
},
These two methods call our _doAjax, passing the necessary information such as the method name and the parameters if needed to the call.
In fact the methods mirror the methods available on the webservice thus completing the proxy.
Now the only thing to do is create a HTML file (or any other file, could even be JSP) that will replace the aspx page we created in the previous article.
You can find all the source code in the example site ive made available for download, in this post I will only show the changes needed.
- First, create a default.html in the root of the site.
- In the head element add these links:
<script src=”System/jquery.js” type=”text/javascript”></script>
<script src=”System/jquery-jtemplates.js” type=”text/javascript”></script>
<script src=”System/ServiceProxy.js” type=”text/javascript”></script>
<link href=”System/Styles.css” rel=”stylesheet” type=”text/css” />
- Copy over the entire javascript element.
- Add the following line as the first line of the script:
<script type="text/javascript">
var proxy = new ServiceProxy();
…
- In the document ready function replace the call to the GetArticles method with this one:
$(document).ready(function() //executes this code when page loading is done
{
proxy.getArticles(articlesRetrieved);
});
- In the loadArticle function replace the call to getArticle with this one:
function loadArticle(link)
{
$("#LoadingImg").removeClass("Hidden");
$("#SingleArticle").html("");
proxy.getArticle(link, articleRetrieved, serviceDefaultErrorHandler);
}
That’s all! Now you have a working page doing exactly the same as it did before only using our own javascript proxy without any dependencies on the Microsoft proxy or the MS Ajax library.
The end result is as expected identical to the one before:

Source Code
Can be downloaded here.
Resources
Poem: Love is Possible July 29, 2009
Posted by yoavniran in Poetry.Tags: love, poem, Poetry, tel aviv
add a comment
This is one i wrote today: 29/07/2009 (on the way to work).
~ Love is Possible ~
Walking down the street alone
The throng around me pulses
A pretty girl passes by
Is there a small smile for me
Hiding in her weary expression?
Walking resumes, I never stopped
Nevertheless I resume.
The letters on the street wall say:
“Love is Possible”
No question mark, it’s just there
Why do the letters seem to quiver?
Three little words
Words giving hope, words obliterating consciousness
Do these words lie to me?
Go on walking, I didn’t stop
Yet I continue.
“LOVE IS POSSIBLE”
I shout to the foggy air
There is no doubt in the sound
Then why does my voice quiver?
The echo seems to mock me
Did my heart lie?
Is that the sun behind rolling clouds?
Will it shine for me?
Poem: In Love’s Defense July 18, 2009
Posted by yoavniran in Poetry.Tags: life, love, poem, Poetry
add a comment
This one i wrote today: 18/07/2009.
Enjoy.
~ In Love’s Defense ~
In love’s defense,
she was here first
Long before we came along
She was never ours to hold
She never belonged to us
but to the world
Belonged to the butterflies’ wings
and to the tree tops’ wind
Our claim on her was never just
All our praises never enough
In Love’s defense,
She never presumed to be more
than what she is
Never asked for anything in return
Not once ridiculed our ethereal groping
Her light continues to elude
our ever present darkness
She dances between music notes
Swims in life’s deep currents
She is free
for us to enjoy
She is here
for us to share
Never own
In love’s defense -
She is LOVE.
Implementing the XSLT Mediator – Part 2 July 17, 2009
Posted by yoavniran in Programming, Tridion.Tags: .NET, CMS, extension objects, how to, mediator, modular templating, templates, Tridion, xml, XSLT
7 comments
Contents
- Introduction
- .NET XSLT Extension Objects
- Creating an Extension Object
- Using Extension Objects – The Old Way
- Using Extension Objects – The New Way
- XSLT Page Template
- Conclusion
- Source Code
- Resources
Introduction
In the previous article I’ve discussed the fundamentals of setting up the XSLT Mediator, configuring it and then showed how to create a simple compound component template which is making use of an XSLT TBB.
In this article I would like to concentrate mainly on extension objects; a little bit on what they are and how to make use of these in conjunction with the mediator.
.NET XSLT Extension Objects
The .NET Framework allows us to extend the style sheets we build by creating Extension Objects, these can be simple classes that contain helper or utility methods.
Some functionality is either extremely difficult or impossible to implement in pure XSLT code, for example we may want to retrieve a list of items from Tridion, doing this in just XSLT will be complicated and unmanageable to say the least.
The extension feature allows writing the logic for this kind of functionality in .NET managed code, we may even already written this code for a different part of our implementation and we simply want to reuse it.
If this concept is still unclear I am sure it will become more so further in the article, I will also add some links to other resources on the web that cover this area more thoroughly.
Creating an Extension Object
We’ll begin by creating a simple class with some useful methods that we can reuse in multiple templates:
using System.Text;
using System.Xml;
using Tridion.ContentManager;
using Tridion.ContentManager.ContentManagement;
using Tridion.ContentManager.Publishing.Rendering;
using Tridion.ContentManager.Templating;
namespace Tridion.Extensions.Templating.XsltHelpers
{
public class SimpleXsltHelper
{
private TemplatingLogger m_Logger = null;
private Engine m_Engine = null;
public SimpleXsltHelper(Engine engine)
{
m_Engine = engine;
m_Logger = TemplatingLogger.GetLogger(this.GetType());
}
///
/// Returns the result of rendering the provided component and compomnent tempalte in a xml document
///component = the TCM URI of the component
///componentTemplate = the TCM URI of the component template
public XmlDocument RenderComponentPresentation(string component, string componentTemplate)
{
StringBuilder sb = new StringBuilder();
using (XmlWriter xWriter = XmlWriter.Create(sb))
{
xWriter.WriteStartElement("result");
TcmUri compURI = new TcmUri(component);
TcmUri ctURI = new TcmUri(componentTemplate);
xWriter.WriteRaw(m_Engine.RenderComponentPresentation(compURI, ctURI));
xWriter.WriteEndElement(); //result
}
XmlDocument resultDoc = new XmlDocument();
resultDoc.LoadXml(sb.ToString());
return resultDoc;
}
/// Used to publish a binary to the presentation server
/// compURI = the TCM URI of the multimedia component to publish
/// Returns the publish path of the binary
public string PublishBinary(string compURI)
{
Component comp = m_Engine.GetObject(compURI) as Component;
string publishPath = comp.Id;
if (comp.BinaryContent != null)
{
Binary pubBinary = m_Engine.PublishingContext.RenderedItem.AddBinary(comp);
m_Logger.Debug("PublishBinary: published Binary: " + comp.Id + " to url: " + pubBinary.Url);
publishPath = pubBinary.Url;
}
else
m_Logger.Warning("PublishBinary: " + comp.Id + " is not a multimedia coomponent");
return publishPath;
}
}
}
Here’s an explanation of the code:
The constructor of the class accepts a single parameter, an instance of the Engine (Tridion.ContentManager.Templating.Engine) class.
RenderComponentPresentation(string component, string componentTemplate) – this method accepts the TCM URI of a component and the TCM URI of a component template, renders the two and returns the resulting content in an xml document.
PublishBinary(string compURI) – this method accepts the TCM URI of a multimedia component and using the AddBinary method makes sure the binary is published to presentation server. The method returns the relative path of the published binary file.
The reason for creating this class is to be able to call the methods defined in it from an XSLT TBB, the next couple of sections demonstrate ways of accomplishing this.
Using Extension Objects – The Old Way
When I released the XSLT Mediator there was only one way for adding extension objects. To add an object to the transformation we had to create the class in the Mediator’s assembly project and inject the line of code for adding the object into the mediator’s class.
I’ve later improved this a bit by making the method in charge of adding extension objects Virtual so a developer can create their own mediator inheriting from the Tridion.Extensions.Mediators.XsltMediator and overriding that method.
So a project with a custom extension object will look something like this:

In the image above you can see the helper class (which we’ll use as an extension object) and the custom mediator inheriting from the XsltMediator.
The code for our custom mediator will look like this:
using System.Xml.Xsl;
using Tridion.Extensions.Mediators;
namespace XSLTMediator.Tutorials
{
public class MyCustomMediator : XsltMediator
{
protected override void AddExtensionObjects(XsltArgumentList arglist)
{
SimpleXsltHelper helper = new SimpleXsltHelper(this.Engine);
arglist.AddExtensionObject("http://www.tridion.com/customhelper", helper);
base.AddExtensionObjects(arglist);
}
}
}
The code is very straightforward, We override the virtual method AddExtensionObjects which accepts a single parameter of type System.Xml.Xsl.XsltArgumentList.
To the arglist parameter we can add our extension objects using its method AddExtensionObject(string, object).
The method expects two parameters, the first, a String, which should contain a unique namespace within the transformation. This can be just about any string of characters you decide to use as long as its unique.
The second parameter is the actual extension object which is an instance of the SimpleXsltHelper class we created earlier.
The last line of code to mention is
base.AddExtensionObjects(arglist);
This makes sure that the helper extension object which is bundled with the mediator is also available in the transformation. If you don’t plan on using this helper object you can simply omit that line of code from your implementation.
To be able to start using our new extension object there is one last step which is needed. In the previous article I’ve showed how to configure the basic mediator in the Tridion configuration file.
First build the project and overwrite the existing Mediator DLL file with the new build.
Since now we have a new custom implementation of the mediator we need to configure this new class name instead.
So in the Tridion.ContentManager.config file change the type attribute of the XSLT mediator from: Tridion.Extensions.Mediators.XsltMediator to XSLTMediator.Tutorials.MyCustomMediator
(the namespace and class name will obviously be different in real implementations).
Make sure you restart all the necessary services as explained in the first article.
Now we can go ahead and use the new methods we created in our XSLT templates.
We will go on and extend the XSLT template used in the previous article:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt"
xmlns:simple="uuid:3CC625ED-34E6-4B51-BDD8-72BBD0D71469"
xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns:tcm="http://www.tridion.com/ContentManager/5.0"
xmlns:customHelper="http://www.tridion.com/customhelper"
xmlns:image="http://www.tridion.com/ContentManager/5.0/DefaultMultimediaSchema" exclude-result-prefixes="msxsl simple customHelper">
<xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
<xsl:template match="/">
<xsl:element name="p">
<xsl:apply-templates select="tcm:Component/tcm:Data/tcm:Content/simple:Content"/>
</xsl:element>
</xsl:template>
<xsl:template match="simple:Content">
<xsl:element name="h3">
<xsl:value-of select="simple:title"/>
</xsl:element>
<xsl:element name="div">
<xsl:copy-of select="simple:body"/>
</xsl:element>
<xsl:element name="div">
Publish Date: <xsl:value-of select="simple:pubDate"/>
</xsl:element>
<xsl:element name="img">
<xsl:attribute name="alt">
<xsl:value-of select="document(simple:image/@xlink:href)/tcm:Component/tcm:Data/tcm:Metadata/image:Metadata/image:altText"/>
</xsl:attribute>
<xsl:attribute name="src">
<xsl:value-of select="customHelper:PublishBinary(simple:image/@xlink:href)"/>
</xsl:attribute>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
First thing to notice is the declaration of the helper class namespace at the top:
xmlns:customHelper=”http://www.tridion.com/customhelper”. The important part is the namespace itself, it should be exactly the same as the one used in the Mediator’s code.
The prefix we assign this namespace can be anything we decide on as long as its unique within the context of our template.
The second part to notice is the call to our PublishBinary() method, using the prefix defined previously we can call any public method defined in the extension object’s class (As long as we use valid parameter data types). Since this method returns the publish path of the binary being published in our example we can use the returned value to set the ‘src’ attribute of the ‘img’ HTML element.

Notice that this time when we execute the compound template there is no need for the default finish actions, the image is published by the XSLT Template and the extension object.
Hopefully this simple example shows how extension objects can be used to augment XSLT templates in such a way that provides a very robust and manageable model.
Using Extension Objects – The New Way
As can be seen from previous sections its quite simple to create XSLT templates for compound templates and even add custom logic in the form of extension objects.
One thing bothered me about this process and that is that this type of templating model basically forces managing code in two locations, two projects: one is the templates projects which is uploaded into Tridion using the assembly upload tool and the second is the Mediator project which during a project and/or implementation is updated with extension objects and helper methods.
These two projects have to be maintained separately even though they both contain functionality which is ultimately used for one purpose – templates.
Because of this issue I came up with a new and in my view better way of creating and maintaining extension objects. This way allows you to create the class(es) in the same project you develop your templates.
The Mediator then loads the extension object(s) from Tridion in a similar manner to how Tridion loads .NET templates.
Using this new way you no longer need to keep updating the Mediator project, you can simply use the provided mediator as is.
To create extension objects in the Templates project you need a few things, if you are using the base project (available on world) you’ll have an easier time because everything you need is provided there.
First, any class which is meant to be used as an EO (Extension Object) should implement an interface, this is an interface you can create yourself or you can use the one in the base project, IXsltHelper. it doesn’t really matter which interface it is actually as we will see in a minute.
The second thing needed is to decorate any class used as an EO with an attribute class, TridionXSLTHelperNSAttribute. This attribute is used to define the namespace the EO will be assigned with when inserted into the argument list.
If you’re not using the base project or using an old version of it, simply download the new project from SDLTridionWorld and copy the TridionXSLTHelperNSAttribute class file to your project.
Your project should have similar elements to this example:

Since we already created a sample extension object we can reuse it by adding it to our templates project.
We will need to modify it a bit to conform to our new style:
using System.Text;
using System.Xml;
using Tridion.ContentManager;
using Tridion.ContentManager.ContentManagement;
using Tridion.ContentManager.Publishing.Rendering;
using Tridion.ContentManager.Templating;
using Tridion.Extensions.ContentManager.Templating;
namespace Tridion.Extensions.Mediators
{
[TridionXSLTHelperNS("http://www.tridion.com/customhelper")]
public class SimpleXsltHelper : IXSLTHelper
{
private TemplatingLogger m_Logger = null;
private Engine m_Engine = null;
.
.
.
Notice that now the SimpleXsltHelper is implementing our IXSLTHelper interface and has the TridionXSLTHelperNS attribute. The value we pass the attribute is the same namespace we used earlier so that means there is no need to change the XSLT at all.
The mediator will take care of the rest, but to make sure it does we need to add a few configuration parameters to the Tridion.ContentManagaer.config file in this fashion:
<mediator matchMIMEType="text/xml" type="Tridion.Extensions.Mediators.XsltMediator" assemblyPath="C:\Program Files\Tridion\bin\Tridion.Extensions.Mediators.dll">
<parameters>
<parameter name="loadFromTridion" value="true"/>
<parameter name="interfaceName" value="IXSLTHelper"/>
<parameter name="templateID" value="tcm:42-15958-2048"/>
</parameters>
</mediator>
Let’s go over the parameters:
loadFromTridion: True or False telling the mediator whether to look for extension objects in Tridion.
interfaceName: The Mediator loads the assembly for Tridion and will look for classes that implement an interface with this name.
templateID: The TCM URI of the template building block containing the templates assembly.
As always make sure to restart all the necessary services after making the configuration changes.
From now on you can create and modify your extension objects as if they were any other .NET template you were working on. Updating the code in Tridion requires the same process as do normal templates and there are no extra steps needed.
It also means you have only one project containing all your templating functionality code which I think is a massive improvement.

Running our compound CT again gives us the exact same result as before:

XSLT Page Template
Up until now we have been working on a compound component template that was using a XSLT TBB but it wasn’t doing much more than what could be accomplished with normal XSLT CT.
Here is an example of a simple XSLT page template:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt"
xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns:tcm="http://www.tridion.com/ContentManager/5.0"
xmlns:customHelper="http://www.tridion.com/customhelper"
exclude-result-prefixes="msxsl customHelper">
<xsl:output method="html" indent="yes" omit-xml-declaration="yes"/>
<xsl:template match="/">
<html>
<head>
<title>
<xsl:value-of select="tcm:Page/tcm:Data/tcm:Title/text()"/>
</title>
</head>
<body style="background-color:yellow;">
<xsl:for-each select="tcm:Page/tcm:Data/tcm:ComponentPresentations/tcm:ComponentPresentation">
<p>
<xsl:variable name="cp" select="customHelper:RenderComponentPresentation(tcm:Component/@xlink:href, tcm:ComponentTemplate/@xlink:href)"/>
<xsl:copy-of select="$cp/result/node()"/>
</p>
</xsl:for-each>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
As with the Component Template created in the first part of this tutorial, you will need to create a XSLT TBB and paste the above code into the source pane, then create a new compound page template in the Template Builder and add the new XSLT TBB to the list of selected templates.
Save and close the new PT and create a new page based on this page template.
Now we can preview our XSLT page template successfully:

Very easily we created a new page template in XSLT, to render the component presentations on the page we use a method we added to the extension object which returns the resulting content and layout in an XML document that is stored in a variable from which we can copy it onto the page.
Conclusion
In this article I focused mainly on creating extension objects and using them from XSLT templates.
I showed two ways of including extension objects in the transformation of templates, both are valid but the second is much more convenient in terms of deploying and managing the functionality of extension objects..
I’ve even added a simple example of a XSLT page template which is where the benefit of using the XSLT Mediator is really obvious since Tridion doesn’t support this type of template natively.
The XSLT Mediator comes with an extension object which is added to the transformation by default. The namespace for this object is: “http://www.sdltridion.com/ps/XSLTHelper”
This default object comes with some useful methods:
getFormatedDate – Generic XSLT helper function to format date strings using standard format strings.
getListItems – Generic XSLT helper function to retrieve items from within an OrganizationalItem
GetMultimediaInfo – Returns xml with information about the MM component such as the mime type or extension
Source Code
Can be downloaded here.
