XYZCONSULTING

4/7/2010

Sorting a .Net List with Lambdas

I love linq.  I would wager that most developers who have done much with it share a similar love.

It makes our lives easier.  It eliminates writing copies amounts of loops, parsing xml, interacting with databases, you name it.  It’s great.

 

When I run into a situation where linq does not have an obvious tie in, I start to get a little anxious,  (pathetic I realize).

 

Today I was faced with a situation where I had a list of custom classes that I needed to sort. 

This being a list, OrderBy was nowhere to be found.

 

So, I returned to my roots and started writing a compare for my class so that I could use the Sort command that is part of the List generic type.  That is when it struck me that I could probably accomplish this using a lambda.  It turns out that I was correct.  Lambda’s were a perfect fit for this scenario.  The code remained clean and concise and I was saved having to write additional methods just to accomplish a one-off scenario on what was a otherwise complete project.

 

Lamdas are a progression in C# past anonymous methods.  In the code below, I show how the code would be implemented with separate function, an anonymous method and finally, with a Lambda expression.

 

First, the test class that we’ll be working with:

public class MyClass
{
    public int propA { get; set; }
    public int propB { get; set; }
    public int propC { get; set; }
}

Our test class:

public class Tester
{
    public void Main()
    {
        List list = new List();
        list.Add(new MyClass() { propA = 1, propB = 2, propC = 3 });
        list.Add(new MyClass() { propA = 2, propB = 3, propC = 4 });
        list.Add(new MyClass() { propA = 3, propB = 4, propC = 5 });
        list.Add(new MyClass() { propA = 4, propB = 5, propC = 6 });        
    }
}

Now then, we write a custom comparer.  Not a lot of code, but you can imagine how this extrapolates over various properties for large classes.

public class Tester
{
    private static int CompareByPropA(MyClass a, MyClass b)
    {
        return a.propA.CompareTo(b.propA);
    }
    public void Main()
    {
        List list = new List();
        list.Add(new MyClass() { propA = 1, propB = 2, propC = 3 });
        list.Add(new MyClass() { propA = 2, propB = 3, propC = 4 });
        list.Add(new MyClass() { propA = 3, propB = 4, propC = 5 });
        list.Add(new MyClass() { propA = 4, propB = 5, propC = 6 });

        //Using the comparer built into the MyClass method
        list.Sort(CompareByPropA);        
    }
}

This time, we drop the custom comparer and implement the sort using an anonymous method.

public class Tester
{
    public void Main()
    {
        List list = new List();
        list.Add(new MyClass() { propA = 1, propB = 2, propC = 3 });
        list.Add(new MyClass() { propA = 2, propB = 3, propC = 4 });
        list.Add(new MyClass() { propA = 3, propB = 4, propC = 5 });
        list.Add(new MyClass() { propA = 4, propB = 5, propC = 6 });

        //Using an anonymous method
        list.Sort(delegate(MyClass a, MyClass b) { return a.propA.CompareTo(b.propA); });
    }
}

Finally, we rewrite the anonymous method into a Lambda.  It is still easy to read and much more concise.

public class Tester
{
    public void Main()
    {
        List list = new List();
        list.Add(new MyClass() { propA = 1, propB = 2, propC = 3 });
        list.Add(new MyClass() { propA = 2, propB = 3, propC = 4 });
        list.Add(new MyClass() { propA = 3, propB = 4, propC = 5 });
        list.Add(new MyClass() { propA = 4, propB = 5, propC = 6 });

        //Using a Lambda
        list.Sort((a, b) => a.propA.CompareTo(b.propA));
    }
}

So, next time you go to write custom compare code, step back and see if you can do it a little more simply.  If you are going to be using your comparison code in more than one place, then perhaps it is still a better idea to implement it using that route vs the lambda.  If it is a one-off thing, then a lambda and some linq can be a beautiful thing!

3/21/2010

Review of Flex 4 In Action

As someone who has relatively little experience with Flex, I found this book to be a great asset in furthering my understanding of how and why things work the way they do not only in MXML, but also on the ActionScript side.

 

The tone of the book is very friendly.  As a general rule, I did not find myself bogged down in technical terminology.  A good balance was struck between keeping things simple for the average reader, yet still technical enough to hold the attention of somebody with more in depth knowledge of previous versions of Flex.

 

The book also starts out with a nice section on the benefits of Flex and RIA's in general along with a few pointers on how to sell upper management on its use.  From there they move on to cover the basics of ActionScript and Flex and show how MXML layout works, how MXML and AS work with one another, some basics on how to work with data inside of your application and also detail the differences between the old Halo controls and the new Spark controls.

 

The second section of the book delves into more complex topics like the event model, view states, writing custom components and more.  There is a small jump in the assumed capabilities of the reading audience at this point.  Readers who are new to Flex and who have worked through the first part of the book should still be able to follow along at this point.

The only negative that struck me as I was reading the book was the code samples.  While they do an excellent job of demonstrating the topic that they are associated with, I would have preferred if by the time I reached the end of the book I had a fully working reference application vs a series of smaller individual apps.

 

Overall, I enjoyed reading the book and learned quite a lot, not only about Flex 4, but Flex as a whole.  The authors did a good job of keeping the subject matter entertaining and making their various contributions flow seamlessly together.

 

I would recommend this book both to people who are staring out in Flex development as well as people who are already familiar with Flex and looking to find out what is new in Flex 4.

 

You can pre-order your copy on Amazon

3/17/2010

OData = Hotness

Microsoft has officially announced OData.  If you are not aware of what this is, then in a sentence: OData is a queryable REST based interface that exposes your data via AtomPub.

 

To publish a feed, you have to use .Net.  However, they have provided client sdk’s for a variety of languages to allow for simple querying of the exposed services and they are working on several more.

 

I strongly encourage you to check it out.

 

Partly to give an idea of what is possible, and partly for my own reference, I am going to repost a “cheat sheet” that I found online at Meta-Me

 

 

The Service:

It all starts with a Data Service hosted somewhere:

http://server/service.svc

 

Basic queries:

You access the Data Service entities through resource sets, like this:

http://server/service.svc/People

You request a specific entity using its key like this:

http://server/service.svc/People(16)

Or by using a reference relationship to something else you know:

http://server/service.svc/People(16)/Mother

This asks for person 16’s mother.

Once you have identified an entity you can refer to it’s properties directly:

http://server/service.svc/People(16)/Mother/Firstname

 

$value:

But the last query wraps the property value in XML, if you want just the raw property value you append $value to the url like this:

http://server/service.svc/People(16)/Mother/Firstname/$value

 

$filter:

You can filter resource sets using $filter:

http://server/service.svc/People?$filter=Firstname  eq ‘Fred’

Notice that strings in the filter are single quoted.

Numbers need no quotes though:

http://server/service.svc/Posts?$filter=AuthorId eq 1

To filter by date you have identity the date in the filter, like this:

http://server/service.svc/Posts?$filter=CreatedDate eq DateTime'2009-10-31'

You can filter via reference relationships:

http://server/service.svc/People?$filter=Mother/Firstname eq 'Wendy'

The basic operators you can use in a filter are:

Operator

Description

C# equivalent

eq

equals

==

ne

not equal

!=

gt

greater than

>

ge

greater than or equal

>=

lt

less than

<

le

less than or equal

<=

and

and

&&

or

or

||

()

grouping

()

There are also a series of functions that you can use in your filters if needed.

 

$expand:

If you want to include related items in the results you use $expand like this:

http://server/service.svc/Blogs?$expand=Posts

This returns the matching Blogs and each Blog’s posts.

 

$select:

Some Data Services allow you to limit the results to just the properties you require – aka projection – for example if you just want the Id and Title of matching Posts you would need something like this:

http://server/service.svc/Posts?$select=Id,Title

You can even project properties of related objects too, like this:

http://server/service.svc/Posts?$expand=Blog&$select=Id,Title,Blog/Name

This projects just the Id, Title and the Name of the Blog for each Post.

 

$count:

If you just want to know how many records would be returned, without retrieving them you need $count:

http://server/service.svc/Blogs/$count

Notice that $count becomes one of the segments of the URL – it is not part of the query string – so if you want to combine it with another operation like $filter you have to specify $count first, like this:

http://server/service.svc/Posts/$count?$filter=AuthorId eq 6

This query returns the number of posts authored by person 6.

 

$orderby:

If you need your results ordered you can use $orderby:

http://server/service.svc/Blogs?$orderby=Name

Which returns the results in ascending order, to do descending order you need:

http://server/service.svc/Blogs?$orderby=Name%20desc

To filter by first by one property and then by another you need:

http://server/service.svc/People?$orderby=Surname,Firstname

Which you can combine with desc if necessary.

 

$top:

If you want just the first 10 items you use $top like this:

http://server/service.svc/People?$top=10

 

$skip:

If you are only interested in certain page of date, you need $top and $skip together:

http://server/service.svc/People?$top=10&$skip=20

This tells the Data Service to skip the first 20 matches and return the next 10. Useful if you need to display the 3rd page of results when there are 10 items per page.

Note: It is often a good idea to combine $top & $skip with $orderby too, to guarantee the order results are retrieved from the underlying data source is consistent.

 

$inlinecount & $skiptoken:

Using $top and $skip allows the client to control paging.

But the server also needs a way to control paging – to minimize workload need to service both naive and malicious clients – the OData protocol supports this via Server Driven Paging.

With Server Driven Paging turned on the client might ask for every record, but they will only be given one page of results.

This as you can imagine can make life a little tricky for client application developers.

If the client needs to know how many results there really are, they can append the $inlinecount option to the query, like this:

http://server/service.svc/People?$inlinecount=allpages

The results will include a total count ‘inline’, and a url generated by the server to get the next page of results.

This generated url includes a $skiptoken, that is the equivalent of a cursor or bookmark, that instructs the server where to resume:

http://server/service.svc/People?$skiptoken=4

 

$links

Sometime you just need to get the urls for entities related to a particular entity, which is where $links comes in:

http://server/service.svc/Blogs(1)/$links/Posts

This tells the Data Service to return links – aka urls – for all the Posts related to Blog 1.

 

$metadata

If you need to know what model an OData compliant Data Service exposes, you can do this by going to the root of the service and appending $metadata like this:

http://server/service.svc/$metadata

This should return an EDMX file containing the conceptual model (aka EDM) exposed by the Data Service.

2/26/2010

ColdFusion Troubles

I have been running awry of ColdFusion.

 

I am running Windows XP (not by choice), and *had* a local installation of ColdFusion 8 Server.  The instance of ColdFusion was stopped since it is a bit of a memory hog and I was not actively using it.  I have been working on getting an instance of Telligent Community Server up and running for evaluation purposes.  I was baffled by the fact that the Telligent demo was taking around 10 minutes on average to load a page from the local system. 

 

Needless to say, since everything else seemed to be running fine, I was blaming Telligent’s software.  Then I started exploring a little more and figure out that IIS was taking around 30 seconds just to serve up an image.  Something was definitely up, but despite all of my best troubleshooting skills, I could not source the problem.

 

I did what I always do when something goes wrong that I don’t understand, I turned to Google.

 

I tried about 20 different “solutions” until I stumbled across a forum post saying to start ColdFusion if it was installed.  *poof*. The page that took 10 minutes to load before now takes 5 seconds.  It turns out that the CF ISAPI plugin is constantly trying to talk to the server.  If it can’t find the server, it doesn’t just die, it keeps trying. … on every. single. request.

 

strike one.

 

A short while later, I was working on trying to speed up a dashboard application that  coworker and I had written.  It is pretty simple. CF queries the database and retrieves somewhere in the range of 10-700 rows of data, turns them into objects, passes those objects off to Flex which then graphs the objects.  It was performing fine as long as there was less than 40 rows. By the time you got up to a few hundred rows of data, it would take an obscene amount of time to load.

 

We scratched our heads for the longest time and were pretty convinced that the Flex chart control was to blame.

 

Then we had an idea.  Instead of letting CF instantiate each row into an object, just send CF the results as an XML document from the database, let CF hand the XML off to Flex, and then proceed from there.

 

Same story. 10 minutes now became 2 seconds.

 

It seems that ColdFusion doesn’t do so well at creating objects.

 

strike two.

 

I’m not very pleased with ColdFusion at the moment.

3/27/2009

Response.Redirect inside of a Try/Catch

Ok, first off, let me state, that I am not entirely certain WHY I did this in the first place.  I am going to say I was rushed and wasn’t thinking clearly.  However, I glazed over it and moved on and when it came time to test, I was getting bizarre behavior that didn’t throw an error.

Session[“var”] = “”; 

try 
{ 
    Session[“var”] = “Good Value”;

    Response.Redirect(“newpage.html”); 
} 
catch(Exception ex) 
{ 
    Session[“var”] = “Bad Value”; 
}

In the code above, Session[“var”] will ALWAYS equal “Bad Value”.  Why you may ask?

Response.Redirect throws a ThreadAbortException.  … Fun, no?

If you are building a URL inside of a try block that you want to then redirect to, declare a string, build your url, and then pass that on to the Response.Redirect statement. 

For Example:

string _url;

try 
{ 
    _url = “yourpage.aspx?var=” + iffyMethodCall(); 
} 
catch(InvalidOperationException ex) 
{ 
    _url = “error.html”; 
}

Response.Redirect(url);

So, If you ever run into odd behavior in a site you are working on and when debugging, your code goes straight past your Response.Redirect and into the catch block and the debugger starts giving you cryptic messages, this may be what you’re seeing.

12/7/2008

IIS Worker Process Fail 503 Error

Helping a friend to configure his new Win2k8 Server with IIS7 this weekend we ran into an issue where IIS kept returning 503 errors.

Examining the Application Event log I saw that  IISW3SVC-WP was quitting due to application errors. "The error is the data".  How helpful.

After a considerable amount of digging I discovered that in the Microsoft.Net/Framework/ folder, there was a beta version of v2 of the framework.  The only version that *should* be there is v2.0.50727. 

I deleted the beta version of the framework and restarted the IIS worker processes that were causing problems and everything immediately burst to life!

I've no clue what installed the beta version of the framework, but it is a definite lesson to make sure that when distributing a framework to be 100% certain that you are always including the latest "release" version... oh yeah, and perhaps doing a check for an existing version of said framework before installing.

At any rate, hope this helps somebody.

12/4/2008

Useless entry #268

While in a chat today, the following conversation occurred...

After I stopped laughing I had to post it.

A : I had a mouse in my well the other day. I shop-vac-d it out.
B : lol, I can hear it now... "whrrrrrrrrr, ssshhTHUNK"
C : *phoomp*
D : and forever after the other mice tell tales of abduction from above
D : "seriously, it was like some kind of tractor beam!"
B : But is derided as a crazy mouse.


9/8/2008

Whedon Quote

I am not sure how many of you are Whedon fans like myself.  I came across this today and I'm posting it in part because it is, in my opinion, phenomenal, and also so that I have an easy place to look it up in the future.

Passion, it lies in all of us, sleeping... waiting... and though unwanted... unbidden... it will stir... open its jaws and howl. It speaks to us... guides us... passion rules us all, and we obey. What other choice do we have? Passion is the source of our finest moments. The joy of love... the clarity of hatred... and the ecstasy of grief. It hurts sometimes more than we can bear. If we could live without passion maybe we'd know some kind of peace... but we would be hollow... Empty rooms shuttered and dank. Without passion we'd be truly dead.

-- Joss Whedon

8/25/2008

Why I am a Republican - Kinda

I normally abhore forwards.  However, I recently received one that I thought was magnificent.

....................................................................................

FATHER AND DAUGHTER

A young woman was about to finish her first year of college. Like so many others her age, she considered herself to be a very liberal Democrat, and among other liberal ideals, was very much in favor of higher taxes to support more government programs, in other words redistribution of wealth.

She was deeply ashamed that her father was a rather staunch Republican, a feeling she openly expressed. Based on the lectures that she had participated in, and the occasional chat with a professor, she felt that her father had for years harbored an evil, selfish desire to keep what he thought should be his.

One day she was challenging her father on his opposition to higher taxes on the rich and the need for more government programs. The self- professed objectivity proclaimed by her professors had to be the truth and she indicated so to her father. He responded by asking how she was doing in school.

Taken aback, she answered rather haughtily that she had a 4.0 GPA, and let him know that it was tough to maintain, insisting that she was taking a very difficult course load and was constantly studying, which left her no time to go out and party like other people she knew. She didn't even have time for a boyfriend, and didn't really have many college friends  because she spent all her time studying.

Her father listened and then asked, 'How is your friend Audrey doing?' She replied, 'Audrey is barely getting by. All she takes are easy classes, she never studies, and she barely has a 2.0 GPA. She is so popular on campus; college for her is a blast. She's always invited to all the parties and lots of times she doesn't even show up for classes because she's too hung over.'

Her wise father asked his daughter,

'Why don't you go to the Dean's office and ask him to deduct 1.0 off your GPA and give it to your friend who only has a 2.0. That way you  will both have a 3.0 GPA and certainly that would be a fair and equal distribution of GPA.'

The daughter, visibly shocked by her father's suggestion, angrily fired back, 'That's a crazy idea, how would that be fair! I've worked really hard for my grades! I've invested a lot of time, and a lot of hard work! Audrey has done next to nothing toward her degree. She played while I worked my tail off!'

The father slowly smiled, winked and said gently, 'Welcome to the Republican party.'

....................................................................................

If anyone has a better explanation of the difference between Republican and Democrat I'm all ears.

*UPDATE*

Ok. So, after a day of politically inspired tweets & conversations with friends, I don't think that I am really a republican per se.  I am conservative no doubt, but I honestly don't think I am as staunch as some of the card carying republicans out there like my father.

I recieved the following from a good friend (who was apparently unable to post a comment to my blog... I need to investigate that)

...........................................


The largest logical problem with that post, and coincidentally one of the most fundamental problems both parties have with complicated issues like welfare, is that it breaks down such a complicated issue into a simple moral dilemma.  Welfare isn't about morality, though its implementation may be immoral.  Whether a child has enough to eat isn't the same as whether you get a good grade in school.  In fact, to suggest such is quite insulting, though I'm sure that wasn't the intent by the OP.  Welfare, fundamentally, is disaster insurance.  You pay into a group fund when you can, and when you need it, the fund is available to you.
 
A far more appropriate comparison would be the following discussion between the same father and daughter.  We pick up the story where she's talking about her friend.  She's the same party girl as before, but this time, instead of the discussion pointing out that her grades were low due to her lifestyle choice, she had instead been assaulted at such a party.  When asked by her father how she handled herself at parties, she responds that she would never go to such places and if she did she'd mace a guy trying anything like that.  When asked if she'd give up her mace to her friend, she replies in the same way as before: why would I suffer because I am prepared, she deserved it since she didn't prepare, etc.  Of course, her father replies, "Welcome to the Republican Party".
 
The point is that both parties indicate that you don't know how to run your life.  Democrats want to provide for those who can't provide for themselves.  Republicans want to act as examples for those who have fallen.
 
I have a different view, and, yes, I'm a libertarian.  There should be no welfare, nor any judgement - at least not by the state.  When a wealthy democrat was told the libertarian ideal, he replied, "Who will care for the homeless."  "You will," came the response.  "You mean, people with money will get together and..." he was cut off.  "No, YOU will."  There is no welfare in a libertarian state, just concerned citizens.
 
This country has never been libertarian, and likely never will be.  We're far too full of ourselves to accept responsibility without structure or recognition.

...........................................

A good point that is going to lead me off on a tangent.  I believe that as a general rule, people should not be given hand-outs.  However, if you are making an effort to get ahead in the world and are simply not able to do it, no matter how hard you are trying, then I will give you my assistance.  I am not heartless, but I do think that people who make no effort whatsoever to better their situation and similarly do nothing but sit and complain about it, are not deserving of my sympathy.  Personal accountability is becoming more and more infrequent in today's world.  There is a definite sense of entitlement.  News flash people. Nobody OWES you anything.  If you want something, go out there and bust your butt.  99 times out of 100, if you try hard enough, you are going to succeed.  On some level, life is fair.  The people who say that life isn't fair simply stopped trying and let their gaurd down.   There is a saying, "you get out of life what you put into it".  If you keep a positive attitude and give every day your best, then you are going to live a happy and successful life.  Just don't blame anyone else for your choices.

I realize that this post started off one way and has devolved into something COMPLETELY different.  This is my blog though.  If you do not like my chain of conciousness, then go read somebody elses blog.

8/2/2008

Vista…My Take

Alright.  It's time to weigh in. 

I have been using Vista for quite a while now, and while it does have its shortcomings, it is a dramatic improvment over XP.

I've listened to a lot of the reasons that Vista = FAIL, but I think a lot of them boil down to the requirements that the OS takes to run properly.  Let's face it, as computers have gotten faster and RAM more abundant, EVERY operating system out there has gone out of its way to take advantage of the extra resources.  Some more than others, but they've all adapted.

So, let's examine some of these requirements for "Windows" past.

Released Processor Speed RAM (MB) HDD (MB)
Windows 95 Aug-95 20 Mhz 4 MB 50 MB
Windows 98 Jun-98 66 Mhz 16 MB 210 MB
Windows 2000 Feb-00 133 Mhz 32 MB 700 MB
Windows XP Oct-01 233 Mhz 64 MB 1.5 GB
Windows Vista Januery 2007 800 Mhz 512 MB 15 GB

If we were to graph this, we would see that with the exception of storage, the requirements have risen at a fairly constant rate over the years.

Requirements.JPG

The most important thing that I see here is that big gap between 2001 and 2007.  From my perspective, what has occured is that there are a considerable amount of computers out there dating back to the turn of the millenium that were more than capable of running XP and still are, but are simply not powerful enough to meet Vista's minimum requirements.  This is also a large reason that business and corporations are not jumping on the upgrade.  It would mean purchasing a whole stock of new computers.

That large gap was Microsoft's biggest mistake.  By sticking to a more frequent release schedule they not only minimize the gossip of issues, but also minimize the whollop of new system requirements.

The other major reason that a lot of people are griping about Vista is program compatibility.  A lot of programs simply will not run on Vista.  Especially if you are running 64-bit.  While Microsoft has gone out of its way to ensure backward compatibility, they should not be responsible for making a program that was written in 1995 work on a modern OS, that is the job of the software manufacturer/developer.   I would also stipulate that if you are a company using a program that old, and the manufacturer has not released an update to allow it to run on today's more modern systems, then you should seriously investigate newer options.  Other OS's don't even bother with backwards compatibility, leaving it entirely the problem of hte developer to release an update...those of you using an Apple product will know what I'm talking about.

Regardless, it has been a year and a half now, SP1 has been released and there are very few remaining glitches.  If you haven't tried Vista yet, give it a try... an honest try.  If after a few weeks, you are still dissatisfied and agree with the naysayers, then by all means, downgrade to XP and continue griping.