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:
- Move the EDMX to a separate assembly.
- Set the EDMX metadata artifact processing to ‘Embed in output assembly’.
- Add a reference in the site.
- Change the connection string to
<add name="ShopEntities" connectionString="metadata=res://*/;provider=System.Data.SqlClient;provider connection string="Data Source=servername;Initial Catalog=dbname;User Id=username;Password=P@55word;MultipleActiveResultSets=True"" 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.
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.

Get the code after the jump.
Read more »
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 »
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 »
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 »
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 »
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!
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());
}
}
}
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 »
Normally, if there are images on a webpage they’re there to support the content and not excessive, so you don’t have to worry about loading times. What if you need to have an undefined number though, and they happen to be high resolution like a gallery?
For the last site I worked on, the client wanted a gallery of 400×400 pixel images to cycle in a gallery on the front page of the site. They’re about 70KB each so if you’re loading 10 or more of them in the middle of the page, they’ll slow the page load down until they’ve all totally loaded.
The solution I used was to add the images to the DOM after the rest of the content loads.
Read more »