Category: 3: Tech -

MySql Magic

As per SO,

SET @count = 0;
UPDATE `users` SET `users`.`id` = @count:= @count + 1;

If the column is used as a foreign key in other tables, make sure you use ON UPDATE CASCADE instead of the default ON UPDATE NO ACTION for the foreign key relationship in that table.

nhibernate hasmany to many

When doing a hasManyToMany relationship, SO makes a few observations

In a many-to-many relationship if collections on both entities aren’t populated, NHibernate doesn’t persist data to the link table.
Set Cascade.All()
Use Flush

So it looks like you dont need it on both sides, but you atleast need the cascade and the flush.
damn it looks like nhibernate isnt toilet trained! or its helping us to be

IViewer is back

A part of me since December 2000, IViewer is the application I literally learnt VB6 with.
In 2006, I stopped working in vb6 and also stopped working on it.

Then one day I rewrote the basic navigation, wmp control player in VB.net. In 2008 I refined the search as you type feature. Still convinced the UI is one of the best there is, I recently began reviving development and am pleased to announce that playlists have been included.

You can see pictures heresetup here, and someday maybe code here.

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;
}

prayers

Things that you would want to pray for appear as moving blurbs on the screen.

Configurable as a screen saver, this page will give you a chance to casually reflect on your prayers.

For the moment, its a static html page.

This will be expanded into a website where the words can be configured, the background colours and maybe the option to set background music.

It will also run on a few novel principles.

Data is stored in the form of cookies only. No need for a login.

For when your cookie is deleted / you switch machines, you will get an email each time you make a change which contains the link that has the data compressed.

php Img Optimizer

Sometimes we find that the images we have on the web are larger than we would like them.

It is helpful in this case to recursively scan a folder, pick out all files larger than our certain threshold and preview them (as thumbnails), resizing the ones we want to.

If the files are ridiculously large in the first place, we may want our preview to be of a resized thumbnail. Credit to Simon Jarvis for his component.

Some of the challenges are:

  • Scanning recursively and resizing images as we encounter them takes too long and the script times out.
  • Paging would solve this, but we cannot page items in a recursive scan. The thresholds may differ from page load to load.
  • Flagging files to skip.

xml serializer: known types with tidy namespace

The KnownType attribute in WCF is XmlInclude in Xml.
These let the serializer know that other types can be encountered which is not know by scanning the contract of the object being serialized. This normally happens when a contract is on a base type, but can hold derived types.

When your xml is visible to the user it matters how clean the text is. Using XmlInclude adds an attribute to let itself know the runtime type like so:
<Item d5p1:type=”Button”.

Now the definition of d5p1 is in the namespace xmlns:d5p1=”http://www.w3.org/2001/XMLSchema-instance”
If this namespace was not already in the root element, the generated xml would have this reference in every item such as:
<Item d5p1:type=”Button” xmlns:d5p1=”http://www.w3.org/2001/XMLSchema-instance” …

Adding this namespace explicitly to the XmlSerializer means that this xmlnd definition will now appear 100000 times in the document annoying the user who is reading it (or worse yet who has to edit it)

If you add code like so, the document magically becomes tidy.

var xml = new XmlSerializer(typeof(T), extraKnownTypes);
var ns = new XmlSerializerNamespaces();
ns.Add("d5p1", "http://www.w3.org/2001/XMLSchema-instance");
xml.Serialize(fileStream, obj, ns);

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 »

t4 templating

These include files (with samples) worry about reading files in the current project, reading direct sql / sprocs and files (tsv) and Grouping them by a given columnIndex

Tips

Host.ResolvePath("Data.txt")

Warnings

//Mention language (at top of file / include file)
<#@ template language="C#v3.5" debug="True" hostspecific="True" #>

//Add assemblies and import namespaces
<#@ assembly name="System.Core"#>
<#@ import namespace="System.Linq"#>

//Include files
<#@ include file="Project.ttinclude" #>

//Inside ttinclude files, Make sure to add a + inside
 the final code block (after includes, imports etc)
<#+
  //helper methods
#>