Blogs

Paul Kimmel's Blog

October 2009 - Posts

  • Professional DevExpress ASP.NET Controls

         

    After many months of hard work and a lot of input from some very creative and smart people I got the word that the book is coming off the presses and should be ready the first week of November. The code has been published on the Wrox website at http://www.wrox.com/WileyCDA/WroxTitle/Professional-DevExpress-ASP-NET-Controls.productCd-0470500832,descCd-DOWNLOAD.html. If you download and start using the code before you get your copy of the book, I will be respond to inquiries at paulk@devexpress.com.

    Be one of the first five people to spot a copy of the book in your local bookstore and blog about it, and I will send you a free autographed copy of my next book. Of course, you have to blog about it, tell me where you saw the book, let me know you blogged about it, and send me your snail mail address.

    I will be at PDC in Los Angeles. Bring me your copy of the book to sign and I will hook you up with some great DevExpress swag.

    Paul

  • Did You Know?

         

    I read and re-read help documentation, white papers, blogs, and tweak and poke around code to find out what is hiding in the crevices. Today I found something that I don’t think I have seen before. You probably know of course that you can define anonymous types with initializers in VB, as shown here:

    Dim company = New With {.CustomerID = "PAULK", .CompanyName = "Kimmel's Konfections"}

    The preceding code will cause the compiler to generate a class and the names in the initializer list—CustomerID and CompanyName—will be added as properties to the class. The type of these properties will inferred by the values assigned to them.

    Did you know that you can nest anonymous type initializers? By using the same notation in the initializer list you can specify nested anonymous types. The following code defines an anonymous class containing a CustomerID and CompanyName and a nested type containing a phone number.

    Dim company = New With {.CustomerID = "PAULK", _
        .CompanyName = "Kimmel's Konfections", _
          .Phone = New With {.Number = "(517) 555-1212"}}

    If you write the class to the console you can see the contents as they are logically laid out (see Figure 1). If you look at the anonymous type in Reflector then you can see that the very short statement generates a complete class with, in this case, a nested class (see Figure 2).

    image 
    Figure 1: The layout of the anonymous type shows that Phone is a nested type.

    image
    Figure 2: The anonymous type with the nested type assigned to Phone.

     

  • Lambda Expressions in VB

         

    Lambda expressions in VB are more verbose than their C# equivalent. You define a Lambda expression by using just the Function keyword the, the argument parameters, optionally the data type, and a statement that returns a value. The is no function name, no return type specified—the return type is implicit—and no Return keyword or End Function line. A Lambda expression must be a Function (not a Sub), and syntactically they look like compressed functions. Similar to the help file’s example here is a simple Lambda Expression that adds sales tax to a value.

    Function(value As Decimal, tax As Decimal) _
                            value * (1 + tax)

    You could certainly define a regular function, but Lambda expressions have some utilities that regular functions won’t support. You can’t define a nested function, but with Lambda expressions you can define a Lambda expression—a function for all intents and purposes—inside of another function. Nesting functions is probably not that useful in and of itself. More importantly Lambda expressions can be used to support a flexible style of programming by permitting you to pass Lambda functions as arguments to other functions, in effect, changing the behavior of the called function. Listing 1 demonstrates how to invoke the extension method Where—for IEnumerable(Of T) types. The Where method accepts a generic delegate Func(Of String, Boolean) which can be satisfied by a Lambda expression.

    Listing 1: The Lambda expression in the Where method accepts a string and returns a Boolean indicating if the input string starts with the letter ‘A’.

    Module Module1

      Sub Main()

        Dim names() As String = {"Paul", "Noah", _
                                 "Alex", "Ashton"}

        Dim NamesThatStartWithA = _
          names.Where(Function(n) n.StartsWith("A"))

        For Each name In NamesThatStartWithA
          Console.WriteLine(name)
        Next

        Console.ReadLine()
      End Sub

    When you see methods that have arguments like predicate As System.Func(Of String, Boolean) then you know that you can use a Lambda expression. You can also assign a Lambda expression to a local variable and pass the variable to satisfy the argument. Of course part of the benefit of things like Lambda expressions is to compact code. Listing 1 can be re-written without the extra local variable, NamesThatStartWithA, as demonstrated in Listing 2.

    Listing 2: Tighten the code up, which of course is a benefit of Lambda expressions-doing more with less.

    Module Module1

      Sub Main()

        Dim names() As String = {"Paul", "Noah", _
                                 "Alex", "Ashton"}

        For Each name In names.Where(Function(n) n.StartsWith("A"))
          Console.WriteLine(name)
        Next

        Console.ReadLine()
      End Sub

    Have fun with Lambda expressions There are a clever idiom rediscovered-probably by a math major at Microsoft-based on a 1930s notation of the same name. (The C# notation is closer to the mathematical notation.) To explore uses for Lambda expressions look at some code you have already written a rewrite it using Lambda expressions where you can.

  • Learn C++, or at Least Learn From It

         

    C++ was invented at AT&T Bell Labs and introduced as C with Classes around 1986. This time frame coincidentally coincides with the approximate availability of PCs to the general public. If you read Bjarne Stroustrup's Biography of this time period—The Design and Evolution of C++—then you will learn that C with Classes was dubbed C++ and released right around 1990. The use of the ++ operator in the name is a play on the idea that C++ is an iteration of C.

    The benefit of learning C++ is not that C++ is the best language or even the right language in all scenarios. In fact for many kinds of applications other languages may likely let you develop applications at a lower cost. No, the benefit of learning C++ is that C++ is an extraordinarily rigorous language. The rigors of learning the C++ language is like the rigors of any intensive training: one gets a more finely-tuned result. Here is another reason for learning C++. Because C++ was an early PC language a lot original object-oriented material was demonstrated and though of in the context of C++. In short, design patterns, folks, refactoring folks, analysis and design folks were all probably string C++ developers. Some of the most esoteric and powerful algorithms have been written about and demonstrated in C++ first—for example, read James Coplien’s Advanced C++ Programming Styles and Idioms book for some mind bending algorithms.

    If you don’t necessarily have the time to take the 18 months or so it can take to learn the fundamentals of and write C++ then spend a little time becoming familiar with the basic grammar and syntax. Follow the study of the language through its grammar and syntax with the study of books on algorithms, idioms, object-oriented patterns and refactorings, and analysis and design concepts. You will find that studying this rigorous language—C++—and the literature that ensued will prepare you to master every other, less rigorous object-oriented language.

    Of course, this is all opinion. However, because C++ is arguably the most rigorous language, its study prepares you thoroughly for less rigorous languages. Studying the material that ensued—the books in literature—contain information that applies to other less rigorous languages, like VB.NET and C#, and will help you use these other languages at a higher level.

  • Block Pesky Text Messages with Alltel/Verizon

         

    Have you ever gotten text messages that you didn’t want to receive? Well, if you have unlimited text then there is no charge, but the trilling or buzzing of a message indicator can be a nuisance. It seems that this is a no-brainer service that phone companies should provide, but it seems to be a closely guarded secret. I have Alltel, which is now Verizon and it does appear you can manage mobile phone to phone text by sending 8888 text messages.

    If you put 8888 in the to line and the command in the body of the message you can better manage text messages. For example,

    • Block: B 5175551212 sent to 8888 -  (note the space) then messages sent from that 10-digit number after the B are blocked
    • List: Send L to 8888 and you will get a message indicating the numbers that you have blocked
    • Unblock: Send U followed by a 10-digit number and you can unblock messages.

    I got a response to a B command and an L command, so it looks like this works. You can also manage email to text blocks online at alltel.com.

    If you have another provider then you will have to contact your provider for provider-specific information. It took me a while to find text messaging management commands for my phone/provider, but ain’t Google grand.

  • How LINQ is Like a For Loop

         

    One of the best ways for me to understand something (relatively) new is to figure out how its like something else, the role it plays as something new, and how to use it. Language INtegrated Query (or LINQ) is a relatively new thing. Let’s step back and look at some existing code that is a ubiquitous staple (see Listing 1).

    Listing 1:  A basic for-loop that copies a desired subset of items from collection to another.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace CompareLinqToForLoop
    {
      class Program
      {
        static void Main(string[] args)
        {
          int[] integers = {1,2,3,4,5,6,7,8,9};

          List<int> results = new List<int>();
          for (int k = 0; k < integers.Length; i++)
            if (integers[k] % 2 == 0)
              results.Add(integers[k]);

          Array.ForEach(results.ToArray(), r => Console.WriteLine(r));
          Console.ReadLine(); 
        }
      }
    }

    The code is trivial but it demonstrates a basic use of a for-loop. The code starts with an array of integers. A new target object, the generic List is created to receive the desired subset. The for-loop iterates over the source collection of integers, tests each element—and in this case the even integers—and places them in the target List. In a general sense the for loop iterates over items and performs an operation on them. In this specific example the operation is to copy selected items to a new subset, the generic List.

    LINQ performs a very similar role to the for loop and subset generator. Instead of specifically creating the target object, defining the for loop, and a separate test, LINQ supports all of these operations in an integrated way. I don’t mean to downplay the value of LINQ or oversimplify it, but if you use this knowledge as a basic starting point—for loop, subset collection generator—then LINQ is pretty approachable. Using LINQ the code in Listing 1 can be re-written as follows (see Listing 2):

    Listing 2: Selecting a subset of objects using LINQ.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace CompareLinqToForLoop
    {
      class Program
      {
        static void Main(string[] args)
        {
          int[] integers = {1,2,3,4,5,6,7,8,9};

          var results = from i in integers
                       where i % 2 == 0
                       select i;

          Array.ForEach(results.ToArray(), r => Console.WriteLine(r));
          Console.ReadLine(); 
        }
      }
    }

    The from clause is the equivalent of the for-loop. The value right after the from keyword is called the range value. The range value plays the same role as the iterator variable in the for-loop. The range variable is i in Listing 2. The value after the in keyword is the source collection. The where clause plays the role of the test. In Listing 1 an if-conditional is used; in Listing 2 the where clause plays the same role. The where clause in LINQ works and looks like a SQL where clause. Finally, the select clause performs the role of copying the desired target objects. The term often associated with the select clause is projection. The term projection is used when you apply the new keyword in the select clause to define a new type. In the example the select clause is simply accumulating the integers that pass the test in the where clause.

    The result of the LINQ query is an IEnumerable<T> object where T in the example is an integer. The result of the LINQ query plays the role of the instantiated List<T> in Listing 1. The var keyword is used to support an unknown, or anonymous, type. You can define the return type on the left side of the equal, but you don’t have to. The reason you want to use var besides that it requires less typing is because LINQ let’s you project a new, as yet undefined, anonymous type.

    Anonymous types is where LINQ starts to become really powerful. Suppose you have a class of employee objects and you want a subset of those employee objects, containing just the employee name and phone number, a contact list. Historically, you would have the Employee class, define a new class containing the name and number fields, and then use a for loop to move the data from the source Employee collection to a collection of instances of the new type. With LINQ you don’t have to define the new type—containing name and number. You can define the new type in the select statement with the new keyword, and simply specify just the values for the projected new type. At its essence LINQ is like a for loop. However, because you can define new types in the select clause on the fly you can avoid defining all of those extra classes that are used for lookups, reports, or to answer user queries.

    If you are just getting started with LINQ, think: from is a for-loop, where is the test, and select is the operation performed for each iteration of the loop. If you need a new type don’t define the class explicitly define it in the select clause. (For more information on LINQ you can check out my book LINQ Unleashed for C# or look at some of the LINQ examples in my upcoming book Professional DevExpress ASP.NET Controls. (The DevExpress doesn’t emphasize LINQ, but there are some LINQ examples.)

  • Intellisense for Your JavaScript with XML Comments

         

    When I first started in IT in 1987 at Underwriters, Safety & Claims in Louisville, Kentucky the PCs were just getting interesting. I was the only one that worked the second shift. My job was backing up mini-computers for the most part. In those days this still was a chore. I made a whopping $7.50 per hour. What was best about this job is that I had a lot of free time to study, access to a wide variety of computers, and Don Gardener and Mike Groher let me write some code. See, the Databus machines running Sunbelt routinely ran out of hard disk space and we’d re-write the code during long running batches to send data to another drive or fix small bugs. (Those were the days.) That was fun. In actuality what got me hooked was Quattro Pro 1, 3D charts, and the new 386SX graphics chips we got for our PCs.

    In those days I spent $200 a month of my own money—remember I only made $300 a week—on computer books, books that I read cover to cover. These days I read a lot, but it is the rare book I have time to read from cover to cover. The reason for this is that I spend a lot of my free time writing books, and the reading is done pretty quickly, usually to research new topics. When writing books one is usually writing about a topic that doesn’t exist in book form as widely, which means the research is white papers, blogs, and technical manuals. I still read a lot, but it is hard to find the time to read a 1,000 page book cover to cover. However, if you are just getting started in IT, reading is the best way to learn about programming and computers. Better in some ways than college courses, for the obvious reason that college curricula follow technology but seldom lead it. Balancing books with the rigor of a college education and the discipline that requires is a wonderful balance though.

    We can’t quite write about VS2010 because it is still in beta and features are evolving and protected, but you can learn about VS2008. A cool feature of VS2008 is extended Intellisense and XML comments for JavaScript. If you put your JavaScript in separate .js files and add XML comments—inside of the functions—then VS2008 will show consumers of those functions extended comment information as they are using those .js files. The following simple hello world function shows you where to place the comment—see Listing 1—and the Figure 1 shows you how Intellisense displays that information when a user is picking through commented functions.

    Listing 1: A JavaScript function with an XML comment.

    function HelloWorld() {
        /// <summary>XML Comments are supported in VS2008</summary>
        alert("Hello World!");
    }

    image
    Figure 1: You can see the extended Intellisense summary displayed as I scrolll through available functions.

    To reference the external .js file add script reference with the src attribute set to the external script file as shown in Listing 2.

    Listing 2: Link to the external script file with the src attribute of the script tag.

    <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <script src="HelloWorld.js" type="text/javascript"></script>
        <script type="text/javascript">
            HelloWorld();
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
        </div>
        </form>
    </body>
    </html>

    Perhaps an interesting development we at DevExpress have to figure out is how to incorporate that Intellisense capability into our Client-Side Events Editor (see Figure 2). That would be cool.

    image
    Figure 2: Our client-side script editor is an easy way to add client-side script to our ASPx controls.

More from DevExpress
Live Chat
Have a pre-sales question?
Need assistance with your evaluation?
We are here to help.
Chat is one of the many ways you can contact members of the DevExpress Team. We are available Monday-Friday between 8:30am and 5:00pm Pacific Time.
If you need additional product information, require pre-sales assistance, or want help with your order, write to us at info@devexpress.com or call us at
+1 (818) 844-3383.