rulururu

post SP 1 (Beta) for Visual Studio 2008 and .NET Framework 3.5

May 14th, 2008

Filed under: .NET, Visual Studio — Kai @ 1:33 pm

As I recently have experienced a few days ago the first beta version of the service pack 1 for Visual Studio 2008 and .NET Framework 3.5 have been released.

The release of the final version is announced for summer.

This servicing updates provide a roll-up of bug fixes and performance improvements.
Furthermore, additions and enhancements that make building .NET applications have become better.

The parts that provide development with C++/MFC won’t have many new features but C# development is said to be improved.

In any case you’d be aware of:

  • Users that have Windows Vista should have SP1 for Vista installed before upgrading the .NET 3.5 Framework with SP1.
  • Any users who still work with beta of Visual Studio 2008 (Codename Orcas I think) will get in trouble when trying to install the service pack. A detailed step-guide can be found here.
  • There is a change in behavior in the .NET 3.5 SP1 beta that causes a problem with the shipping versions of Expression Blend (WYSIWYG-Editor für XAML). The recommented way to work around this issue is to download the recently updated version of Blend 2.5.

At least bear in mind “be careful - it’s still beta form”. The usage on critical system is not recommented yet.

Scott Guthrie (Corporate Vice President der Microsoft Developer Division) has done a great blog post that shows the improvments in detail.
It can be found here.

The Visual Studio SP1 Beta is quite extensive and includes support for SQL Server 2008, new ADO.NET features, improvements to the WPF designers, WCF templates for Silverlight projects, debugger support for the .NET Framework public symbols and source release, control improvements and Visual C++ improvements such as the Office 2007 Ribbon bar.

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 Best Practice: Avoid using const on read-only variables

    April 22nd, 2008

    Filed under: .NET — Kai @ 9:59 am

    I often mention the blindfold use of readonly and const keyword in C#. In general you can say that const variables get the value assigned at Compile time and are unchangeable once established. In opposite to that readonly variable get the value assigned at run time and are unchangeable once established.

    A quick synopsis on the differences between ‘const’ and ‘readonly’:

    const

    • Can’t be static.
    • Value is evaluated at compile time.
    • Initiailized at declaration only.

    readonly

    • Can be either instance-level or static.
    • Value is evaluated at run time.
    • Can be initialized in declaration or by code in the constructor.

    For a const thist would be typical:

    public class MyClass
    {
      public const double PI = 3.14159;
    }

    PI cannot be changed in the application anywhere else in the code as this will cause a compiler error.

    Constants must be of an integral type (sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, or string), an enumeration, or a reference to null.

    Constants can be marked as public, private, protected, internal, or protected internal.

    As mentioned above a readonly can be assigned at run time. Due to that this is allowed:

    public class MyClass
    {
      public readonly double PI;
     
      public MyClass()
      {
        PI = 3.14159;
      }
    }

    A C# guideline defines that the best practise is to avoid const on read-only variables, therefor use the readonly keyword.

    The reason why is very simple. Lets say you have the following code in a class library:

    public class ServiceClass
    {
        public const int MyConst = 12;
        public readonly int MyReadOnlyVar = 10;
    }

    And you have the following code in another assembly calling the code above.

    ServiceClass service = new ServiceClass();
     
    int someValue = ServiceClass.MyConst;
     
    someValue = service.MyReadOnlyVar;

    You deploy both the class library and the assembly calling it. After deployment, a change is being made to the class library. you change the values of MyConst to 15 and MyReadOnlyVar to 15. You now release the class library and life is good. Is it?

    What’s the values of someValue in the two statements below after the second release of the class library?

    int someValue = ServiceClass.MyConst;
     
    someValue = service.MyReadOnlyVar;

    Initially, when the compiler sees the line

    int someValue = ServiceClass.MyConst;

    it replaces ServiceClass.MyConst with 12.

    At runtime the class library is not called for the value since it is a constant. As a result of this, the code calling into the class library is not aware that the value of ServiceClass.MyConst has changed. It will continue to use the old value 12 while the new value of MyConst is 15.

    post Book Recommendation: XAML in a Nutshell

    April 16th, 2008

    Filed under: .NET, Books, WPF — Kai @ 7:34 pm

    XAML in a NutshellToday I’d like to recomment a book to you. It’s called XAML in a Nutshell (O’Reilly, 2006; ISBN: 0596526733) by Lori A. MacVittie.

    For those of you who don’t know already XAML is a .NET technology. It’s a markup language that can be used to help create desktop applications, web pages, and printable documents.

    It stands for Extensible Application Markup Language and is pronounced as zammel ([zæ:mɛl]).

    XAML generally follows XML syntax rules, just as any other XML-based markup language does. Each XAML element has a name and one or more attributes. Attributes correspond directly to object properties, and the name of the XAML element exactly matches the name of a CLR class definition.

    XAML is pure markup, which means that while the names of event handlers are specified as attributes, you must implement the actual logic of the event handler in code. If you’re familiar with ASP.NET programming techniques, then you’ll be familiar with the term codebehind, which refers to the code “behind” a XAML interface element that is responsible for providing application logic such as event handlers.
    It can be implemented in either C# or VB.NET. In both cases, the code can be placed inline in the XAML file, although this contradicts best practices in separating the presentation and application logic layers.

    A XAML file can be compiled into a .baml (Binary XAML) file, which may be inserted as a resource into a .NET Framework assembly. At run-time, the framework engine extracts the .baml file from assembly resources, parses it, and creates a corresponding WPF visual tree or workflow.

    When used in Windows Presentation Foundation, XAML is used to describe visual user interfaces. WPF allows for the definition of both 2D and 3D objects, rotations, animations, and a variety of other effects and features.

    Here’s an overview of what to expect:

    • Introducing XAML
    • Getting Started
    • XAML Basics
    • Layout and Positioning
    • Resources
    • Storyboards and Animations
    • Elements
    • Controls
    • Shapes and Geometry
    • Layout
    • Animations and Transformations
    • Events

    Along with this, you get eight appendices covering the major parts of the XAML technology.

    This excellent book gives the reader a quick reference to XAML with examples. In other words, this book provides documentation of all core components and presents detailed discussions on features such as animation, resources, and layout that will help you on your way to becoming a XAML developer.
    Even if you’ve never before heard of XAML, this book will give a good starting point to begin your investigations into this new technology…

    The best comes last. You can get a preview online on google’s books: [link]

    post Basic but reusable: Reading CSV

    April 16th, 2008

    Filed under: .NET — Kai @ 9:54 am

    First, let’s recite the rules of CSV: Each line in a text file represents a record. The fields on each line are separated by commas.

    Generally a CSV file should be abide by this rules:

    • Each record is one line (with exceptions)
    • Fields are separated with commas
    • Leading and trailing space-characters adjacent to comma field separators are ignored
    • Fields with embedded commas must be delimited with double-quote characters
    • Fields that contain double quote characters must be surounded by double-quotes, and the embedded double-quotes must each be represented by a pair of consecutive double quotes.
    • A field that contains embedded line-breaks must be surounded by double-quotes
    • Fields with leading or trailing spaces must be delimited with double-quote characters
    • Fields may always be delimited with double quotes
    • The first record in a CSV file may be a header record containing column (field) names

    Take for example the next trivial CSV file:

    alice, bob, eve, trudy
    alice said: "don't move","""I won't"", he replied"

    The first line parses into four separate fields (”alice”, “bob”, “eve”, “trudy”). The second one is trickier, but it produces two values.

    The easiest implementation would be this:

    private void readFile(String filePath)
    {
      TextReader tx;
                try {
                    tx = new StreamReader(filePath);
                    String line;
     
                    while ((line = tx.ReadLine()) != null)
                    {
                        parseData(line);
                    }
     
                    tx.Close();
                } 
                catch(IOException ex) 
                {
                    Console.WriteLine(ex.Message);
                }
    }

    Can be simply used that way:

    private void parseData(String d)
    {
                String[] sepData = d.Split(',');
                foreach(String d in sepData)
                {
                    Console.WriteLine(d);
                }
    }

    And as you can guess, the code produces output like this:

    > alice
    > bob
    > eve
    > trudy

    Those are just basics but they are reusable in some projects.

    post Code nested inside a namespace?

    April 11th, 2008

    Filed under: .NET — Kai @ 7:38 am

    Recently I wondered if code should be always nested in a namespace or not.

    The question actually shouldn’t be which is “better” rather which is better for a particular case.

    using bar;
    namespace Foo {
      // etc
    }

    or

    namespace Foo {
      using foo;
      // etc
    }

    I don’t know how to answer the question “which is better?” because I do not know the intended purpose of the code. I therefore tried to think of ways that these could be different, and answer the question “how do these differ?”

    The answer is that if there is only one namespace in the file, it hardly matters. If there are two or more namespaces in the file, then put the directives you want shared amongst them at the top of the file, and the ones you do not want shared inside each the namespace. I further noted that having multiple top-level namespaces in the same file is a little weird, so maybe don’t even go there and make it a moot point.

    My first statement was not right. There is a way that these could be different that I forgot about. The first version is equivalent to

    using global::bar;
    namespace Foo {
      // etc
    }

    The second version is equivalent to

    namespace Foo {
      using global::bar;
      // etc
    }

    unless Foo contains a namespace called bar. In that case, it is equivalent to

    namespace Foo {
      using global::Foo.Blah;
      // etc
    }

    So there are at least two ways that things can get broken here. First, moving a not-fully-qualified directive from outside to inside (or vice versa) may cause a semantic change in the program. And second, if there is a not-fully-qualified directive inside the namespace which refers to a top-level namespace then adding a child namespace that collides with that name can introduce a semantic change in the program.

    Therefore my advice is:

    • have only one top-level namespace per file
    • if you choose to put using directives inside your namespaces then fully qualify them with the global alias qualifier

    If you take this advice then it really does not matter whether the directives go inside the namespace or outside; either way you will not accidentally break yourself by introducing a name collision.

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