Tuesday, March 15, 2011

Sitecore and FieldRenderer

I get work with Sitecore quite a bit, and even though I do like the product itself, my biggest gripe is that the online documentation is sparse and not easily searchable. In particular, I could not find the documentation for FieldRenderer format parameters anywhere. These are extremely useful for formatting Date and Image fields.

First include WebControls namespace to use FieldRenderer:
using Sitecore.Web.UI.WebControls;

Next, use the following overload for the Render method:
FieldRenderer.Render(Item item, string fieldName, string parameters);

As far as the parameters argument goes, this where I had to dig endlessly to figure out the right string every time I use the functionality. Here is the info I was able to come up with, which will hopefully save you some time:

1. Date Formatting, add format= and then formatting string you want to use
FieldRenderer.Render(item, "Date", "format=MM/dd/yyyy")

2. Images - one thing to note, URL format is used to combine parameters together.
FieldRenderer.Render(item, "Date", "w=500&h=700&as=1")

For images the list of options is significantly larger:

w: - Width
h: - Height
mw: - Max Width
mh: - Max Height
la: - Language
vs: - Version
db: - Database
bc: - Background Color
as: - Allow Stretch
sc: - Scale (.33 = 33%)

Tuesday, March 1, 2011

WPF - Passing Arguments to Timer.Tick

Recently I worked on a projected that needed to animate objects based on a timer. I wanted to write a generic timer handler to perform an operation on the object passed in to the timer. Initially I tried messed with EventArgs passed to the event handler, but turns out there is an easier way - using the "Tag" property:

// Note: You can have only one DispatchTimer object per class
private DispatcherTimer _timer;

MyClass()
{
    // Timer Start Code
    var myObject = new SomeObject();
    _timer.Interval = TimeSpan.FromMilliseconds(700);
    _timer.Tag = myObject ;
    _timer.Tick += TimerTickEventHandler;
    _timer.Start();
}

private void TimerTickEventHandler(object  sender, EventArgs e)
{
    var timer = (DispatcherTimer)sender;
    var myObject = (SomeObject)timer.Tag;
    // now you can use myObject
    timer.Stop();
}