BAU Code

Random Notes on .NET technologies

Learn.C# Memory Leaks

http://www.codeproject.com/Articles/19490/Memory-Leak-Detection-in-NET

Old but still a good one in my opinion.

August 18, 2012 Posted by | Learn.Wpf | Leave a Comment

Learn.C# Any() vs Count()

Like most developers, I run a “is the collection null || is the collection empty” checks right before I iterate thru. So I write code like this


if(collection == null || collection.Count() == 0) return;

This changed as during one of our code review sessions, one of the guys suggested to use .Any() rather than Count(). In my head, that made sense as somehow I thought .Any() might be faster as it’s probably just doing a check on the first element (likely different in the case of passing a Func/Predicate argument)

So I figured to write simple code to compare .Any() vs .Count()

Here’s the code, nothing fancy


var stopwatch = new Stopwatch();
for(int counter = 0; counter < 5; counter++)
{
var listOfCustomer = new Customer[10000];
for (int index = 0; index < 10000; index++)
{
listOfCustomer[index] = new Customer { Age = 10, Id = "Agile", Name = "Agile" };
}


stopwatch.Start();
bool isEmpty = listOfCustomer.Count() == 0;
stopwatch.Stop();
Debug.WriteLine(string.Format("Using Count():{0}ms isEmpty:{1}", stopwatch.Elapsed,isEmpty));

listOfCustomer = new Customer[10000];
for (int index = 0; index < 10000; index++)
{
listOfCustomer[index] = new Customer { Age = 10, Id = "Agile", Name = "Agile" };
}

stopwatch.Start();
isEmpty = !listOfCustomer.Any();
stopwatch.Stop();
Debug.WriteLine(string.Format("Using Any():{0}ms isEmpty:{1}", stopwatch.Elapsed, isEmpty));
}

Using Count():00:00:00.0000280ms isEmpty:False
Using Any():00:00:00.0001755ms isEmpty:False

Using Count():00:00:00.0001828ms isEmpty:False
Using Any():00:00:00.0001997ms isEmpty:False

Using Count():00:00:00.0002061ms isEmpty:False
Using Any():00:00:00.0002080ms isEmpty:False

Using Count():00:00:00.0002159ms isEmpty:False
Using Any():00:00:00.0002175ms isEmpty:False

Using Count():00:00:00.0002220ms isEmpty:False
Using Any():00:00:00.0002229ms isEmpty:False

Interestingly enough, even Resharper is suggesting that I use .Any() on this line


bool isEmpty = listOfCustomer.Count() == 0;

So Count() is a wee bit faster than any, which goes against the suggestion. Perhaps I’m missing something or I ought to try it out using a Func/Predicate argument.

August 9, 2012 Posted by | Learn.Wpf | Leave a Comment

Misc. Less Diablo 3, more WPF

Yep Diablo 3 took over, workload wasn’t any better so I ended up working more and doing Diablo 3 at home to relax my head.

That’s all going to change now.

July 29, 2012 Posted by | Learn.Wpf | Leave a Comment

Learn.Everyday.Programming: Things I’d like to improve on

  1. My code isn’t backed up by unit test. I could have but I don’t have time, I thought I have enough time but I didn’t. I’ll charge it to bad estimates but it isn’t like everyone is unit testing their work and I’m the only one who doesn’t. We don’t have any unit test cases. I wrote a performance test that should have been part of a POC but…that’s another story
  2. My code isn’t pretty. Multiple classes in a single file. Multiple responsibilities/behavior in a single interface. “Readonly” properties getting set after object has been instantiated a.k.a. “Attach{Insert object}”
  3. My code isn’t guaranteed to work. Sadly, because of number one plus cowboy coding, I’m not sure if my code will work.
  4. My Saturdays and Sundays aren’t mine, it belongs to the company as I need to catchup with the work.
  5. Everything is high priority.
  6. Everything is simple when it isn’t really.

Not exactly related to technical coding but definitely a learning experience in Project Management.

  • Continue to be aggressive but always stay grounded and realistic.
  • Aggressive timelines seldom (read:never) translates to good code. Reasonable timelines do.
  • Stay on the safe side as user trust is something that doesn’t come easy but can vanish in a few clicks.
  • If some of your members are working on weekends, then there’s probably a problem with work distribution or promised timelines; usually both.
  • If everything is easy, then there probably smelly code or a lot of code debt. Chances are, it may ship quick but is a nightmare to maintain.
  • Test test test as you can never have too many test.
  • State facts and present numbers in proving a point.
  • Not all problems can be solved by using a hammer. If the hammer worked on the previous, there’s a possibility that it may or may not work for the next.
  • Frameworks merit generic solutions, domain specific merit tailor made solutions.

/Sad panda

May 30, 2012 Posted by | Learn.Everyday.Programming | Leave a Comment

Learn C#: My replacement for switch case statements on building properties that depend on other properties

Yes, so the subject isn’t exactly fancy but here’s what I’m trying to solve.

We have a huge object that has at the minimum 50 properties. Some of which are straightforward to populate while some are based on the values of others. Say, a number is positive if the direction is or the meaning of date is dependent of the type of object that is.

I figured we can always write this with the classic switch case or a series of if else statements but I figured to try this. The code exposes AddProperty which accepts the property name of what you’re trying to populate and a string or list of strings that refer to properties it depends on. It also exposes AddAction which refers to the actual Action that needs to be done to populate the property. It requires that it implements ILoadValueByPropertyName which is an arbitrary interface that has method called load that prepopulates the value of property based on the propertyname.

How do you use it?


public class Class1
{
public static void Main(string[] args)
{
var person = new Person();
var personDependentPropertyEngine = new PropertyRuleEngine<Person>(person);

personDependentPropertyEngine
.AddProperty("FirstName", "RawName")
.AddAction("FirstName", (t) => t.FirstName = t.RawName);
personDependentPropertyEngine
.AddProperty("FullName", new List<string> { "FirstName", "LastName" })
.AddAction("FullName", (t) => t.FullName = String.Format("Good Morning, Mr {0} {1}", t.FirstName, t.LastName));
personDependentPropertyEngine
.AddProperty("FullNameLength", "FullName")
.AddAction("FullNameLength", (t) => t.FullNameLength = t.FullName.Length);

personDependentPropertyEngine.Eval();

Console.WriteLine(person.FullName);
Console.WriteLine(person.FullNameLength);
Console.Read();
}
}

public interface ILoadValueByPropertyName
{
void LoadValue(string propertyName);
}


using System;
using System.Collections.Generic;
using System.Linq;

namespace CompositePropertyEngine
{
public class PropertyRuleEngine<T> where T: ILoadValueByPropertyName
{

private readonly Dictionary<string, List<string>> _propertyToDependentPropertyNames = new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, Action<T>> _propertyToAction = new Dictionary<string,Action<T>>();
private readonly T _model;

public PropertyRuleEngine(T model)
{
_model = model;
}

public PropertyRuleEngine<T> AddProperty(string propertyName, List<string> dependentPropertyNames)
{
List<string> mappedDependentProperties;
if(!_propertyToDependentPropertyNames.TryGetValue(propertyName,out mappedDependentProperties))
{
mappedDependentProperties = new List<string>();
_propertyToDependentPropertyNames.Add(propertyName, mappedDependentProperties);
}

if (_propertyToDependentPropertyNames.Values.Any(mappedDependentProperty => mappedDependentProperty.Contains(propertyName)))
{
throw new ArgumentException("Regitering a Dependent Property that depends on a Dependent Property requires that you register the latter first!");
}

dependentPropertyNames.ForEach(mappedDependentProperties.Add);
return this;
}

public PropertyRuleEngine<T> AddProperty(string propertyName, string dependentPropertyName)
{
return AddProperty(propertyName, new List<string>{dependentPropertyName});
}

public PropertyRuleEngine<T> AddAction(string propertyName, Action<T> action,bool overwrite = true)
{
Action<T> existing;
if(!_propertyToAction.TryGetValue(propertyName,out existing))
{
_propertyToAction.Add(propertyName,action);
return this;
}

_propertyToAction[propertyName] += action;
return this;
}

public void Eval()
{
foreach (var key in _propertyToDependentPropertyNames.Keys)
{
_propertyToDependentPropertyNames[key].ForEach(_model.LoadValue);
}
foreach (var key in _propertyToAction.Keys)
{
_propertyToAction[key](_model);
}
}
}
}

May 13, 2012 Posted by | Learn.Wpf | Leave a Comment

Learn.C# Learning LINQ

LINQ is starting to creep in my code and I like it! Thanks to Resharper’s squiggly green line telling me to use a LINQ expression instead.

Some of the more common things I do.

1. I need a new collection out of an existing collection and it happens that the collection I want is a property of the individual items on the existing collection


var newCollection = oldCollection.Select(x => x.Property);

2. I need to count the contents based on a certain criteria. Now most of the examples I saw used a combination of Where Then Count, but I just use Count passing Predicate. Not too sure of the difference though.


int validItemCount = oldCollection.Count(x => x.IsValid);

//or

int validItemCount = oldCollection.Where(x => x.IsValid).Count();

3. I need to check if everything falls on the same criteria


bool areAllItemsValid = oldCollection.All(x => x.IsValid);

4. I need some dictionary of some sorts


var dictionary = oldCollection.ToDictionary(x => x.Category);

Still learning the ropes, hopefully next time I can shuffle cards using a single line of LINQ.

May 5, 2012 Posted by | Learn.C# | Leave a Comment

Learn.C# Xml consumption, Memory usage and Design

So we’ve dived into the wonderful world of rich controls backed up by heavy data (100+ string, double, string, enum columns) What do we get? Slow and heavy representation of supposedly dynamic data.

At the moment we chose to back up our XamGrid with an object referencing a dictionary of string vs string xpath lookups, numerous CLR properties and an XmlContainer. On top of that, there’s the extra conversion algorithm that converts information we get out of the XmlContainer into appropriate data types (is it a string? no, is it a datetime? no, is it a double? yes, convert and return…something like that) So if I need to render “PropertyA”, I end up going to the dictionary of string key vs Xpaths, I then use the XPath to query the backing store and then convert it to the appropriate data type. Of course there are optimizations on where we skip this part and do this only on the first time we retrieve the data but that introduces another backing store to capture which keys have I processed already. Overall, a single row is really heavy on memory with some overhead in getting data. The backing store of the XmlContainer is again, you guessed it, a dictionary of strings vs dynamics. Not much experience with performance on dynamics but it strikes me as the dynamics part is really getting used as a glorified “object” as we still end up casting it back to some for or another.

So what does a row look like in memory, I’d say roughly like

XmlContainer + dynamic object overhead + dictionary of xpaths vs dynamic objects + TradeObject + dictionary of strings vs boolean if the propertyname has already been resolved or not + an array of PropertyInfo + 100 CLR property objects mostly of which are strings + Enumerable LegObject (mostly 1-3) that you can think of as another TradeObject + XmlContainer

Hopefully we can still turn around and fix this. I’d go about doing this the old school way. XmlReader for Xml to create a flat tradeobject. Control on column visibility is left to the GridControl and not to PropertyDescriptors on the Collection Datasource.

The design in paper or as individual solutions is good though. I absolutely loved the idea of a fluent xml parser and the selective binding based on property visibility. I just don’t think it’s scalable enough for the data that we’re dealing with.

May 5, 2012 Posted by | Learn.C# | Leave a Comment

Learn.Wpf: Binding Commands to Events

Let’s say that you have a WPF Usercontrol that has a Grid Control and you want to Bind a Command to the MouseDoubleClick Event of the Grid.

I came acrosss two general ways of solving this

1. Attached Properties using this or earlier incarnations of this approach

2. Declaring an ICommand Depedency Property on the Control, wire up a handler to the actual Event on the code behind and then call the ICommand CanExecute/Execute. Something like this.


// Dependency Property Declaration elide

// this is code written in wordpress and not in VS

private void OnMouseDoubleClick(object sender, EventArgs e)

{

if(MouseDoubleClickCommand!=null && MouseDoubleClickCommand.CanExecute(e.args))
MouseDoubleClickCommand.Execute(e.args);
}

Not as flexible compared to the first approach as it requires a UserControl wrapper and lacks reusability. Use whenever appropriate.

April 13, 2012 Posted by | Learn.Wpf | Leave a Comment

Learn.WPF: Infragistics XamDataGrid Load and Save Customization

I’m fairly certain that there’s a ton of examples out there about this topic but let me just say, this really saved me a lot of donkey coding. Well, maybe one can argue that we can definitely write code to mimic, if not surpass, the functionality of loading/saving XamDataGrid settings. For my purposes though, it gets the job done nicely.

Save Custom Filters, Column visibility, Column Sequence


var profileString = grid.SaveCustomization();

Refer to this example on how to directly push it to a stream.

We had to use the returned string in the SaveCustomization call as we needed to combine that xml with other things.

Now please do take this with a grain of salt sa I also came across of a blog that says the method calls don’t really work. Maybe a version difference? Here’s the link.

April 10, 2012 Posted by | Learn.Wpf | Leave a Comment

Learn.Everyday.Programming: Ten Commandments of Egoless Programming.

http://blog.stephenwyattbush.com/2012/04/07/dad-and-the-ten-commandments-of-egoless-programming/

Must read!!!

April 10, 2012 Posted by | Learn.Everyday.Programming | Leave a Comment

Follow

Get every new post delivered to your Inbox.