Posts

Showing posts from February, 2009

Simple file content summary

A few days ago, I was reviewing some old samples to teach C# and I came across one that instructed the user to write a simple program. The goal was to read a text file and display on the Console a small summary containing, for example, the number of characters and the number of lines. The solution provided for this exercise was to iterate over the content of the file character by character and increment a few counters based of Char.IsSomething tests.

Here is a much cooler way to do that using a LINQ query :
string content = File.ReadAllText(path);

var contentByGroups =
from c in content
group c by Char.GetUnicodeCategory(c) into groups
select new { Category = groups.Key,
Count = groups.Count() };

foreach (var group in contentByGroups)
{
Console.WriteLine("Category {0} : {1}",
group.Category,
group.Count);
}

The Char.GetUnicodeCategory is used to get the corresponding category of each character of the file.

Thread-safe form method

If you use threads in a winforms application, you probably have already encountered the classic InvalidOperationException saying that you are trying to make an illegal cross-thread operation. This is because you cannot modify a control from a thread other than the one that created it.
Here is a simple way to write your methods in the form to avoid that exception :
void SomeMethod(SomeType parameter)
{
if (this.InvokeRequired)
{
this.BeginInvoke(new MethodInvoker(delegate()
{ this.SomeMethod(parameter); }));
}
else
{
// Do what SomeMethod is supposed to do.
}
}
You can use Invoke instead of BeginInvoke if you want to make an asynchronous call to the delegate.
Notice the anonymous method (delegate() {...}) used to invoke the same instruction in the correct thread.

Converting a List using a lambda expression

Here is a little construct I use when I need to convert a List<T> to a List<U> or when I need to pass a list of concatenated values as a string.
First, to convert a List<T> to a List<U> :

List<Guid> guidList = // Initialize list here or get it as a parameter or whatever :)
List<String> stringList = guidList.ConvertAll<String>(g => g.ToString());

It is really simple, I just use the ConvertAll method parameterized with the target type and pass it the lambda responsible for converting from the source type (Guid) to the target type (String). This example is obvious but the important thing is the combination of ConvertAll and a lambda.

For the second use ("passing a list of concatenated values as a string"), it is also really simple :
String stringValue = String.Join(
" separator ",
myGenericList.ConvertAll<String>(
/* Insert lambda here that return a string value */).ToArray());

The trick is simply to call ToArra…

Handling exceptions the right way in WCF (part 2)

In my previous post I talked about FaultExceptions and how they are transmitted from the server to the client.
First, let's have a look at the sample service contract :
[ServiceContract]
public interface ITimeService
{
[OperationContract]
[FaultContract(typeof(TimeExceptionDetails))]
DateTime GetTime();
} The service implementation :
public class TimeService : ITimeService
{
#region ITimeService Members

public DateTime GetTime()
{
return DateTime.Now;
}

#endregion
} And the Fault details class :
public class TimeExceptionDetails
{
public static readonly TimeExceptionDetails Default = new TimeExceptionDetails();

[DataMember]
public String Message { get; private set; }

public TimeExceptionDetails()
{
this.Message = "There is a problem in the spacetime continuum, Marty";
}

public TimeExceptionDetails(String message)
{
this.Message = message;
}
}
Now we'll learn how to ease the process of creating FaultExceptions by using the IErrorHandler interface. This interface allow…

Binding two Windows Forms controls

Recently, I came across a small windows application where the developer had difficulties to activate controls based on a another one. Typical example is when you want to activate a textbox sitting next to a checkbox. The developer chose to use the CheckedChanged event of the Checkbox, and to modify the Enabled property of the Textbox accordingly. The problem is you have to properly initialize the CheckState, and Enabled property of the controls to keep them both in sync from the beginning.

Then I showed him how to bind two controls directly. Most developers know about binding a control to datasource, but few of them know that it is also possible to bind to another control.

The following line shows how to do that :
myTextbox.DataBindings.Add("Enabled", myCheckbox, "Checked");
This line simply binds the Enabled property of the Textbox to the Checked property of the Checkbox. By doing that, there is no need to initialize each property nor to respond to any event.
The only …

Methods taking variable number of args (part 2)

In my previous post, I talked about the choice I made about taking a variable number of parameters. At that time, I used a simple params object[], and the logic was built into the method (in the constructor of the underlying form in fact, but it is not relevant here).The problem with this approach is how to handle parameters with the same type but different meanings. A very simple example is the caption and the text of the InformationBox. Both are strings but how to differenciate between the two. I had to force the first parameter to be the text, but it was beginning to look like the MessageBox.
For those who are familiar with C# 3.0, you may have already guessed what I could have used if .NET 3.5 had been available at that time. I could have used object initializers. It is a simple constructor syntax that allow the developer to specify only the properties he (or she) wants to define. For example, assuming the Client class is already defined with two properties "Name" and &quo…

Methods taking variable number of args (part 1)

A few months ago, I started a small project on Codeplex, its goal was simple : providing an alternative to the default Windows Forms MessageBox. One of the things that annoyed me with the MessageBox was to be forced to provide values for parameters I did not want to change.
Here is a little example :
MessageBox.Show("Text", "Caption", MessageBoxButtons.OK, MessageBoxIcon.Information);
Clearly in this case, I should not have to specify the third parameter since it is already the default value.

So basically, I needed to create a method (Show in this case) that take a variable number of parameters. The problem was with the types of the parameters, I have a whole lot of different types.

At that time, I had two ways to achieve that :Providing an overload of Show for each combination of parameters.Using params and the only type shared by all the parameters : object.The first one is nice when you have two parameters, but in InformationBox we are now dealing with up to 25 param…

Handling exceptions the right way in WCF (part 1)

Control over exceptions is very important in WCF because exceptions can contain a lot of information about the internals of your service potentially leading to security issues. WCF allows to define not only data, service or message contracts but also fault contracts. Fault contracts are used to materialize potential exceptions in the metadata of your service.

To do that, you just have to declare on your service contract which exception might be raised by a specific method.

Here is a simple service contract :
[ServiceContract]
public interface IService1
{
[OperationContract]
[FaultContract(typeof(SomeFault))]
void DoSomething();
}

Here, we are telling the WCF runtime to expose a fault contract in the service metadata. The object containing the fault detail is named SomeFault. Here is the definition of the SomeFault class :
[DataContract]
public class SomeFault
{
[DataMember]
public String SomeInfo { get; set; }
}
As you see, SomeFault is a data contract. Its use is only to transfer data …

Get newly added entities in an Entity Framework query

A few days ago, a colleague of mine ran into a little problem using Entity Framework. He was adding new entities to the context and then wanted to display these entities. Unfortunately, since the new entities are only in memory, they are not fetched by the query.
In fact, you have to use the ObjectStateManager accessible from the context to query in-memory entities. This object manages the entity cache in the context.

You can use the following code to obtain every entity already in the cache. Assuming the type of the objects you want to query is Client :
var listInMemory =
context.ObjectStateManager
.GetObjectStateEntries(EntityState.Added)
.Select(e => e.Entity).OfType<Client>().ToList();

listInMemory will contain only the new added entities from the current context. You can combine EntityState values to retrieve entities in different states.

You can also use an Union construct to add those entities to the list of entities returned by a standard Entity query. For…

Welcome

This blog will enable me to post a few tips and tricks I learned playing with the latest technologies. I will mostly talk about WCF, LINQ and also about a few interesting (I hope) things I want to share with everyone :)