DotNet Support Blog
Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Specification Pattern and Lambdas

Posted In: , , . By Sothy Mom

While working on my current project I decided that I had a need to use the Specification Pattern . After finding a clean implementation by Jeff Perrin I set to work creating the specifications that I needed. I quickly realized that we were going to end up having a ton of specifications and sometimes they would only apply to very special cases. Other times they would be very broad cases and they needed to be even more composable than even the fluid interface implemented in Jeff’s implementation wasn’t going to be enough. It after all still required me to create a concrete implementation for each specification, no matter how minuscule it might be.

This is the part where I thought to my self that since i was really only creating implementations for a single method that I could just write a LambdaSpecification and be able to use this for all the special cases I had.

Below is the LambdaSpecification Code:


using System;
using System.Linq.Expressions;

namespace Specification
{
    public class LambdaSpecification<T> : Specification<T>
    {
        private Func<T,bool> _expression;

        public LambdaSpecification(Func<T,bool> expression)
        {
             if(expression ==null) throw new ArgumentNullException(”expression”);
              _expression = expression;
        }

        public override bool IsSatisfiedBy(T obj)
        {
            return _expression(obj);
        }
    }
}

And the Tests:


[Test]
public void LambdaSpecification_CanExecuteSimpleLambda()
{
    var p = new Person() {Name = “Eric”};
    var spec = new LambdaSpecification<Person>(x => x.Name == “Eric”);

        Assert.IsTrue(spec.IsSatisfiedBy(p));
}

[Test]
public void LambdaSpecification_CanExecuteComplexLambda()
{
    var p = new Person() {Name = “Eric”, Age = 28};
    var spec = new LambdaSpecification<Person>(x => x.Name == “Eric” &&
                                                                        new IsLegalDrinkingAgeSpecification().IsSatisfiedBy(x));

    Assert.IsTrue(spec.IsSatisfiedBy(p));
}

//Might Not be needed but I wanted to be sure
[Test]
public void LambdaSpecification_CanExecuteLambda_AndUseAndSpecification()
{
    var p = new Person() {Name = “Eric”, Age = 28};
    var spec = new LambdaSpecification<Person>(x => x.Name == “Eric” );

    Assert.IsTrue(spec.And(new IsLegalDrinkingAgeSpecification()).IsSatisfiedBy(p));
}

Comments are welcome and encouraged, especially if you see a reason why I shouldn’t be doing this. Or, if you have any ways to make this better, I would love to hear them. This is the first time I have ever used a lambda as a parameter in my own code and so far i am liking it.

Thanks to Jeff Perrin again for his post on creating a clean implementation of the specification pattern.

 

Often we need to capitalize the first letters of some word or some text (for example when we want to display users name or city name etc).
Since string class does not have a method to do this we could think that there is no built-in solution in C# for this problem...
But a little digging trough MSDN would help us find ToTitleCase method of TextInfo class in System.Globalization namespace that does exactly what we need: capitalizes the first letter of each word in the string.
here is how to use it:

using System.Globalization;

  ...

string capitalized = CultureInfo.CurrentCulture.TextInfo.ToTitleCase("asp.net simply rocks!!!");

After the execution, capitalized string would have this value: "Asp.Net Simply Rocks!!!" which is exactly what we needed, right?
Off course, how will string be capitalized depends on the current culture that is set on your ASP.NET page, but we can easily override this and use the culture we want like this:

TextInfo UsaTextInfo = new CultureInfo("en-US", false).TextInfo;

string capitalized = UsaTextInfo.ToTitleCase("asp.net simply rocks!!!");

 

FOAF parsing and crawling in C#

Posted In: . By Sothy Mom

I’ve been looking deeply into FOAF lately and last week I worked on a parser that could wrap a FOAF document into a strongly typed class for easy consumption by C#. Now I want to share it with anyone interested. It appears there are no FOAF parsers available in C# yet. I wasn’t able to find any.

The parser

The class FoafParser has two public methods, Parse and ParseFriendsAsync, which handles two different approaches in fetching FOAF documents.

The Parse method

This method takes a URL as a parameter which must point to an online FOAF document. It then parses the foaf:Person element which contains fields such as name, birth date, photo, homepage etc. It then looks for people in the FOAF document that are described as someone you know, parses the information available and adds it to a public collection property. The following example parses a FOAF document and binds it to an ASP.NET Repeater.

FoafParser parser = new FoafParser();
parser.Parse(new Uri("
http://example.com/foaf.xml"));
if (parser.IsParsed)
{
  ltOwner.Text = parser.Owner.Name;
  repFriends.DataSource = parser.Friends;
  repFriends.DataBind();
}

The ParseFriendsAsync method

When you list people you know in a FOAF document, it is common to only provide very little information such as the full name. When that is the case it is also common to provide a link to that persons FOAF document using the rdfs:seeAlso tag. We can then use that link to retrieve all your friend's FOAF documents and parse them as well.

It can take a long time to retrieve all those documents one at a time, but if we do it asynchronously then we can speed things up substantially. When you have called the Parse method on the FoafParser class, you can then call ParseFriendsAsync. It loops through all the friends that the Parse method found in search for the rdfs.seeAlso tag. When it finds it, a web request is made to retrieve the FOAF document of that friend and then parse it for information.

When the ParseFriendsAsync method is finished, it triggers an event you can listen to. All the friends with FOAF documents have now been updated in the collection.

private void RetrieveAsync()
{
FoafParser parser = new FoafParser();
  parser.Parse(new Uri("
http://example.com/foaf.xml"));
if (parser.IsParsed)
  {
    parser.FriendParsingComplete += new EventHandler<EventArgs>(parser_FriendParsingComplete);
    parser.ParseFriendsAsync();
  }
}

void parser_FriendParsingComplete(object sender, EventArgs e)
{
// Now the Friends collection has been updated asynchronously.
FoafParser parser = (FoafParser)sender;

  Response.Write(parser.Friends.Count);
}

Download

In the zip file below you’ll find the FoafParser.cs class as well as an example .aspx page and code-behind file.

FoafTester.zip (3,77 kb)

 

Operator~ and BinarySearch

Posted In: . By Sothy Mom


Usually, we use Array.BinarySearch to find a value in a sorted array, we all know that this method returns the index of the searched value in the array, if value is found. It turns out that the return value of BinarySearch is much more interesting and useful. Lets focus on what happens if the value is not found in the array.

Those who claim that if value is not found than a negative number will be returned, are absolutely right. But most of us don’t really know the whole truth about that negative number and how it can be used.

magnifying-glass

To understand its usage, we can see how the Add method in SortedList class is implemented (this operation must keep the list sorted):

1:
2: public virtual void Add(object key, object value)
3: {
4:     if (key == null)
5:     {
6:         throw new ArgumentNullException();
7:     }
8:     int index = Array.BinarySearch(this.keys, 0, this._size, key, this.comparer);
9:     if (index >= 0)
10:     {
11:         throw new ArgumentException();
12:     }
13:     this.Insert(~index, key, value);
14: }

Did you notice the bitwise complement operator~ in line 13? It is applied on the negative result of the binary search to produce an index that is used in the Insert method. The guys in Microsoft who wrote the SortedList.Add method took advantage of the following fact about BinarySearch return value:

If the array does not contain the searched value, the method returns a negative integer so you can apply the bitwise complement operator~ to it and produce an index. If this index is greater than or equal to the size of the array, the searched value is the largest number in the array. Otherwise, it is the index of the first element that is larger than the searched value.

So, the produced index can be used in the Insert method to add the value in the correct place and keep the array sorted. When I introduced this fact to some of my colleagues , they claimed this is very nice and tricky but may be unreadable. What do you say?

 

A C# Operator I would like to see.

Posted In: . By Sothy Mom

You could argue there are too many operators in C# as it is; however, I feel having an acute knowledge of the available operators is like knowing CTRL + B will bold the selected text in most word processing software.

To put it simply, it hurts no-one, whilst providing shortcuts to advanced users.

Consider the following:

if (MyObject != null)
{
    return MyObject;
}
else
{
    return SomeOtherObject;
}

In C# 2.0, the kind people at Microsoft provided the ?? operator to make this a much more sucinct:

return MyObject ?? SomeOtherObject;

One thing that I find ugly and boring in code is that of checking for nulls in nested object properties, so for a moderately extreme example:

Staff.Manager.PersonalDetails.Address.Location.Postcode

In order for me to be sure that I can access the “Postcode” part of this chain correctly (with the caviet that each of these proerty objects might be null) I’d have to write something like the following:

if (Staff != null && Staff.Manager != null &&
    Staff.Manager.PersonalDetails != null &&
    Staff.Manager.PersonalDetails.Address != null && .....
{

I’m sure you’ll agree the above is pretty ugly, especially if you don’t really care which property is null, just if any of them are.

So, I propose a new operator, the “Is anything in this chain null” operator, to be used something like so:

return ??{Staff.Manager.PersonalDetails.Address.Location.Postcode} : “No Postcode”

The actual syntax of this operator isn’t important, just the functionality.