rulururu

post Don’t compare objects mindless

February 18th, 2008

Filed under: .NET, Java — Kai @ 11:27 pm

When comparing objects in .Net I sometimes have to think about what way is the right one for my current case.

Imagine we got two objects called a and b that hold some data. There are several ways to compare them to each other - but it fact it’s not as confusing as I first thought.

Basically we can compare two different things of an object:

  • Identity (reference equality): Two objects are identical if they actually are the same object in memory. If the point to the same reference in memory they are equal.
  • Equivalence (value equality): Two objects are equivalent if the value or values they contain are the same.
int a = 3; 
int b = 3;

In most cases you’d regard them as equal ’cause their values are the same. Compared by identitiy they’re not equal.
This is the first you’d always keep in mind.

if(a.Equals(b))
{ 
Console.WriteLine("a equals b...");
}

Equals() is a virtual method on System.Object. It’s intended to test for identity or equivalence as appropriate. If you have an own type definition you’d like to be compareable you can override it in your class. Althougth it’s not necessary because there’s a default override of .Equals() in the base class. System.ValueType which will work for any structs you set up. Before overwriting it you’d consider that it uses reflection, which is slow, and involves a certain amount of boxing.

Value types get refleced over their internal fields to see if they are all equal.
For reference types, the situation is different. In general I’d expect Equals() for reference types to do an identity comparison but certain reference types aren’t lightweight enough to work as value types, but nevertheless have value semantics. That means most reference types are compared by reference but some like System.String are compared by value.

if(object.Equals(a, b))
{ 
Console.WriteLine("a equals b...");
}


object.Equals(object, object)
is a static method on the object class. This method was designed to reduce effort for programmers to check if a is null before calling a.Equals(b).
Generally it’s about the same as above mentioned a.Equals(b) but it also returns true if both objects are null ’cause they point to the same reference.

if(object.ReferenceEquals(a, b))
{ 
Console.WriteLine("a has same reference as b...");
}

object.ReferenceEquals(object, object) compares the addresses on the memory where the objects are.
Normally whether value types occupy the we don’t care about the memory addresses of them when comparing. It isn’t relevant for anything we’d want to normally use them for.

The difficulty comes from the fact that ReferenceEquals expects two System.Objects as parameters. This means that our value types will get boxed onto the heap as they are passed in to this routine. Normally, because of the way the boxing process works, they will get boxed separately to different memory addresses on the heap.

String a = "test", b="test";
if(a == b)
{ 
Console.WriteLine("a is equal to b...");
}

== is propably the most used operator for equality testing.
For value types within the .NET Framework, == is implemented as you would expect, and will test for equivalence (value equality).

If you use the == operator with reference types without thinking, bad things can happen. For example if you compare data structures which are not the same but contain the same value they’ll be compared as objects which means the comparison is done for reference and the result will be false even though the values are the same.

If you’d like to compare e.g. as System.String by reference you can do that as well by casting them to object.

String a = "test", b="test";
if ((object) a == (object) b)
{
Console.WriteLine("a and b point have same reference");
}

a is b checks the type of the the objects it is given. It’s not the comparison you might expect by the name of the operator.

int a = 3, b=4;
if(a is b)
{ 
Console.WriteLine("a and b are both integer");
}

In Java the meaning of those methods is about the same but when using the == operator you’d be careful because it does always a reference comparison - that’s why most people when programming Java for the first time don’t get the expected results. When comparing Strings in Java you’d always use equals().

static String s1 = "test";
static String s2 = new String ("test");
public static void main (String [] args)
{
  System.out.println ((s1 == s2) ? "same reference" : "not same reference");
  System.out.println ((s1.equals (s2)) ? "same value" : "not same value");
}

C# makes comparing strings easy even for a novice programmer and without sacrificing flexibility. The compiler is smart enough to realize that the == operator, when used with Strings, compares values rather than references. The option to compare references, of course, is still open to the programmer.

Always make sure that you know what you want to compare before using one of those methods/opertors without thinking.

post AndAlso instead of And keyword

February 8th, 2008

Filed under: .NET, C++ — Kai @ 5:01 pm

At first consider this:

if(array[i] != NULL && array[i+1] == 2) {
 //do something
}

As well in C# a typical check that you might see is something like this:

if ((Bunch["Key"] != null ) && (Bunch["Key"].Length > 0) {
//do something
}

Similarly in VB.Net you’ll find

If Not IsNothing(Bunch.Item("Key")) And Bunch.Item("Key").Length > 0) Then
' do something
End If

In both examples C++ as well C# the second condition would not throw a NullException because if the first condition fails the second (and also further ones) are not accessed.
But in the VB.Net example, if the first condition isn’t met both conditions will be evalutated either way. As you know, this will cause an NullReferenceException if for “Key” does not exist in the the Bunch collection.

A better choice would be to use the AndAlso keyword.

If Not IsNothing(Bunch.Item("Key")) AndAlso Bunch.Item("Key").Length > 0) Then
' do something
End If

This will cause the statement to stop executing if “Key” is null in the Bunch.Items collection.

post Lambda in C#

February 7th, 2008

Filed under: .NET — Kai @ 10:47 pm

Λ is more than the 11th letter of the Greek alphabet.

C# in .NET 3.0 got a number of handy new language features, but the one I’m enjoying the most at the moment is the addition of the => operator (otherwise know as lambda). While this operator does not add any new functionality to the language, it is a great piece of syntactic sugar.

In .NET 2.0, writing anonymous functions inline was a very verbose process, you might often had a hard time reading them ’cause they were looking kinda ugly.

To show you what I do mean I created a simple function. It takes a delegate that should take in 2 integers and return an integer value. Additionally it takes a list of intergers (params is used here). Finally it returns a single integer.

public delegate int expo(int x, int y);
 
public int SomeFunc(expo f, params int[] list)
{
  int r = 1;
  foreach (int i in list)
    r = f(r, i);
  return r;
}

This function is pretty clear, but the usage is ugly:

int n = SomeFunc(new expo(
      delegate(int x, int y) { return x * y; }), 55, 33, 223, 31);

also that is not even better:

int n = SomeFunc(delegate(int x, int y) { return x * y; },
      55, 33, 223, 31);

But now have a look at that great solution:

int n = SomeFunc((x, y) => x * y, 55, 33, 223, 31);

That’s an example of a lambda expression. Lambda expressions are always of this form:
parameters => expression
You no longer need to use the word delegate, you no longer need to declare the types of the parameters to the function.

This is just the basic use of the new lamdba operator in C#. So far, lambdas don’t appear to offer anything I didn’t already have with anonymous methods besides a different syntax. However, they turn out to be able to do something that anonymous methods cannot.

Indeed most of the new C# 3.0 languages features have been added on LINQ’s behalf, although none of them is inextricably bound to LINQ.

LINQ (Language Integrated Query) defines a standard way of performing queries against various types of data in a way that can be tightly integrated into a language. I wrote about that earlier.

Consider the following code which is very common:

DataContext dc = new DataContext("...");
Table<Cars> cars = dc.GetTable<Cars>();
Table<Brands> brands = dc.GetTable<Brands>();
 
var q = from c in cars, b in brands
        where b.Name == "BMW" && (c.ID == b.ID)
        select new { b.Date, c.CarHolder, c.Street, };
 
foreach (var item in q)
{
    Print(String.Format("Date: {0} Belongs to: {1} at {2}",
        item.Date, item.CarHolder, item.Street));
}

The way I’d prefer when using lambda is:

var q = cars.Where(b => b.Name == "BMW").SelectMany(
    b => brands.Where(b => c.ID == b.ID).
            Select(b => new { b.Date, c.CarHolder, c.Street }));

Deferred execution allows the language extensions for XLinq, DLinq, LINQ, or any other Linq extension that comes after to process the logic represented by the expression tree before execution so that optimizations can take place.

If you are planning on doing anything with LINQ, you should know what a lambda is, how to use it in real terms.

post Save Application data before shutdown

January 28th, 2008

Filed under: .NET — Kai @ 4:19 pm

Often in application before the OS shuts down some data is saved. In some cases a messagebox asks you for that e.g. in MS Word.

The way to implent that is that the app has to recognize that the OS is going to shut down.

FormClosingEventArgs is derived from CancelEventArgs. FormClosingEventArgs has property (CloseReason) which tells you reason of close. This may be used for identifying and handling close reason.

At first the OnClosing method has to be overridden:

protected override void OnClosing(CancelEventArgs e) 
        { 
            //Your alternate implementation
            FormClosingEventArgs args = e as FormClosingEventArgs; 
            if (args != null) 
            {
                //do something with args
            }
            base.OnClosing(e); 
        }

Referred to MSDN documentation there are some properties of CloseReason.

  • None: The cause of the closure was not defined or could not be determined.
  • WindowsShutDown: The operating system is closing all applications before shutting down.
  • MdiFormClosing: The parent form of this multiple document interface (MDI) form is closing.
  • UserClosing: The user is closing the form through the user interface (UI), for example by clicking the Close button on the form window, selecting Close from the window’s control menu, or pressing ALT+F4.
  • TaskManagerClosing: The Microsoft Windows Task Manager is closing the application.
  • FormOwnerClosing: The owner form is closing.
  • ApplicationExitCall: The Exit method of the Application class was invoked.

The implementation of the CloseReason senario is very easy:

switch (ce.CloseReason)
        {
            case CloseReason.UserClosing:
                SaveData(); //data is saved
                break;
            case CloseReason.WindowsShutDown:
                SaveData(); //data is saved
                break;
default: break;
       }

post Data binding with WPF

January 28th, 2008

Filed under: .NET, C++, General Programming, MFC, WPF — Kai @ 2:50 pm

Today I had a close look at the Data binding possibilities provided by the Windows Presentation Foundation.

Before telling you more about that I’d like to show you good-old know alternatives and then compare them to WPF’s solution.

MFC with C++

DDX (Dialog Data Exchange) and DDV (Dialog Data Validation) are two great tools that allow us to easily set and access the values of certain MFC controls.

DDX allows us to link the value of a variable to a control. To use some DDX functions, you should override the DoDataExchange function of a dialog:

afx_msg void DoDataExchange(CDataExchange*);

The function itself can look like this, it just binds the “resource” to a member variable.

afx_msg void DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Text(pDX, TXT_NAME, m_strName);
}

The first line calls the base class, the seconds calls that function:

void DDX_Text(CDataExchange* pDX, int nIDC, CString& value);

If we want to set the value of the controls, we can call the UpdateData passing FALSE to the UpdateData function. On the other hand, if we want to retrieve the value of the control into our CString variable, we would pass TRUE to the UpdateData function.

BOOL CWnd::UpdateData(BOOL bSaveAndValidate)
{
	CDataExchange dx(this, bSaveAndValidate);
	try
	{
		DoDataExchange(&dx);
	}
	catch(CUserException e)
	{
		return FALSE;
	}
	return TRUE;
}

For other controls such as the list box, radio button and check box, we would use the similar DDX functions DDX_CBString, DDX_Radio and DDX_Check respectively.

When using DDX for the exchange of data between controls and variables we easily can validate them.

void CSample::DoDataExchange(CDataExchange* dx)
{
	CDialog::DoDataExchange(dx);
	//{{AFX_DATA_MAP(CDlg)
	...
	DDX_Text (dx, TXT_AGE, m_iAge);
	DDV_MinMaxInt(dx, m_iAge, 0, 150);  // <- validation
	. . .
	//}}AFX_DATA_MAP
}

The DDX_Text() call transfers the contents of the edit control into the m_age data member, converting it into an integer. After that is has to pass validation.

DDV_MinMaxInt looks as follows:

void DDV_MinMaxInt(CDataExchange* dx, int value, int min, int max)
{
	if (value < min || value > max)
	{
		AfxMessageBox("Please enter a value between ...");
		dx->Fail();
	}
}

If the value doesn’t yield the condtions of the validation method a error message is shown and Fail() is invoked on the data exchange object.

Windows Forms with C#

Data binding in C# provides a more advanced way for developers to create a read/write link between the controls on a form. It’s often used for binding forms to complex data structures such as SQL databases. Windows Forms data binding allows you to access data from databases as well as data in other structures, such as arrays and collections.

Each Windows Form has at least one BindingContext object that manages the access to and from the controls. For example if you add use a textbox control to a form and bind it to a column of a table (e.g. “tblAddress.Name”) in a dataset(e.g. called “dsAddr”), the control communicates with the BindingContext object for that form.

txtname.DataBindings.Add("Tom Morello",Adresses,"tblAddress.Name");
CurrencyManager cm = (CurrencyManager)this.BindingContext[dsAddr,"tblAddress"];
foreach(object s in cm)
{
Console.WriteLine(s.ToString());
}

The CurrencyManager is used to keep data-bound controls synchronized with each other.

That way of data binding is very useful when dealing with collection controls such as ListView or ListBox.
It’s common practice to bind them to any kind of Array, Collection or List.

A quick and clever way is the usage of data bindings in C# with ADO.NET Data Objects because those data structures are suitable for binding to.

DataTables such as GridView provide DataSource and DataMember properties:

gv1.DataSource = dsAddr;
gv1.DataMember = "tlbAddresses";

other appropriate objects are:

  • DataColumn
  • DataView
  • DataSet
  • DataViewManager

You also can bind controls to other controls. Binding data of a ComboBox to a ListBox follows the same model and is no problem.

DataBinding with WPF

Now we come to the point the article originally was about.
When working with collection-like data sources in WPF, you can read properties of the selected item by writing your binding expressions directly into the XAML (eXtensible Application Markup Language) code that defines the structure of every WPF-GUI.

<DockPanel DataContext="{x:Static Persons}">
  <TextBlock DockPanel.Dock="Top"
             Text="{Binding Lastname}" >
  <ListBox ItemsSource="{Binding}"
           IsSynchronizedWithCurrentItem="True" />
</DockPanel>

In that example the source is an array of persons names and the ListBox should show the lastname of every person the array contains.
When WPF encounters a binding to a non-existent property on a collection, WPF has a fallback strategy: it looks for the named property on the current item.

If source and destination are both collections you can do

Property="{Binding /}"

to bind them to each other.

That’s nice behavoir but just the beginning of some great ideas.
There are several things you can define in the binding object:

  • OneWay binding causes changes to the source property to automatically update the target property, but changes to the target property are not propagated back to the source property.
  • TwoWay binding causes changes to either the source property or the target property to automatically update the other. This type of binding is appropriate for editable forms or other fully-interactive UI scenarios.
  • OneWayToSource is the reverse of OneWay binding; it updates the source property when the target property changes.
  • OneTime binding causes the source property to initialize the target property, but subsequent changes do not propagate. This means that if the data context undergoes a change or the object in the data context changes, then the change is reflected in the target property. This type of binding is appropriate if you are using data where either a snapshot of the current state is appropriate to use or the data is truly static.

The UpdateSourceTrigger property of the binding determines when binding should appear.

  • LostFocus (default e.g. for TextBox)
  • PropertyChanged
  • Explecit (when calling UpdateSource)

Due data binding you could for example bind a textbox value to its background color. The property of type string in the binding source object is connected to a Color property of type Color.

IValueConverter makes it possible:

public class ColorBrushConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        Color color = (Color)value;
        return new SolidColorBrush(color);
    }
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return null;
    }
}

To ensure that the user has entered the expected information we user input validate it with some logic.
At first we add a validation in description section of the GUI.

<TextBox Name="Birthday" 
    Style="{StaticResource textStyleTextBox}">
  <TextBox.Text>
    <Binding Path="BDay" UpdateSourceTrigger="PropertyChanged">
        <Binding.ValidationRules>
        <ExceptionValidationRule />
      </Binding.ValidationRules>
    </Binding&gt;
 </TextBox.Text>
</TextBox>

The ValidationRules property takes a collection of ValidationRule objects. When the user enters a value that cannot be converted to an the expected type, an exception is thrown, causing the binding to be marked as invalid.

You also can define your own rule:

<Binding.ValidationRules>
                <src:MyRule />
            </Binding.ValidationRules>
class MyRule : ValidationRule
{
    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        DateTime date;
        try
        {
            date = DateTime.Parse(value.ToString());
        }
        catch (FormatException)
        {
            return new ValidationResult(false, "Invalid date!");
        }
        if (DateTime.Now.Date < date)
        {
            return new ValidationResult(false, "You cannot be born in the future.");
        }
        else
        {
            return ValidationResult.ValidResult;
        }
    }
}

You also might visualize a wrong input for the user.

<Style x:Key="textStyleTextBox" TargetType="TextBox">
  <Setter Property="Foreground" Value="#fff000" />
  <Setter Property="MaxLength" Value="10" />
  <Style.Triggers>
    <Trigger Property="Validation.HasError" Value="true">
      <Setter Property="ToolTip"
        Value="{Binding RelativeSource={RelativeSource Self},
                        Path=(Validation.Errors)[0].ErrorContent}"/>
    </Trigger>
  </Style.Triggers>
</Style>

Now a tooltip appears when the HasError property of Validation is true. You can define a so called Error Template that is used for invalid inputs, if you don’t the default is used.

There are enough and to spare features you can use when working with bindings in WPF, but telling about all of them would carry things too far.

Comparison and forecast

The way MFC programmers use is clear and easy to use. It’s not very casual to handle but it can be extented unique for the project’s necessities.

Win Forms are mostly the same - also the spreading of Win Forms applications on the software market seems to be similar to MFC apps.

From my point of view software development can be really enhanced by technolgies like those provided by the WPF. Also for non-WPF applications its always worth to think about those concepts.

post C# params keyword

January 25th, 2008

Filed under: .NET — Kai @ 5:58 pm

Lets take a look at what the params keyword does.

It mainly gives you the ability to create functions that take a variable number of arguments - often called “variadic” or “variable arity” functions. This is not a really new feature only provided by C# you can also find it in C and C++, in the form of the “…” syntax, and Java uses that syntax as well. (e.g. Exception{} catch(…))

I’d like to show how useful the usage in C# can be:

public int Sum(params int[] list)
{
  int res = 0;
  foreach (int i in list)
    res += i;
  return res;
}

As you can see, the params keyword is used as an argument list for a number of typed vars.

You can call that small function with zero or more arguments.

int result = Sum(5);
result = Sum(5,4,3,4);
result  = Sum(new int[] { 3,4,4,2,11 });
result  = Sum();

This would report an error because the arguments are invalid:

int result = Sum(1,2,3 new int[] { 4,5,6 });

Even though you can pass in lists/array for the params, you can’t mix it up with regular values at all.

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