rulururu

post Short precious code snippet

August 12th, 2009

Filed under: .NET — Kai @ 12:45 am

I was recently talking about linq features with a friend. Now I saw somebody wanted to break a loop after 50 iterations. Trivial but also for that there’s a precious solution using linq.

int processed = 0;
foreach(ListViewItem lvi in listView.Items)
{
   //do stuff
   ++processed;
   if (processed == 50) break;
}

use linq

foreach(ListViewItem lvi in listView.Items.Take(50))
{
    //do stuff
}

or, you’re right “old” style would be

for(int i=0; i < listView.Items.Count && i <= 50; i++)
{
   ListViewItem lvi = listView.Items[i];
  //do stuff
}

post LINQ to Amazon

July 1st, 2009

Filed under: .NET — Kai @ 3:55 pm

As you know you can query with LINQ lots of different sourcse. It’s possible to query, project and filter data in arrays, enumerable classes, XML (XLINQ), relational database, and third party data sources. Last year I among others wrote something about LINQ & XML.

After doing some query we get results of a as a collection of in-memory objects that can be enumerated using a standard iterator function such as C#’s foreach.

I found a funny Provider called Linq to Amazon which allows querying Amazon for books using Linq! It uses Linq’s extensibility to allow for language-integrated queries against a book catalog. The Linq query gets converted to REST URLs supported by Amazon’s web services. These services return XML. The results are converted from XML to .NET objects using Linq to XML.

For the moment, let’s look at the client code:

var query =
  from book in new Amazon.BookSearch()
  where
    book.Title.Contains("darkness and light") &&
    (book.Publisher == "Hitchcock") &&
    (book.Price <= 25) &&
    (book.Condition == BookCondition.New)
  select book;

I think this code speaks for itself! This is Linq to Amazon code. It expresses a query against Amazon, but does not execute it… The query will be executed when we start enumerating the results.

The following piece of code converts from Linq to Amazon to Linq to Objects:

var sequence = query.ToSequence();

The var might remind you to the times of Flash, VB or JavaScript. But those times were baaad, very bad. Nowadays we’re strongly typed or even better generic:

A good alternative is:

IEnumerable<SomeOtherClass> results = ...

The returned catalogue can now be grouped, filtered more detailed or just thrown away. Do whatever you like todo ;-)

There are many more, more or less usefull ones:

  • LINQ to SharePoint
  • LINQ to Amazon
  • LINQ to Active Directory (LDAP)
  • LINQ to NHibernate
  • LINQ to MySQL / Oracle / SQLite
  • LINQ to Flickr

Have fun ;)

post Love or Hate Extension Methods?

July 14th, 2008

Filed under: .NET — Kai @ 12:39 pm

In C#, there is no String.Left() function. Fair enough; we can roll up our sleeves and write our own function lickety-split:

public static string Left(string s, int len)
{
    if (len == 0 || s.Length == 0)
        return "";
    else if (s.Length <= len)
        return s;
    else
        return s.Substring(0, len);
}

And call it like so:

var s = "superlongstring";
s = Left(s, 5);

But with the advent of C# 3.0, there’s an even better way — extension methods. With an extension method, we “extend” the String to add the missing function. The code is fairly similar:

public static string Left(this string s, int len)
{
    if (len == 0 || s.Length == 0)
        return "";
    else if (s.Length <= len)
        return s;
    else
        return s.Substring(0, len);
}

And now we can call it as if this very method existed on the String class as shipped:

var s = "superlongstring";
s = s.Left(5);

Pretty slick. It’s difficult not to fall in love with extension methods, as they allow you to mold classes into exactly what you think they should be. This is fairly innocuous in C#, as extension methods only allow you to add new functionality to classes, not override, remove, or replace anything.

post Shorten a Path

June 25th, 2008

Filed under: .NET — Kai @ 7:36 pm

Sometimes you need a long path to be short because the field that displays the text doesn’t have enought space for the whole path.

This in .NET written function does cut “C:\Windows\System32\Test\Test.dll” to “C:\Windows\…\Test.dll”.

First parameter is the path that has to be shorten.
Second parameter is the maximum length of the new string.
Third parameter is the Font that is used.
Return value is the new storten string.

public string PathShorten(string Path, int Length, Font TextFont)
{
    string[] PathParts = Path.Split('\\');
    StringBuilder PathBuild = new StringBuilder(Path.Length);
    string LastPart = PathParts[PathParts.Length - 1];
    string PrevPath = "";
 
    //check if path is already shorter than max. length
    if (TextRenderer.MeasureText(Path, TextFont).Width < Length)
        return Path;
 
    for (int i = 0; i < PathParts.Length - 1; i++)
    {
        PathBuild.Append(PathParts[i] + @"\");
        if (TextRenderer.MeasureText(PathBuild.ToString() + @"...\" 
              + LastPart, TextFont).Width >= Length)
            return PrevPath;
        else
            PrevPath = PathBuild.ToString() + @"...\" + LastPart;
    }
    return PrevPath;
}

Just a simple snipped but I guess that it can often be valuable. I hope it can be used widely.

post Avoid making useless new object

June 4th, 2008

Filed under: .NET, C++ — Kai @ 3:16 pm

You often see statements like the one here when programmers want to check if a string has value or not.

if(strName!="")
{ ... }

For C++ programmers (who uses CString for example) this is correct and not really unusual - but please if you’re writing code in C# or another .NET language keep in mind that this causes the allocation of a new String object just for the reason to compare it with an empty string.

Correct implementations would be:

if(strName.Length <= 0)
{ ... }
 
if(strName.Length == 0)
{ ... }

You will not regognize this in a performance test or when using the application but it’s just good form to do it right - also because you know why you should do.

When working with CStrings it’s dispensable faster or slower to compare with an empty string or just to compare the length. If you have a look at the IsEmpty() member function of CString Class you’ll mention that I’m right:

bool IsEmpty() const throw()
{
     return( GetLength() == 0 );
}

post Question of Recursion

May 22nd, 2008

Filed under: .NET, C++, General Programming — Kai @ 2:53 pm

Algorithms can often be implemented recursively or nonrecursively; the decision rests with the programmer, who might shy away from a recursive solution because the algorithm might not terminate or that performance might be poor. In reality, recursion can allow for very elegant code as well as facilitating an interesting and economical type of code reuse.

Iterative algorithms, especially those with a loop, can usually be easily rewritten to use recursive function calls instead of loops. In some cases it’s a bad idea because the iterative version is usually simpler, faster, and uses less memory.

The classical scenario for recursion was search algorithms, factorial calculations, and so on. A well-know algorithmn that uses recursion is Binary Search.

This recursive version checks to see if we’re at the key (in which case it can return), otherwise it calls itself so solve a smaller problem, ie, either the upper or lower half of the array.

int BinarySearch(int iSortedArray[], int iFirst, int iLast, int iKey) 
{
   if (iFirst <= iLast) {
       int iMid = (iFirst + iLast) / 2;  
       if (iKey == iSortedArray[iMid]) 
           return iMid;  
       else if (iKey < iSortedArray[iMid]) 
           return BinarySearch(iSortedArray, iFirst, iMid-1, iKey);
       else
           return BinarySearch(iSortedArray, iMid+1, iLast, iKey);
   }
   return -(iFirst+ 1);    // failed to find key
}

Besides elegant code design recursion can be the reason for some problems.
Recursion isn’t safe in C/C++ because there is no reasonable way to deal with running out of call stack space. Even if you dynamically allocate stack frames from the heap, you still can run out of heap and how do you handle the error then?

You might convert the failed call stack allocation into an exception that unwinds the stack until an out-of-stack exception handler is found, but the problem is that any function in any library called from a recursive routine might be the call that blows the stack.

Fortunately any algorithm that can be written recursively can be rewritten iteratively by keeping a heap-based stack object (and if it can be written completely tail-recursively, you don’t even need a stack). The code might be uglier when written iteratively, but it’s always possible.

You’d defenetly use recusion when you can guarantee two things:

  • Each recursive step breaks down the problem into a smaller problem of the same type.
  • Each recursive step reduces the problem significantly.

The first is a general rule of recursion. If each step doesn’t break the problem down into a smaller problem of the same type, it’s harder to write a recursive function and guarantee that it will terminate. The second is kinda personal guideline. I generally won’t write a recursive function unless it divides the problem in half with each step. This way I can verify with relative ease that the algorithm will be efficient.

Originally I planted to write this post about anonymous recursion with lambda in c#, but then I decited to describe recursion basics a bit more in detail.

A simple recursive function in c# would be for example:

private static double pow(double var, double n)
{
    if(n == 0)
        return 1;
    else
        return var * pow(var, n - 1);
}

Anonymous recursion is a recursion technique that uses anonymous functions.
I got the idea to define a special delegate type for self-applicable functions:

delegate T Pow<T>(Pow<T> self);

The delegate above can be defined like this:

Pow<double> myPow = f => f(f);
 
myPow(myPow);

When myPow is being applied to itselfwill apply myPow to itself, which will … infinite recursion. While not particularly useful in this setting, the example demonstrates that you can in fact have recursive application in a lambda expression. Now all we have to do is to make it do something useful as it goes, such as call functions recursively.

Recursion is beautiful and lambdas are the ultimate abstraction. But that’s too much for now…I’ll write about that sometime.

ruldrurd
Next Page »
Powered by WordPress, Content and Design by Kai Bellmann
Entries (RSS) and Comments (RSS)