May
30
2010

Umbraco: Breadcrumb Trail



Posted in ASP.NET and Programming

I’ve been using Umbraco recently, and always find it hard to find XSL templates or spend hours tweaking one when countless other people must have done the same thing, but not published the finished stylesheet.

Below is a navigation breadcrumb template which prints a trail to the current page, starting with level 1.
Read more »

Mar
8
2010

Entity Framework in Mednium Trust



Posted in ASP.NET

ASP.NET and medium trust typically don’t get along well once you start using third party libraries. It really should, however, be easier to get the Entity Framework working on medium trust, and this had me baffled for a few hours trying to split the EDMX file and other fruitless solutions.

To get this working I needed to:

  1. Move the EDMX to a separate assembly.
  2. Set the EDMX metadata artifact processing to ‘Embed in output assembly’.
  3. Add a reference in the site.
  4. Change the connection string to
    <add name="ShopEntities" connectionString="metadata=res://*/;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=servername;Initial Catalog=dbname;User Id=username;Password=P@55word;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" />

Which every guide claimed would work. There’s one more step if you have custom partial entity classes (in App_Code). If so, these also need to be moved to your output assembly, as you can’t split partial classes across assemblies. Lastly, change the namespace in your partial classes to the same as your output assembly, and everything should work.

Feb
7
2010

Watermarked TextBox with an AttachedProperty



Posted in Programming and WPF

Ever wanted to create a watermark effect for a TextBox in WPF? Most of the tutorials scattered around have either used static text or created a subclass of TextBox. I wanted to use an AttachedProperty instead, and though it took a while to try every possible combination of brackets and bindings I came up with the following to create an AttachedProperty which you can apply in any ResourceDictionary or wherever you keep your Styles.


Watermarks with Attached Properties
Get the code after the jump.

Read more »

Jan
30
2010

Creating query strings with LINQ



Posted in Programming

While implementing a recipe search API for ChickenPing, I’ve just spotted the following hilariously verbose piece of code which concatenates parameters as part of a GET request.

StringBuilder buffer = new StringBuilder();
bool first = true;
foreach(KeyValuePair<string , string> parameter in parameters) {
    if(first) {
        first = false;
    } else {
        buffer.Append('&');
    }
    if(encodeParams) {
        buffer.AppendFormat("{0}={1}", System.Uri.EscapeDataString(parameter.Key), Uri.EscapeDataString(parameter.Value));
    } else {
        buffer.AppendFormat("{0}={1}", parameter.Key, parameter.Value);
    }
}
string queryString = buffer.ToString();
</string>

The worst thing is I only wrote this about six months ago. I simplified it to the following with LINQ:

Read more »

Dec
19
2009

Minimize To Tray with WPF



Posted in Programming and WPF

I’ve been working on porting LockCrypt to WPF from Java and was pretty shocked to find there was no no built-in support. It’s entirely possible, but you have to use WinForms. I based this on Delay‘s sample, feel free to use it however you wish.

namespace Lime49.WPF {
    /// <summary>
    /// Tray minimization utility, based on Delay's code - http://blogs.msdn.com/delay/.
    /// </summary>
    public static class TrayMinimizer {
        /// <summary>
        /// Enables "minimize to tray" behavior for the specified Window.
        /// </summary>
        /// <param name="window">Window to enable the behavior for.</param>
        public static void EnableMinimizeToTray(Window window) {
            if(MinimizeInstances.ContainsKey(window)) {
                Console.WriteLine(string.Format("Minimization already enabled for '{0}'", window.Title));
            } else {
                var instance = new MinimizeToTrayInstance(window);
                instance.Enable();
                MinimizeInstances.Add(window, instance);
            }
        }

Read more »

Sep
7
2009

WPF: TextBox Error Notification Through Style



Posted in Programming and WPF

By default, WPF doesn’t provide any visual indication when ValidationRules aren’t met for TextBoxes. When I was learning WPF, I read a post about providing error notification for TextBoxes through the user of a style. I can’t find the article/post, but it never worked properly for me so I’ve modified and fixed what I had. This only works if there are ValidationRules bound to the TextBox, and it only displays the first failed rule.

<style TargetType="{x:Type TextBoxBase}" x:Key="{x:Type TextBox}">
  <setter Property="Margin" Value="2" />
  <setter Property="SnapsToDevicePixels" Value="True"/>
  <setter Property="OverridesDefaultStyle" Value="false"/>
  <setter Property="KeyboardNavigation.TabNavigation" Value="None"/>
  <setter Property="FocusVisualStyle" Value="{x:Null}"/>
  <setter Property="MinWidth" Value="80"/>
  <setter Property="MinHeight" Value="20"/>
  <setter Property="AllowDrop" Value="true"/>
  <setter Property="Background" Value="{StaticResource WindowBackgroundBrush}" />
  <setter Property="BorderBrush" Value="{StaticResource SolidBorderBrush}" />
  <setter Property="Template">
...
</setter></style>

The rest is after the jump.

Read more »

Jul
31
2009

WPF: Changing Input Focus to Hidden Elements



Posted in Programming and WPF

When trying to change the focused element in the WPF recipe management app I develop, ChickenPing, I recently ran into a problem. I wanted a shortcut key (Ctrl + something) to change the selected tab in a TabControl, then focus an element in that tab. There are a few ways you might try doing this, both do more or less the same thing and both will fail unless the tab in question is already selected. For example:

 tabControl.SelectedItem = someTab;
 someTextBox.Focus();
 FocusManager.SetFocusedElement(this, someTextBox);
 // both only work unless the tab which contains them is visible.

The problem is that an element can only be focused if it is visible. Making the item visible just before trying to focus it fails because the change hasn’t had time to take effect.

Read more »

Jul
29
2009

TopMost Window In XAML



Posted in Programming and WPF

I was kind of looking forward to delving into some native call to make a Window always on top in WPF, but it was actually surprisingly easy, a single binding in the Window’s declaration:

<Window ...
	Topmost="{Binding ElementName=itmTopMost,Path=IsChecked}"
...
	<MenuItem Header="_Always on Top" x:Name="itmTopMost" IsCheckable="True" />

No code involved!

Jul
25
2009

ASP.NET: Remove from the cache using



Posted in ASP.NET and Programming

The Cache object in ASP.NET isn’t like other collections, probably because it needs to be specialized so it doesn’t make use of generics. Unfortunately, that makes it more difficult to work with. This small utility method removes an object from the cache by key using a predictate. You could easily modify it to compare either of the IDictionaryEnumerator’s Key or Value properties.

/// <summary>
/// Removes an item from the cache using a Predictate to match the key.
/// </summary>
/// <param name="keyCriteria">The Predictate to use for each key to determine whether the entry should be removed.</param>
/// <summary>
/// Removes an item from the cache using a Predictate to match the key.
/// </summary>
/// <param name="keyCriteria">The Predictate to use for each key to determine whether the entry should be removed.</param>
public static void RemoveFromCache(Predicate<string> keyCriteria) {
	IDictionaryEnumerator enuma = HttpContext.Current.Cache.GetEnumerator();
	while(enuma.MoveNext()) {
		if(keyCriteria(enuma.Key.ToString())) {
			HttpContext.Current.Cache.Remove(enuma.Key.ToString());
		}
	}
}
Jul
9
2009

ASP.NET: Data Binding with ObjectDataSource



Posted in ASP.NET and Programming

In the past when writing forms with ASP.NET I’ve usually used an SqlDataSource when binding to controls, but I’ve been doing a lot of WPF lately. Being a desktop platform, WPF has excellent support for DataBinding, but obviously since HTTP is a stateless protocol (apart from the ViewState in ASP.NET which isn’t ideal), it’s not so well suited to data binding.

One thing I’ve never really tried is binding an object to a form to display a single item (eg: a report). This leads to writing lots of tedious code like:

	Order theOrder = GetOrder(orderId);
	litName.Text = theOrder.Name;
	litID.Text = theOrder.ID;
	litCustomer.Text = theOrder.BillingCustomer.Name;
	...

Read more »



Page 1 of 29123451020...Last »