Category: C#

TimeSpan to String Converter for XAML binding

Need to convert a TimeSpan to a sensible string for you Windows Phone or Windows Store App. With a little Bing help I created this converter. I hope you find it useful.


public class TimeSpanToStringConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        TimeSpan span = (TimeSpan)value;
        if (span == TimeSpan.MinValue)
        {
            return "0 seconds";
        }
        string formatted = string.Format("{0}{1}{2}{3}",
            span.Duration().Days > 0 ? string.Format("{0:0} day{1}, ", span.Days, span.Days == 1 ? String.Empty : "s") : string.Empty,
            span.Duration().Hours > 0 ? string.Format("{0:0} hour{1}, ", span.Hours, span.Hours == 1 ? String.Empty : "s") : string.Empty,
            span.Duration().Minutes > 0 ? string.Format("{0:0} minute{1}, ", span.Minutes, span.Minutes == 1 ? String.Empty : "s") : string.Empty,
            span.Duration().Seconds > 0 ? string.Format("{0:0} second{1}", span.Seconds, span.Seconds == 1 ? String.Empty : "s") : string.Empty);
        if (formatted.EndsWith(", ")) formatted = formatted.Substring(0, formatted.Length - 2);
        if (string.IsNullOrEmpty(formatted)) formatted = "0 seconds";
            return formatted;
    }
        
    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        string strValue = value as string;
        TimeSpan resultSpan;
        if (TimeSpan.TryParse(strValue, out resultSpan))
        {
            return resultSpan;
        }
        throw new Exception("Unable to convert string to date time");
    }
 }

The type or namespace name ‘xxxx’ does not exist in the namespace ‘yyyy’ (are you missing an assembly reference?)

If you suddenly find your Visual Studio solution falling to pieces with loads of error messages like the title above when you build. You also know that the project libraries are being referenced correctly and they build OK. Then check that you do not have an uninvited app.config file lurking at the root of any of your projects.

I have spent lots of annoying wasted hours trying to figure this out only to have found that a NuGet installation has added an app.config to the projects.

Delete this and do a rebuild and all should be OK.

The moral of this story is make sure you build and check-in before adding any NuGet packages. Then immediately rebuild after. If this scenario occurs, you know what to do.

C# DateTime.ToString formats quick reference

Always useful too quickly see all the format options for DateTime.ToSring(). Republished here thanks to http://www.geekzilla.co.uk/View00FF7904-B510-468C-A2C8-F859AA20581F.htm

The quickset’s below. For the rest click the link above.

Pattern Equivalent Format string Example
d MM/dd/yyyy 08/22/2006
D dddd, dd MMMM yyyy Tuesday, 22 August 2006
f0 dddd, dd MMMM yyyy HH:mm Tuesday, 22 August 2006 06:30
f1 dddd, dd MMMM yyyy hh:mm tt Tuesday, 22 August 2006 06:30 AM
f2 dddd, dd MMMM yyyy H:mm Tuesday, 22 August 2006 6:30
f3 dddd, dd MMMM yyyy h:mm tt Tuesday, 22 August 2006 6:30 AM
F dddd, dd MMMM yyyy HH:mm:ss Tuesday, 22 August 2006 06:30:07
g0 MM/dd/yyyy HH:mm 08/22/2006 06:30
g1 MM/dd/yyyy hh:mm tt 08/22/2006 06:30 AM
g2 MM/dd/yyyy H:mm 08/22/2006 6:30
g3 MM/dd/yyyy h:mm tt 08/22/2006 6:30 AM
G MM/dd/yyyy HH:mm:ss 08/22/2006 06:30:07
m MMMM dd August 22
r ddd, dd MMM yyyy HH’:’mm’:’ss ‘GMT’ Tue, 22 Aug 2006 06:30:07 GMT
s yyyy’-‘MM’-‘dd’T’HH’:’mm’:’ss 2006-08-22T06:30:07
u yyyy’-‘MM’-‘dd HH’:’mm’:’ss’Z’ 2006-08-22 06:30:07Z
U dddd, dd MMMM yyyy HH:mm:ss Tuesday, 22 August 2006 06:30:07
y yyyy MMMM 2006 August

Redirecting MVC controller to HTTPS if required

Check out this excellent blog on how to create a simple ActionFilterAttribute that handles redirecting to https:// if required.

http://weblogs.asp.net/dwahlin/archive/2009/08/25/requiring-ssl-for-asp-net-mvc-controllers.aspx

then just decorate your whole Controller ot ActionResult method with

[RequiresSSL]
 public class AccountController : Controller
 {
 ...
 }

Getting AddThis.NET for BlogEngine.NET extension working!

There are currently a few hurdles to getting the very useful AddThis.net version 5 extension going on BlogEngine.net version 2.5 or later. I have consolidated the steps here.

There are a few ways of getting an extension added to a BlogEngine.Net project. I decided to use the NuGet approach. If you haven’t got this Visual Studio extension installed yet…do it now! see my earlier blog How to easily add open source libraries to net projects using NuGet).

First Configure NuGet

  1. Right-click on your web project and select ‘Manage NuGet Packages…’
  2. This will display the NuGet Manager. Click on the ‘Settings’ button at the bottom left.
  3. This opens the Visual Studio Option dialog. Make sure that ‘Package Sources’ is selected in the tree on the left.
  4. Enter the following and click the ‘Add’ button and then ‘OK’ on the Options dialog to close and save the new settings.
  5. You should now see the new BlogEngine.Net extensions library list under the ‘Online’ section. If necessary close the NuGet Manager and re-open it from the projects shortcut menu again.
  6. Simply select the extension you like and click ‘Install’. Nice an easy!

Second – Fix the project!

You will now try and rebuild your project to find that a whole load of failures occur.

This is easily fixed.

You will need to add the following reference to /App_Code/Extensions/AddThis.cs and pretty much every file under /App_Code/Extensions/BookmarkButtons, but the errors panel will give you the list of issues.

using BlogEngine.Core.Web.Extensions;

Then rebuild and voila…hopefully no errors!

Refresh a controls binding in Silverlight or WPF without using PropertyChanged

I often need to change the Language (or culture) of a control (changing the Control.Language) or the whole thread (changing CurrentThread.CurrentUICulture). Such as when displaying dates and currencies in a particular culture. Anyone who has tried this will realise that the controls will not reflect the change until an underlying value has updated.

Alternatively you can rebind the control. To help I have created a simple generic method to help.

        
    ///<summary>
    /// Rebinds a controls dependency property to it's original binding. Used to refresh a control.
    /// </summary>
    /// <remarks>Can be used after updating a controls Culture</remarks>
    /// <param name="cntrl">The control to which the dependency property exists</param>
    /// <param name="depprop">The dependency property of the control</param>
    public static void ForceControlRebind(Control cntrl, DependencyProperty depprop)
        {
            try
            {
                BindingExpression BindExp = cntrl.GetBindingExpression(depprop);
                Binding Bind = BindExp.ParentBinding;
                cntrl.SetBinding(depprop, Bind);
            }
            catch (Exception)
            {
                throw;
            }
        }

To rebind a control just pass the Control and the DependencyProperty whose binding you wish to refresh.

So, for a TextBox called txtBox1 the syntax would be:

ForceControlRebind(txtBox1, TextBox.TextProperty);