Category: snippets - small bits of code

WPF Conditional Converter

PS
Sometimes the enabling/visibility of a control has to be based on whether a bounded property matches a value or not.

Using the System.Windows.Data.IValueConverter and making use of ConverterParameter, we can set this up generically to compare with the bounded value as shown in the code tab.

This is easier that setting up the code to programmatically do this / creating special properties like IsSomething. With judicious use of parameter name, this can be carried to any level.

Code

// Usage
ConditionalConverter.Register("IsSomething", "What1", false, true);
ConditionalConverter.Register("NotSomethingElse", "What2", false, true);
// In WPF
// ctl IsEnabled="{Binding Path=ItemName, Converter={StaticResource ConditionalConverter}, ConverterParameter=IsSomething}"


// In the Converter
private static Dictionary<string, Tuple<object, object, object>> Conditions = new Dictionary<string,Tuple<object,object,object>>;

public static void Register<T>(string parameter, object value, T valueIfEqual, T valueIfNotEqual)
{
	Conditions[parameter] = new Tuple<object, object, object>(value, valueIfEqual, valueIfNotEqual);
}

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
	Tuple<object, object, object> condition;
	if (Conditions.TryGetValue((string)parameter, out condition) == false)
	{
		throw new InvalidOperationException("Not registered with Parameter:" + parameter);
	}

	return condition.Item1.Equals(value) ? condition.Item2 : condition.Item3;
}

MVC Generic Html by anonymous type

PS
There is no equivalent for asp’s create generichtmlcontrol.
In some rare cases, it may make sense to do this. Esp when the generation of html is mixed with @ directives inside “” for attrs.

*Note that class is a keyword and cant be used as property name in the anonymouse type. So we use CssClass instead and make the Extension method aware of this possibility.

@Html.StartTag("div", new { id ="name", CssClass = "cls", style= @Model.Styles})
@Html.EndTag("div")

UPDATE (Feb 10th): You can say @class to use the reserved keyword. So the code atts[“class”] = atts[“CssClass”]; is redundant

Read more »

NHib Atleast One Check

PS
NHibernate doesnt have a way to check whether a List has atleast one item.
This kind of validation is important and if it fails, atleast the save should catch it.
This can be done with a neat Mapper extension and an on save listener.

//Register with the NH Configuration
configuration.SetListener(ListenerType.SaveUpdate, new HasAtleastOne.Listener());

//Use in the classMap
HasMany(x => x.Links).KeyColumn("Project_id").MustHaveAtleastOne();

//Test the code
var l = new HasAtleastOne.Listener();
var e = new Project();
l.TestSave(e);

Read more »

save datarow / table with concurrency check

PS
You can initialize a dataadaptor with a top 0 * from table, pass that to a SqlCommandBuilder to get insert / update commands.

If you set the ConflictOption of the builder to OverwriteChanges, it will not use all the fields in the where condition (default option CompareAllSearchableValues)

To change the rowversion, you need to adapt the command, add rowversion in the where condition so that ado.net throws a DBConcurrencyException if it has been changed by another user.

Modifying the da.UpdateCommand does not seem to change the actual query run on the db for the individual row. You need to then hook the DataAdapter’s RowUpdating event. This gives the command per row. of course, if its an insert, you do nothing because defaults are specified in the db.

Lastly, once the update is made in the db, we need to change the rowversion in the datarow because otherwise the second save will fail.
Read more »

displaying tree info

Statement

given an item which has a parent of itself, its possible to make this into a hierarchical object format and diplay it using a combination of ul / li.

I’ve developed this in both C# and cakephp (See overleaf), and now in 2015 using Yii (without the Set class). Read more »

comparing 2 classes

When Comparing 2 classes, its possible to specify the following
Properties only on the left
Properties only on the right
Same property but with different Types on either side

A sample of this can be seen here

filesize extension method

This extension method humanizes the file size (FileInfo.Length is long but we need to make it into a decimal to get decimal places (long / long = long). Read more »

Dictionary to fill a ComboBox

Simplest was to have key / value pairs displayed in a ComboBox. Read more »