Ruben would probably
not like it, but I like to use a static UmbracoHelper class in
my user controls that encapsulates all interaction with Umbraco. I
use the web.config file to define certain important IDs that I
might need in my user controls. For example, I usually create
a Settings node so that the content manager can manage things like
the email address to use when sending emails from the website, or
the name of the person said emails appear to come from. I would
then store the id of this node in my web.config file, like so:
<add key="SettingsNodeId" value="1071"/>
Then, I can create a handy method in my UmbracoHelper class
which takes the name of an attribute of the settings node, and
returns its value as a string, like so:
///
/// Get the value of the named attribute from the Umbraco settings node
///
///
///
internal static string GetUmbracoSettingsNodeProperty(string propertyName)
{
// Get the names setting from the Settings node in Umbraco
Node n = new Node(int.Parse(ConfigurationManager.AppSettings["SettingsNodeId"].ToString()));
if (n!= null && n.GetProperty(propertyName) != null)
{
return n.GetProperty(propertyName).Value;
}
else
{
return "";
}
}
And then, in the code of my user control, I can do this to get
the email address, for example:
string strEmailTo =
umbracoHelper.GetUmbracoSettingsNodeProperty("emailTo");
Of course, if your node IDs change, then you need to update your
web.config file to match. I think that there is a method where you
can use the Dictionary object in Umbraco in a similar manner -
anyone got any ideas on this, please leave a comment!
And finally, what if you want to get a value from a different,
arbitrary node? Well, you can store any node ids you want in the
web.config, and then use this function:
/// Get the value of the named attribute from a specified Umbraco node
internal static string GetUmbracoNodeProperty(int nodeId, string propertyName)
{
// Get the names setting from the Settings node in Umbraco
Node n = new Node(nodeId);
if (n != null && n.GetProperty(propertyName) != null)
{
return n.GetProperty(propertyName).Value;
}
else
{
return "";
}
}
To use this, in your user control code you can do this:
litPageIntro.Text =
umbracoHelper.GetUmbracoNodeProperty(
int.Parse(ConfigurationManager.AppSettings["MemberDirectoryNodeId"].
ToString()), "pageIntro");
Assuming your MemberDirectoryNodeId entry in your web.config
actually exists and is set correctly, you now have your Umbraco
content-managed content appearing in your user controls! The
umbracoHelper class gets compiled into your user controls dll, and
gets uploaded to your server along with the compiled code of your
user controls, so you don't need to worry about it. Easy!
David