Developer .NET UPDATE—brought to you by Windows & .NET Magazine Network.
http://www.winnetmag.net


THIS ISSUE SPONSORED BY

Networking UPDATE Email Newsletter

SQL Server Magazine
(below DEVELOPER .NET PERSPECTIVES)


SPONSOR: NETWORKING UPDATE EMAIL NEWSLETTER

  • NEW! NEWS, TIPS, AND MORE TO KEEP YOUR NETWORK HUMMING

  • Networking UPDATE brings you the how-to tips and news you need to implement and maintain a rock-solid networking infrastructure. We'll explore interoperability solutions, hardware (including servers, routers, and switches), network architecture, network management, network security, installation technology, network training, and WAN disaster recovery. Subscribe (at no cost!) at:
    http://www.winnetmag.com/email/networking

    October 29, 2002—In this issue:

    1. DEVELOPER .NET PERSPECTIVES

    • Dynamically Calling Properties and Methods

    2. ANNOUNCEMENTS

    • Attend Our Free Tips & Tricks Web Summit
    • Try a Sample Issue of Exchange & Outlook Administrator

    3. NEW AND IMPROVED

    • Develop with Subscription-Based Component Collection

    4. CONTACT US

  • See this section for a list of ways to contact us.

  • 1. DEVELOPER .NET PERSPECTIVES
    (contributed by Tim McCarthy, timm@interknowlogy.com)

  • DYNAMICALLY CALLING PROPERTIES AND METHODS

  • Have you ever had to set an object's property value when you didn't know what property you were going to set until runtime? Have you ever needed to call an object's method, but you didn't know which object or which method until runtime? If so, you're in luck—you can use the Microsoft .NET Framework's System.Reflection namespace to dynamically load, inspect, and invoke properties and methods in assemblies.

    The key starting point for unlocking all this power is the Reflection.Assembly class. The Assembly class contains properties and methods for accessing .NET assemblies, which are either .dll or .exe files. Think of assemblies as containers of type definitions and resources. Assemblies are completely self-describing, which means that they contain metadata that describes their types (e.g., properties, methods, classes, classes' fields) and resources. Because of this feature, the Reflection namespace knows about an assembly's internals. The Reflection namespace makes type information available at runtime.

    Types are System.Type classes. In the .NET Framework, all objects and values are instances of System.Type. If you have a System.Type object, you can discover all of that type's members at runtime. For example, suppose you want to set the value of one of the Customer class properties, but you won't know which property to set until runtime. Here's a simple definition of the Customer class:

    \[Serializable\]
    public class Customer
    \{
       private string _firstName = "";
       private string _lastName = "";

       public Customer()
       \{
       \}
       public string FirstName
       \{
          get
          \{
             return _firstame;
          \}
          set
          \{
             _firstName = value;
          \}
       \}
       public string LastName
       \{
          get
          \{
             return _lastName;
          \}
          set
          \{
             _lastName = value;
          \}
       \}
       public void Save()
       \{
          XmlSerializer serializer = new
             XmlSerializer(this.GetType());
          // To write to a file, create a StreamWriter object.
          StreamWriter writer = new StreamWriter("Customer.xml");
          serializer.Serialize(writer, this);
       \}
    \}

    This code marks the class as serializable. In the Save method, the code serializes the class and writes it to the Customer.xml file, which gets created in the same directory in which the compiled code is running.

    To see this code in action, create a Console application in Visual C# .NET and copy the above code into the project. In the Main() subroutine, include code that retrieves a property's name and value, dynamically sets the property on the Customer class instance, then calls the Customer.Save() method to persist the values to the file. Here's what that code might look like:

    static void Main(string\[\] args)
    \{
       // 1. Get the property name from the user.
       Console.Write("Please enter a property name "
          + "(FirstName or LastName):  ");
       string propertyName = Console.ReadLine();

       //  2. Get the property value from the user.
       Console.Write("Please enter a property value for "
          + "previous property name (FirstName or LastName):  ");
       string propertyValue = Console.ReadLine();

       // 3. Create a Customer class instance.
       Customer customer = new Customer();

       // 4. Get the System.Type you need.
       Type customerType = customer.GetType();

       // 5. Get an instance of the PropertyInfo object based on
       // the type you just received from the assembly.
       PropertyInfo propertyInfo =
          customerType.GetProperty(propertyName);

       // 6. Dynamically set the value of the Customer object property.
       propertyInfo.SetValue(customer, Convert.ChangeType(propertyValue,
          propertyInfo.PropertyType), null);

       // 7. Save the Customer class's data.
       customer.Save();
    \}

    In Steps 1 and 2, the code simply retrieves the property name and property value that the user provided. In Steps 3 and 4, the code creates a new instance of the Customer class, then uses that instance to get a System.Type object representation (i.e., customerType) of the Customer class. In Step 5, the code uses the previously derived type to get a System.Reflection.PropertyInfo representation of the property of interest. In Step 6, the code calls the PropertyInfo instance's SetValue method and passes in three values: the Customer class instance, the user-provided property value, and null. The SetValue method uses the first two values to dynamically set the Customer class instance's property value. Note how the code wraps the user-provided property value with the Convert.ChangeType method to make sure that the value being passed in is the correct type. The null value lets the SetValue method know that no other optional property index values will be passed in. Finally, in Step 7, the code calls the customer.Save method to persist the Customer class's property value.

    This example is simple, but it effectively demonstrates the power and flexibility that System.Reflection provides. The process of dynamically calling a method is almost the same as the process of dynamically setting properties. The only differences are that you use the MethodInfo class instead of the PropertyInfo class and the Invoke method instead of the SetValue method. If you're interested in looking at the code for this project, email me at timm@interknowlogy.com.


    SPONSOR: SQL SERVER MAGAZINE

  • REGISTER TODAY! SQL SERVER SECURITY FOR .NE

  • Join Morris Lewis, Tues., Nov. 12 for a special one-hour presentation, "Designing SQL Server Security for .NET," brought to you by SQL Server Magazine. Learn how to adapt SQL Server security to support truly distributed applications. Tap into Morris Lewis' programming, network administration, database administration, and training expertise. Click here!
    http://www.sqlmag.com/sub.cfm?code=mlei322jdn

    2. ANNOUNCEMENTS
    (brought to you by Windows & .NET Magazine and its partners)

  • ATTEND OUR FREE TIPS & TRICKS WEB SUMMIT

  • Join us on December 19th for our Tips & Tricks Web Summit featuring three eye-opening events: "Disaster Recovery Tips & Tricks," "Intrusion Detection: Win2K Security Log Secrets," and "Merging Exchange Systems: Tips for Managing 5 Key Challenges." There is no charge for this event, but space is limited so register today!
    http://www.winnetmag.com/seminars/tipstricks

  • TRY A SAMPLE ISSUE OF EXCHANGE & OUTLOOK ADMINISTRATOR

  • If you haven't seen Exchange & Outlook Administrator, you're missing out on key information that will go a long way toward preventing serious problems and downtime for your enterprise. Get a free sample issue today, and discover tools you won't find anywhere else to help you migrate, optimize, administer, and secure Exchange and Outlook. Order now!
    http://www.exchangeadmin.com/sub.cfm?code=efei232jup

    3. NEW AND IMPROVED
    (contributed by Sue Cooper, products@winnetmag.com)

  • DEVELOP WITH SUBSCRIPTION-BASED COMPONENT COLLECTION

  • ComponentOne released ComponentOne Studio Enterprise, a comprehensive collection of grid, reporting, charting, data, UI, and e-commerce components for Visual Studio (VS), Visual Studio .NET, and ASP.NET developers. ComponentOne Studio Enterprise includes ComponentOne Studio (a collection of ActiveX components), ComponentOne Studio for .NET (a set of WinForms for the Microsoft .NET platform), and ComponentOne Studio for ASP.NET (a group of WebForms for enterprise ASP.NET development). ComponentOne Studio for ASP.NET is in beta and is expected to be available for download in fourth quarter 2002. A 1-year subscription to ComponentOne Studio Enterprise costs $899.95 and includes new product releases, updates, upgrades, select product betas, and email support. Contact ComponentOne at 412-681-4343, 800-858-2739, or sales@componentone.com.
    http://www.componentone.com

    4. CONTACT US
    Here's how to reach us with your comments and questions:

    This weekly email newsletter is brought to you by Windows & .NET Magazine, the leading publication for Windows professionals who want to learn more and perform better. Subscribe today.
    http://www.winnetmag.com/sub.cfm?code=wswi201x1z

    Receive the latest information about the Windows and .NET topics of your choice. Subscribe to our other FREE email newsletters.
    http://www.winnetmag.net/email