Wilsonhut

Deal with it or don't

Monthly Archives: March 2013

Obvious Methods: IDictionary Get – With Defaults plus

This is a follow-up to my post Obvious Methods: IDictionary Get – with defaults

Now the methods will add to the list, if you want.

public static TValue Get<TKey, TValue>(this IDictionary<TKey, TValue> dictionary,
		                                    TKey key, Func<TKey, TValue> getDefaultValue,
		                                    bool addDefaultToSource = false)
{
	TValue value;
	if (dictionary.TryGetValue(key, out value))
	{
		return value;
	}

	value = getDefaultValue(key);
	if (addDefaultToSource)
	{
		dictionary.Add(key, value);
	}
	return value;
}

public static TValue Get<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key,
		                                    Func<TValue> getDefaultValue, bool addDefaultToSource = false) { return dictionary.Get(key, k => getDefaultValue(), addDefaultToSource); } public static TValue Get<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue defaultValue, bool addDefaultToSource = false) { return dictionary.Get(key, k => defaultValue, addDefaultToSource); } public static TValue Get<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, bool addDefaultToSource = false) { return dictionary.Get(key, k => default(TValue), addDefaultToSource); }

Check out Obvious Methods: IDictionary Get – with defaults for how to use it.

Advertisements

Get User Identity in your log4net

You want your website’s log4net logs to have the authenticated user’s name. Here’s all you do.

(credit to Gian Marco Gherardi)

Add this in your code (right after you call XmlConfigurator.Configure(…) would be fine.)

	GlobalContext.Properties["user"] = new HttpContextUserNameProvider();

Then…

	public class HttpContextUserNameProvider
	{
		public override string ToString()
		{
			HttpContext context = HttpContext.Current;
			if (context != null && context.User != null && context.User.Identity.IsAuthenticated)
			{
				return context.User.Identity.Name;
			}
			return "";
		}
	}

The, in your log4net config, you can use it with “%property{user}”
like so…

<conversionPattern value="%date %-5level %property{Category} [%property{user}] - %message%newline" />

Like a charm.