Skip to content

Instantly share code, notes, and snippets.

@rustyswayne
Last active April 12, 2016 15:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rustyswayne/52a9b7316984ff1ef5c4b546c83f0949 to your computer and use it in GitHub Desktop.
Save rustyswayne/52a9b7316984ff1ef5c4b546c83f0949 to your computer and use it in GitHub Desktop.
Possible static class for currency formatting
/// <summary>
/// A helper that provides quick access to common Merchello currency and operations.
/// </summary>
public static class CurrencyContext
{
/// <summary>
/// Merchello's <see cref="IStoreSettingService"/>.
/// </summary>
/// <remarks>
/// This is lazy to prevent problems with application bootstrapping
/// </remarks>
private static readonly Lazy<IStoreSettingService> StoreSettingService = new Lazy<IStoreSettingService>(() => MerchelloContext.Current.Services.StoreSettingService);
/// <summary>
/// Umbraco's Runtime cache.
/// </summary>
private static readonly IRuntimeCacheProvider _cache = ApplicationContext.Current.ApplicationCache.RuntimeCache;
/// <summary>
/// The store currency.
/// </summary>
// ReSharper disable once InconsistentNaming
private static ICurrency _storeCurrency;
/// <summary>
/// The currency format.
/// </summary>
// ReSharper disable InconsistentNaming
private static ICurrencyFormat _currencyFormat;
/// <summary>
/// Gets the store currency.
/// </summary>
/// <remarks>
/// This assumes that all stores will use the same currency
/// </remarks>
public static ICurrency StoreCurrency
{
get
{
if (_storeCurrency != null) return _storeCurrency;
var storeSetting = StoreSettingService.Value.GetByKey(Merchello.Core.Constants.StoreSettingKeys.CurrencyCodeKey);
_storeCurrency = StoreSettingService.Value.GetCurrencyByCode(storeSetting.Value);
return _storeCurrency;
}
}
/// <summary>
/// Gets the store currency format.
/// </summary>
private static ICurrencyFormat StoreCurrencyFormat
{
get
{
if (_currencyFormat != null) return _currencyFormat;
_currencyFormat = StoreSettingService.Value.GetCurrencyFormat(StoreCurrency);
return _currencyFormat;
}
}
/// <summary>
/// Formats the currency based with symbol and configured culture.
/// </summary>
/// <param name="amount">
/// The amount.
/// </param>
/// <returns>
/// The formatted amount.
/// </returns>
/// <remarks>
/// Overrides for currency format are made in the Merchello.config
/// </remarks>
public static string FormatCurrency(decimal amount)
{
return string.Format(StoreCurrencyFormat.Format, _storeCurrency.Symbol, amount);
}
#region Reset
/// <summary>
/// Clears the static field values.
/// </summary>
internal static void ResetCurrency()
{
_storeCurrency = null;
_currencyFormat = null;
}
#endregion
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment