rulururu

post Tipps for writing good performanced code in .NET

May 6th, 2008

Filed under: .NET, General Programming — Kai @ 5:50 pm

Writing code that runs quickly is sometimes at odds with writing code quickly.

Writing unnecessary code is undoubtedly bad for work efficiency. However, it’s important to realize that different situations have different needs. Code for vehicular real-time control systems has inherent up-front responsibilities for stability and performance that aren’t present in, say, a small one-off departmental application. Therefore, it’s more important in such code to optimize early and often.

  • 1. Tools
  • While testing tools such as NUnit and the upcoming VS.NET 2005 Team System can help you find bottlenecks, when tuning small sections of code, there’s still no substitute for the micro-benchmark. This is because most generic testing frameworks depend on things like delegates, attributes, and/or interface method calls to do testing, and the code usually is not written with benchmarking primarily in mind. This can be very significant if you’re interested in measuring the execution time of a batch of code down to the microsecond or even nanosecond level.
    However, these techniques alone can’t solve the dreaded problem of uniformly slow code, which surfaces when large bottlenecks have been resolved but the code still exhibits inadequate performance. This is code that has been written without attention to correct usage.

    Another important tool is ildasm.exe, the IL disassembler. With it, you can inspect the IL of your release builds to see if your assumptions are correct about what’s going on under the covers.
    A great free tool for decompiling IL to C# or VB source, Reflector, can be found [here]; it’s incredibly useful for viewing code that ships with the .NET Framework, for those of you less familiar with IL.

  • 2. Techniques & Guides Lines
  • 2.1 Objects and Garbage Collectors
    Objects are expensive to use, partly because of the overhead involved in allocating memory from the heap (which is actually well-optimized in .NET) and partly because every created object must eventually be destroyed. The destruction of an object may take longer than its creation and initialization, especially if the class contains a custom finalization routine.

    It’s necessary to understand garbage collection to appreciate the full impact of using objects. The single most important fact to know about the garbage collector is that it divides objects into three “generations”: 0, 1, and 2. Every object starts out in generation 0; if it survives (if at least one reference is maintained) long enough, it goes to 1; much later, it transitions to 2. The cost of collecting an object increases with each generation. For this reason, it’s important to avoid creating unnecessary objects, and to destroy each reference as quickly as possible. The objects that are left will often be long-lived and won’t be destroyed until application shutdown.

    2.2 Lazy Instantiation / Initialization
    The Singleton design pattern is often used to provide a single global instance of a class. Sometimes it’s the case that a particular singleton won’t be needed during an application run.
    It’s generally good practice to delay the creation of any object until it’s needed, unless there’s a specific need to the contrary - for instance, to pre-cache slow-initializing objects such as database connections. The “double-checked locking” pattern is useful in these situations, as a way to avoid synchronization and still ensure that a needed action is only performed once. Lazy initialization is a technique that can enhance the performance of an entire application through object reduction.

    2.3 Avoiding Useage of Class Destructors
    Class destructors cause extra overhead for the garbage collector, ’cause it must track which objects have been finalized before their memory can be reclaimed.

    2.4 Casting and Boxing / Unboxing Overhead
    Casting is the dynamic conversion of a type at runtime to another, and boxing is the creation of a reference wrapper for a value type (unboxing being the conversion back to the wrapped value type).
    The overhead of both is most heavily felt in collections classes, as they all - with the exception of certain specialized ones like StringDictionary - store each value as an Object. For instance, when you store an Int32 in an ArrayList, it is first boxed (wrapped in an object) when it is inserted; each time the value is read, it is unboxed before it is returned to the calling code.

    One soloution is to use generics, the other how to avoid overhead is to avoid it by creating strongly typed collections and by typing variables and parameters as strongly as possible. If you’re unsure about whether or not boxing/unboxing is taking place, you can check the IL of your code for appearances of the box and unbox keywords.

    2.5 Trusting the Garbage Collector
    Programmers new to .NET sometimes worry about memory allocation to the point that they explicitly invoke System.GC.Collect(). Garbage collection is a fairly expensive process, and it usually works best when left to its own devices. A thumb rule is not to call GC.Collect() unless you really know what you’re doing.

    2.6 Excessive use of Delegates
    Delegates are slower to execute than interface methods. Delegates are often used to introduce a level of indirection in code, but in almost all cases interfaces allow a cleaner design. Don’t use them if it’s not necessary.

    2.7 Using the ‘Sealed’ Keyword
    Wherever extensibility is not required, you should use the sealed keyword. This makes your design easier to understand, as someone can tell at a glance if a certain class or method isn’t meant to be extended or overridden. It also increases the chances that the compiler will inline code.

    2.8 for versus foreach
    The rumor abounds that the foreach loop is bad for performance. The truth is actually a little more complicated. Basically, foreach involves no performance penalty when used against arrays. However, when used against lists it involves the same overhead as creating an enumerator and using it within a try/catch block!

    2.8 Working With Strings
    Don’t Use String.Format() to Concatenate Strings.
    While string-formatting routines built into .NET are very useful for globalization and other tasks, they’re not meant to be used for appending strings to each other. You’d better prefer Stringbuilders as I explained in this post.

    2.9 Minimizing Synchronized Blocks
    The use of the [MethodImpl Attribute(MethodImplOptions.Synchronized)] attribute should be avoided, as it always locks an entire method and is also non-standard C# usage. Instead, the lock keyword or one of the System.Threading classes should be used. Wherever possible, adjust the start of a synchronized section forward and the end backward. Do whatever you can to decrease the number of synchronized operations.

    Do early optimization before rewriting half of your project afterwards but don’t waste too much time in optimizing parts of code that don’t make problems now. It’s never false thinking of writing a quick running code than just writing it down quick but don’t agonize over things that don’t make problems yet.

    post Sorting Strings containing Numbers

    March 24th, 2008

    Filed under: .NET, General Programming — Kai @ 6:20 pm

    It’s often necessary to sort lists. The Sort method of ArrayList class shows that it can’t be difficult. Also some other classes can be sorted unless they are type IComparable.
    The sort method of ArrayList class has several overloads, some can be given to a Comparer, which implements the IComparer interface.

    The interface has just one method called Compare which returns equal, greater or smaller depending on the two values it compares.

    If you’d make your own comparer you’d simply do that like this:

    public class MySpecialComparer : object, System.Collections.IComparer
    {
     
        /// <summary>
        /// Default constructor - initializes all fields to default values
        /// </summary>
        public MySpecialComparer()
        {
        }
    }

    There’s also a difference in ascending and descending sort order. Mention the following code which compares String descending:

    public class DescendingComparer : IComparer
    {
      public int Compare(object objA, object objB)
      {
        return String.Compare(objB.ToString(), objA.ToString());
      }
    }

    The trick is just to compare B to A and not the way round.

    To sort a simplest one dimensional array in alphabetical order, we’ll leverage the static “Sort” method in the Array class to sort the array. The Array.Sort method will sort the array in place, meaning we don’t have to create another array to contain the resulting array. Here is how:

    String[] myAnimals = {"Zebra","Elephant","Snake"};
    Array.Sort(myAnimals);

    As expected this will result in the array getting sorted in the ascending order i.e. iterating the elements of this array will cause the output in the following manner:

    Elephant, Snake, Zebra

    Computer string sorting algorithms generally don’t order strings containing numbers in the same way that a human would do. Consider:

    rfc1.txt, rfc2086.txt, rfc822.txt

    It would be more friendly if the program listed the files as

    rfc1.txt, rfc822.txt, rfc2086.txt

    Filenames sort properly if people insert leading zeros, but they don’t always do that.
    It’s kinda tricky when strings that contain numbers are sorted ’cause they’ve to be sorted numerically.

    Imagine an array of values like this:

    string[] Items = { "z4", "z2", "z15", "z1" };

    The idea is to write a Comparer (implements IComparer) which extracts the numeric part e.g. by RegEx: [0-9]*
    Then sort as already familiar with a Collections.Sort method that uses the comparator.

    Generally you’d “invent” an algorithm that breaks strings into chunks, where a chunk contains either all alphabetic characters, or all numeric characters. These chunks are then compared against each other. If both chunks contain numbers, a numerical comparison is used. If either chunk contains characters, the ASCII comparison is used.

    Ian Griffith offered a code sample that helps to handle string sorting with numbers:

    /// <summary>
    /// Compares two sequences.
    /// </summary>
    /// <typeparam name="T">Type of item in the sequences.</typeparam>
    /// <remarks>
    /// Compares elements from the two input sequences in turn. If we
    /// run out of list before finding unequal elements, then the shorter
    /// list is deemed to be the lesser list.
    /// </remarks>
    public class EnumerableComparer<T> : IComparer<IEnumerable<T>>
    {
        /// <summary>
        /// Create a sequence comparer using the default comparer for T.
        /// </summary>
        public EnumerableComparer()
        {
            comp = Comparer<T>.Default;
        }
     
        /// <summary>
        /// Create a sequence comparer, using the specified item comparer
        /// for T.
        /// </summary>
        /// <param name="comparer">Comparer for comparing each pair of
        /// items from the sequences.</param>
        public EnumerableComparer(IComparer<T> comparer)
        {
            comp = comparer;
        }
     
        /// <summary>
        /// Object used for comparing each element.
        /// </summary>
        private IComparer<T> comp;
     
     
        /// <summary>
        /// Compare two sequences of T.
        /// </summary>
        /// <param name="x">First sequence.</param>
        /// <param name="y">Second sequence.</param>
        public int Compare(IEnumerable<T> x, IEnumerable<T> y)
        {
            using (IEnumerator<T> leftIt = x.GetEnumerator())
            using (IEnumerator<T> rightIt = y.GetEnumerator())
            {
                while (true)
                {
                    bool left = leftIt.MoveNext();
                    bool right = rightIt.MoveNext();
     
                    if (!(left || right)) return 0;
     
                    if (!left) return -1;
                    if (!right) return 1;
     
                    int itemResult = comp.Compare(leftIt.Current, rightIt.Current);
                    if (itemResult != 0) return itemResult;
                }
            }
        }
    }

    When using it a regular expression for the numbers is needed.
    Using C# 3.0 it can be used that way:

    Func<string, object> convert = str =>
    {   try { return int.Parse(str); }
        catch { return str; } };
     
    var sorted = testItems.OrderBy(
        str => Regex.Split(str.Replace(" ", ""), "([0-9]+)").Select(convert),
        new EnumerableComparer<object>());

    Again the lambda expression can help a lot. sorted is an untyped listed that can be iterated with foreach.

    When sorting / comparing strings that contain numbers you always should consider to sort them the way a human would do.

    post Metasyntactic variable foo

    February 29th, 2008

    Filed under: General Programming — Kai @ 8:18 am

    As you know the term foobar or foo and bar separately are very often used in programming examples.

    const Object* foo();
    void bar(Object *);
     
    void blah() {
       bar(foo());         // Error: bar discards const
    };

    You might have known that spam and eggs are variables most commonly used by Python programmers.

    The majority of programmers might be aware of those variables being called metasyntactic variables but I think just a few do exactly know where they come from, what can be attributed to the fact that this question may is not be answered conclusively.

    A very historic example of foobar being used in a famous program is its use as a variable name in the fortran code of Colossal Cave Adventure (1977). The variable FOOBAR was used to contain the players progress in saying the magic phrase “Fee Fie Foe Foo”.

    Foo

    The first appearance of FOO can be found in 1930 in a comic strip called “Smokey Stover” (www.smokey-stover.com). In this connection, the autor makes BAR a word for the military abbreviation “FUBAR”, which stands for “Fucked Up Beyond All Repair” or “All Recognition” - in other words “irreparable”.

    Earlier versions of this entry suggested the possibility that hacker usage actually sprang from “FOO, Lampoons and Parody”, the title of a comic book first issued in September 1958, a joint project of Charles and Robert Crumb. Though Robert Crumb (then in his mid-teens) later became one of the most important and influential artists in underground comics, this venture was hardly a success; indeed, the brothers later burned most of the existing copies in disgust. The title FOO was featured in large letters on the front cover.

    Other sources confirm that FOO was a semi-legendary subject of British-army in World War II graffiti more-or-less equivalent to the American Kilroy. Where British troops went, the graffiti “FOO was here” or something similar showed up. Several slang dictionaries aver that FOO probably came from Forward Observation Officer.

    The question is if foo is used just in any case you just like to or if there are some kinda rules or unified standards when it should be used and when not.

    The first usage is simply the one mentioned above in source code. Additionally in filenames, a common convention is that any filename beginning with a metasyntactic-variable name to mark it as a file that is crap and may be deleted at any time.

    The etymology of hackish foo is obscure. In RFC (Request for Comments) documents yuo can find comprehensive information about the Etymology of “Foo” (RFC 3092). The document is 99% fun and shouldn’t be taken too seriously. It’s awesome that people put in so much effort for a really unimportant variable that’s not really more than a placeholder in code.

    For me the the only sense in foo is to have a variable that doesn’t prescind from the major thing in the example. Besides you don’t have to think every time again of a variable name that is elevant to contribute. Even thought I can’t remeber of having used foo or bar lots of times.

    post Basic design patterns and a book recommendation

    February 23rd, 2008

    Filed under: General Programming, Java — Kai @ 3:52 pm

    About a year ago I got interested in the complexety of design patterns for better solving problems in software development you are circularly confronted with. When reading “Head First Design Pattern” by Eric Freeman, Elisabeth Freeman and Kathy Sierra I soon mentioned that I use the common ones of them without having recognized it before.

    designpatternsI’m not as surprised about that as you might think ’cause there a several problems in software development you can just solve that way or you chose kinda “dirty” way. Even thougth the book is exhausting to read ’cause it’s not written the way most book for programmers are - it’s really abstract which means they’re almost never writing about problems that occur the development of a software product but all-time about compareable situations in real life. None the less I can without any doubt recommend it to you as a book every programmer should have read once or maybe twice.

    To give you a short preview I’d like to tell you about real basic patterns you might already know very-well.

    All code examples are written in Java, not because I do like Java that much, rather ’cause Java is qualified to be readed easily particularly concerning object orientated programming techniques. It doesn’t have much overhead in syntax that would distract you from the things I really want to you see. Of course patterns are used in every object orientated language they just differ form each other by the way there’re syntactical written and some programming languages have features that help to implement them easier.

    • The Factory Method
    • It’s its intention to separatly construct a complex object so that the same construction process can create different representations.

      It provides a simple decision making class which returns one of several possible subclasses of an abstract base class depending on data it is provided.
      If there’s more than one way to created an object factory methods are right choice. Especially when the class that calls a factory method delivers the required information for creating an instance.

      The factory method pattern should be used in those cases:

      * The class that calls the factory method doesn’t know exactly what instance has to be created.
      * The calling class is not pretty sure howto created the needed instance.
      * The calling class gives information to the factory method that helps/is required to created the needed instance of an object.
      * The class that provides a factory method to gives permission of its creation to its subclasses.

      Factory methods are common in toolkits and frameworks where library code needs to create objects of types which may be subclassed by applications using the framework.

      This example of a facotory method creates an instance of an ImageReader. Each time the program reads an image it needs to create a reader of the appropriate type based on some information in the file.

      public class ImageReaderFactory 
      {
          public static ImageReader getImageReader( InputStream is ) 
          {
              int imageType = figureOutImageType( is );
       
              switch( imageType ) 
              {
                  case ImageReaderFactory.GIF:
                      return new GifReader( is );
                  case ImageReaderFactory.JPEG:
                      return new JpegReader( is );
                  // etc.
              }
          }
      }
    • The Abstract Factory Method
    • It provides an interface to create and return one of several families of related objects. It encapsulated a group of individual factories that have a common theme.

      Abstract factory methods work like classic factory methods but they’re a bit enhanced. Using them is recommented when:

      * A class should work totally independent from the creation of the instances of objects it works with.
      * A group of objects shall be created ’cause they’d be used together
      * A class library should offer a whole bunch of implementations.

      Typically you find it in GUI libraries that offer different themes for their controls.

      At first we design a abstract factory that looks very clear:

      public abstract class AbstractGUI 
      {
           public Button CreateButton()
           {
              return new Button();
           }
      }

      Afterwards two concret class get designed that extends the abstract class and its methods override the deliverd ones.

      public class XPStyle extends AbstractGUI 
      {
         @Override
         public Button CreateButton()
         {
            return new XP_Button();
         }
      }
       
      public class GnomeStyle extends AbstractGUI 
      {
        @Override
         public Button CreateButton()
         {
            return new Gnome_Button();
         }
      }

      The GUI class has a method for the name of a control:

      public class AbstractGUI 
      {
      private String name;
       
        public String getName() 
        {
          return this.name;
        }
       
        public void setName(String name) 
        {
          this.name = name;
        }
      }

      This is the most important part, that is used when a particular button is created:

      public class XP_Button extends Button
      {
        public XP_Button()
        {
          super();
          setName(”XP Button”);
        }
      }

      Eventually the great advantage of this is that you don’t have to worry about what kind of objects you’re building the factory does ease your workload.

    • The Builder Pattern
    • It can be used to clearify a complex building progress of an big object.

      This should explain how a abstract builder works:

      abstract class ButtonBuilder
      {
          protected Button button;
       
          public Button getButton()
          { 
              return button; 
          }
          public void BuildNewButton()
          { 
              button = new Button(); 
          }
       
          public abstract void buildStyle();
      }

      In this class the concret building is done:

      class MySuperButtonBuilder extends ButtonBuilder
      {
          public void buildStyle()
          { 
              button.RoundBorders(1);
              button.FancyLook(1);
          }
      }

      It separates the construction of a complex object from its representation, so that several different representations can be created depending on the needs of the program.

    • The Prototype Pattern
    • The prototype means making a clone. This implies cloning of an object to avoid creation. If the cost of creating a new object is large and creation is resource intensive, we clone the object. We use the interface Cloneable and call its method clone() to clone the object.

      public class Data implements Cloneable 
      {
          public Object clone()
          {
              try{
                  return this.getClass().newInstance();
              }
              catch(InstantiationException e)
              {
                 e.printStackTrace();
                 return null;
              }
          }
      }
       
      public class DataCreator
      {
         private Data d;
       
           public DataCreator(Data d)
           { 
               this.d = d; 
           } 
           public Data GetData() 
           { 
             return (Data)data.clone(); 
           } 
           public Object clone()
           { } 
      }
       
      public class SecretData extends Data 
      {
      //concrete prototypes to clone
      }

      Working with that can be done in that way:

      Data dataprotoype = new SecretData(); 
      Data mydata = new SecretData(dataprotoype); 
       
      for(int i=0; i<100; i++) 
         tmpData = mydata.GetData();

      It starts with an initialized and instantiated class and copies or clones it to make new instances rather than creating new instances.

    • The Singleton Pattern
    • Is the one that provides a class of which there can be no more than instance, and provides a single global point of access to that instance.
      Sometimes it’s appropriate to have exactly one instance of a class: e.g. for window managers, print spoolers etc.
      The most common usage is a logging class that does something with alle logs and exceptions that are thrown.

      If an object is needed in the whole application a singleton is better than a real global object. But you’d also be careful when implementing lots of singletons ’cause you surly don’t want
      give up object orientation and have everything globally just for easier usage.

      A singleton should give you those possibilies:

      * Create the only existing object of a class
      * Provide a global point of access to the object (getInstance(); ).

      The first thing you’ve to do when avoiding the creation of multible objects from one class is to set the constructor to private access.
      Then you’ve provide your own method for creation of an object that checks if another object exists before creating. Easy but effective!

      private static Logger log;
       
      private Logger() 
      {
      //private constructor
      }
       
      public static Logger getInstance() 
      {
       if (Logger.log == null) 
       {
         Logger.log = new Logger();
       }
          return Logger.log;
      }

      To improve this solution we’d make it thread-save. Java provides a synchronized keyword that ensures the synchronized access. Java makes it really simple, C# needs a variable that is volatile (indicates that a field can be modified in the program by something such as the operating system, the hardware, or a concurrently executing thread.) which is check before creating a new object.

      public static synchronized Logger getInstance () 
      {
          if (Logger.log == null) {
            Logger.log = new Singleton ();
          }
          return Logger.log;
        }

    Design patterns are an extensive topic you could write about for hours. My aim was just the give you a thorough insight into that issue without going to deep and making it more complex than necessary.

    To have basic ability in using those patterns is also important ’cause when discussing with other programmers you don’t want to discuss the whole logic you’ll write you just want to discuss about a certail technical term and if it matches to solve the given problem.

    Here you can buy Head First Design Patterns published by O’Reilly on Amazon.com

    post Simple XOR Crypter

    February 13th, 2008

    Filed under: C++, General Programming — Kai @ 8:07 pm

    Exclusive or is a type of logical disjunction on two operands that results in a value of “true” if and only if exactly one of the operands has a value of “true”.

    The truth table is as follows:

    a | b | a XOR b
    —-+—-+———
    0 | 0 | 1
    0 | 1 | 0
    1 | 0 | 0
    1 | 1 | 1

    • 1 xor 1 = 0
    • 1 xor 0 = 1
    • 1110 xor 1001 = 0111

    XOR can be used to swap two numeric variables, using the XOR swap algorithm; however it’s regarded as more of a curiosity and not encouraged in practice.

    As you know ^ declares XOR in C/C++.

    void XorSwap(int* x, int* y)
    {
        if (x != y) {
            *x ^= *y; // the right-most expression
            *y ^= *x; // the middle expression
            *x ^= *y; // the left-most expression
        }
    }

    A reson why you’d better avoid excessive use of XOR is that on modern CPUs, the XOR technique is considerably slower than using a temporary variable to do swapping. One reason is that modern CPUs strive to execute commands in parallel. In the XOR technique, the inputs to each operation depend on the results of the previous operation, so they must be executed in strictly sequential order.

    XOR can simply be used for an easy to understand encryption algorithm.
    In an XOR encryption program each letter of the key and the input(e.g text) gets converted to ascii, then to binary (0’s and 1’s). The 0 or 1 from the key is xored against the 0 or 1 of the text.

    Consider that function:

    string XOR(string value,string key)
    {
        string retval(value);
     
        short unsigned int klen=key.length();
        short unsigned int vlen=value.length();
        short unsigned int k=0;
        short unsigned int v=0;
     
        for(v;v<vlen;v++)
        {
            retval[v] = value[v] ^ key[k];
            k=(++k < klen ? k : 0);
        }
     
        return retval;
    }

    It can be used like this:

    string value("Hello World");
    string key("key");
     
    cout << "Plain text: " << value << "\n\n";
    value = XOR(value,key);
    cout << "Cipher text: " << value << "\n\n";
    value = XOR(value,key);
    cout << "Decrypted text: " <<value << std::endl;

    XORing is used in many cryptographic algorithms to produce a ciphertext from the key and plaintext - especially in so-called “stream ciphers”.
    You might have noticed that this encryption is similar to Vigenère Cipher method and basically an enhanced version of it. XOR encryption takes the result of XORing the ascii number of the value and the number of the key value to produce a crypted value. Vigenère Cipher takes the result of adding (modulo 255) the ascii number of the value to the ascii number of value to produce a crypted value. That’s the reason why XOR encryption is more attractive than the addition function XOR is a symmetric operation, whereas addition is not.

    If you’d like to use XOR encryption I would therefore advice you that function, cause it’s valid C++ and uses a template. You don’t have to care about datatypes you like to crypt/encrypt.

    template<typename>
    void BetterXor(const T& value, const T& key, T& result)
    {
       typedef unsigned char byte;
     
       const byte* pvalue = reinterpret_cast<const>(&value);
       const byte* pkey = reinterpret_cast<const>(&key);
     
       byte* pResult = reinterpret_cast[byte*](&result);
     
       for( size_t i = 0; i < sizeof(value) && i < sizeof(key); ++i )
          pResult[i] = pvalue[i] ^ pkey[i];
    }

    Nevertheless if you need strong encryption, DO NOT USE XOR algorithms. If true security is an issue then you will want to use something else.

    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.

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