Grounding.co.za

Technology information for IT specialists
Welcome to Grounding.co.za Sign in | Join | Help
in Search

Tech Talk with Brett Maytom

October 2007 - Posts

  • Understanding the IEnumerable and IEnumerator interfaces in C#

    In nearly every application you write, you will need to use a collection and an iterate to loop through all items in the collection.  Building a collection can be done by using arrays, collections and generic collections.  You can also create a class and build your own collection, however you will need to implement the IEnumerator and IEnumerable interfaces.

    The IEnumerable interface is simple as it has a simple method, GetEnumerator which returns an IEnumerator.  Thus the IEnumerable interface indicates the class or structure can be iterated through.  The actual plumbing of the collection is in the IEnumerator class, the interface is defined as follows:

        public interface IEnumerator
        {
            object Current { get; }
            bool MoveNext();
            void Reset();
        }

    In order to use the enumerator, one needs to call Reset as to move to the before the first item in the list.  In a loop the MoveNext() method is called and should it return true, a call to current is made to get the item from the collection.  When there are no more items in the collection, MoveNext() will return  false.

    The code below demonstrates the IEnumerator implementation code and is to assist you in learning the interface.  By no means is this production code as it lacks error checking and mimics what the System.Collection.ArrayList class does anyway.

    namespace Brett.Demo.Enumerations
    {
        using System;
        using System.Collections;
    
        class DemoEnumeration : IEnumerable, IEnumerator
        {
    
            
            #region IEnumerable Members        
            /// <summary>
            /// Implement the IEnumerable interface.
            /// </summary>
            /// <remarks>
            /// You will note that the GetEnumerator method was Explicitly defined on the 
            /// interface, thus preventing it being visible from other interfaces.
            /// </remarks>
            /// <returns>
            /// Return the IEnumerator, in this case the class supports the IEnumerator
            /// </returns>
            IEnumerator IEnumerable.GetEnumerator()
            {
                return this;
            }
            #endregion
    
            #region IEnumerator Members
            /// <summary>
            /// This property returns the current item in the collection.
            /// </summary>
            /// <remarks>
            /// An InvalidOperationException will be called if the Current
            /// property is called directly after a Reset and without a MoveNext().
            /// It will also throw the exeption if the MoveNext method has moved
            /// past all items in the list.
            /// </remarks>
            object IEnumerator.Current
            {
                get
                {
                    if (_cursor >= 0 || _cursor < _items.Count - 1)
                    {
                        return _items[_cursor];
                    }
                    else
                    {
                        throw new InvalidOperationException();
                    }                
                }
            }
            /// <summary>
            /// Attempt to move to the next item in the collection
            /// </summary>
            /// <returns>
            /// True if another object exists, otherwise false to
            /// indicate that there are no more items in the collection.
            /// </returns>
            bool IEnumerator.MoveNext()
            {
                if (_cursor < _items.Count - 1)
                {
                    _cursor++;
                    return true;
                }
                else
                {
                    return false;
                }
            }
    
            /// <summary>
            /// Moves the cursor in the collection to before the first item.
            /// A call to MoveNext() needs to be made to move to the first item
            /// in the collection.
            /// </summary>
            void IEnumerator.Reset()
            {
                _cursor = -1; 
            }
    
            #endregion
    
            private int _cursor;            //Keep track on which item on in the enumerator.
            private ArrayList _items;       //Store the  items
    
            /// <summary>
            /// A default constructor to initialize the underlying collection
            /// </summary>
            public DemoEnumeration()
            {
                _cursor = -1;
                _items = new ArrayList();
            }
    
            /// <summary>
            /// Add an item to the collection.
            /// </summary>
            /// <param name="o">The item to add to the collection</param>
            /// <returns></returns>
            public int Add(object o)
            {
                return _items.Add(o);
            }
            
            /// <summary>
            /// Returns the number of items in the collection.
            /// </summary>
            public int Count
            {
                get { return _items.Count; }
            }
        
    
        }
    
        /// <summary>
        /// The demonstration application.
        /// </summary>
        class Program
        {
            static void Main(string[] args)
            {
                //Create a collection and populate with some items
                DemoEnumeration numbers = new DemoEnumeration();
                numbers.Add(3);
                numbers.Add(6);
                numbers.Add(9);
                numbers.Add(12);
    
                //Looping the hard way, through the interface
                IEnumerator e = numbers;
                //Loop through the collection                        
                while (e.MoveNext())
                {
                    Console.Write("{0} ", e.Current);
                }
                //Go to the begining of the list
                e.Reset();
                Console.WriteLine();
    
                //Looping the easy way, using the foreach statement
                foreach (int i in numbers)
                {
                    Console.Write("{0} ", i);
                }
                Console.WriteLine();
            }
        }
    }
    
    Posted Oct 30 2007, 10:22 PM by Brett with no comments
    Filed under: ,
  • How your browser finds and downloads a web page

    image

    As a programmer entering the ASP.NET development field, it is important to have a basic understanding of how your browser actually downloads and retrieves a web page.

    Glossary of terms

    http

    Http stands for hypertext transport protocol and defines how a hypertext aka HTML is requested or a post made to a server is sent.  It thus defines the protocol (language) of getting pages, putting in query strings and even submitting forms.

    Web Server

    A web server is a computer that provides hypertext aka HTML on the Internet allowing users to view it in a Web Browser.

    IIS

    Internet Information Server is web server application made by Microsoft that ships part with Windows Servers.

    DNS

    A Domain Name Service is used to resolve a human readable name to an IP address.

    Browser

    A browser is a software product capable of requesting web pages written in HTML from a web server and displaying them on screen.  The browser can also process multi media pages and other types of documents.

    IP Address

    Every computer on the Internet has a unique number called an IP address.  IP stands for Internet Protocol. 

    TCP/IP

    Transmission Control Protocol (TCP) is the mechanism used to format requests and responses to a server and ensure reliable delivery of data.

    Socket

    A socket is a connection from a client computer to a server computer using TCP/IP.

    Port

    A server may host many protocols such as ftp, http, smpt, pop and many more.  Each service needs to be uniquely distinguished by a number called a port.  The default port for a web server is 80 and not necessary to type into the URL.  Some administrators may change this port number for security or other reasons.

    URL

    A Uniform Resource Location is what is typed in a browser to request a resource on the internet.  The format is

    <protocol>://<host>[:port][<path>][?<query>]

    Viewing a web page

    Let us walk through what happened when you typed http://www.grounding.co.za in your browser

    image

    1. You opened up your browser, e.g. Internet Explorer, Mozilla and typed in the URL to the web page to view.  As mentioned lets use http://www.grounding.co.za, however the process is the same for every other web site.
    2. The browser does not know the IP address of the server www.grounding.co.za and needed to resolve the address by using the DNS Servers hosted on the Internet.  When resolving a name, the browser connects to a well known root server and starts resolving the URL in a backward method, i.e. za.co.grounding.www.  The browser queries the root server where the za sever is.
    3. The browser then queries the za server for the co sever.
    4. The browser queries the co server grounding server.
    5. The browser then queries the grounding server for the www server.
    6. The browser then requests the page from the browser.
    7. The browser starts processing and displaying the HTML page and should if find the page has graphics, js and css files in it, the browser will then connect the the www server and request and download each resource.

    Processing a static web site

    The

    image

    1. The user types in a URL or clicks on a hyperlink and the server resolves the IP address of the server using DNS.
    2. The browser establishes a connection with the web server and requests a page using the http get protocol.  Should the request not include a page name, the web server will return the default file, index.htm in the above example
    3. The HTML of the page is returned to the browser.
    4. The browser starts rendering the HTML and realises there is an image in the <img> tag.  The browser then requests the image.
    5. The browser will continue to request all other images, multimedia, javascript and css files from the server until the page is fully rendered.
  • Fixing "This program cannot display the webpage" error for CHM Files

    I was busy demonstrating how to create a .CHM help file from XML documentation in some C# code using Sandcastle.  Is saved the file into a directory C:\Demos\C#\XMLDoc.  When I opened up the .chm help file, the error below was shown:

    image

    With a bit of searching, I found the answer:

    .chm Files do not like the # ? & and + characters in the pathname.

    I renamed the C# folder to CSharp, i.e. C:\Demos\CSharp\XMLDoc and it worked.

  • Object Orientation - Objects

    In previous articles we have learnt about classes and that a class defines the item we are discussing.  A customer for example does have properies, fields and methods; however it does not not define any customer.  A class therefore provides a mechanism to describe an item, but does not define any real item.  It is thus a blueprint.

    In order to create a real customer one has to create an instance of a class and reference it through a variable name.  When creating an instance of the class an object is created in memory.

    The line of code below declares a variable theCustomer of data type Customer.  Initially the variable is set to a value of null.  A null variable means there is no real customer, however it is capable of storing a customer

    Customer theCustomer;

    The code below uses the new keyword to create an object in memory of type Customer. This then sets the variable theCustomer to reference the new object.

       theCustomer = new Customer();

    Example

    The following example creates three different customer objects in memory and uses them by calling properties and methods.

    namespace BrettM.Training.OO.Objects
    {
        using System;
    
        /// <summary>
        /// The customer class defines a business client that purchases
        /// products and services from our company.
        /// </summary>
        class Customer
        {
            #region // Fields
    
            /// <summary>
            /// A field variable to hold the customers name
            /// </summary>
            private string _name;
    
            #endregion
    
            #region // Properties
    
            /// <summary>
            /// The name of the customer
            /// </summary>
            public string Name
            {
                // The get accessor to return the name field
                get { return _name; }
                // A set accessor to change the name field
                set { _name = value; }
            }
    
            #endregion
    
            #region // Methods
    
            public void Print()
            {
                Console.WriteLine("Customer details");
                Console.WriteLine("----------------");
                Console.WriteLine("Name: {0}", this.Name);
                Console.WriteLine();
            }
    
            #endregion
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                //Create a variable of type customer
                Customer theCustomer;
                // Create an instance of the class
                theCustomer = new Customer();
    
                // Create the customer one object
                Customer one = new Customer();
                one.Name = "Mr Tom Jones";
    
                // Create the customer two object
                Customer two = new Customer();
                two.Name = "Mrs Sue Smith";
    
                // Create the customer three object
                Customer three = new Customer();
                three.Name = "Ms Sally Wilson";
    
                //Print out all customer details
                one.Print();
                two.Print();
                three.Print();
            }
        }
    }
    
    Posted Oct 10 2007, 06:37 AM by Brett with no comments
    Filed under:
  • Object Orientation - Classes

    As people we have the need to label things in order to classify and give meaning to things.  We label thinks such as customer, person, product, car, dog, cat.  In each item we label we can generally describe it by saying a customer has an account with us, buys products from us and pays for the product.  A customer must also have a name and an account number, we need to bill the customer and need a billing address.  In the English language, we use nouns to classify things. 

    However, in classifying things we are still generalising on the item.  For example, should we say "Please deliver the products to the customer.", in conversation we fully understand the statement and it makes sense.  However what customer, at what address and when?  What are the products to deliver and which product should we take from the same shelf of products (the one at the top or the one at the bottom)?

    In programming, we too classify the same things however there is a formal way of declaring items.  We create classes to classify many things in code.

    Some examples of classes

    • Customer, Product, Account, Address
    • Player, Enemy, High scores, Weapon
    • Page, Form
    • Country, Region, City
    • Button, Label, Dialog box

    Describing classes

    In each of the above example classes we could generally describe what each one should be and how it should behave.  We can also perform tasks on the class or even be made aware that some action or event has occurred.

    Classes can be described using

    • Properties
    • Fields
    • Methods
    • Events
    • and then some more in later topics
    Properties

    A property exposes characteristics or attributes of a classes, thus allowing us to set and retrieve information about the class.  For example, a customer may have property for their name and another for the account number.

    Properties may be read\write such as the telephone number of the customer which can be viewed or changed at any time.  Other properties may be read only in which we can only view the data but never change it, such as an account number.  Finally some properties may be write only where we could change it, however never view it; such as a password.

    The code below creates a simple read\write property for the customers name

    Methods

    Methods allow us to perform actions on the class and these actions typically describe some small business or system process.  These methods are normally defined by the verbs we use on the class.  We might perform actions on the customer such as Change Details, Suspend, Unsuspend, Remove, Change Address,  Log interaction, Fax, Bill, Accept Payment.  This list is endless and needs to be defined against what your application needs to do.

    The sample below implements a Print method to write the customers details to screen.

    Fields

    In our class we create properties and methods that interact with the data of the class, however we will need to define variables within the class to store the data.  Exposing our variables as properties in a class does not provide control as we cannot control read only, read\write and write only.  Secondly we can perform other actions such making the class aware that data has changed and it needs to be re-saved or even validated.  Sometimes we may even perform some simple calculations such as recalculating the total when either the quantity, unit price or discount changes.

    Events

    As we write more complex applications, the need for other system components being dependant on our class increases.  In many cases these other components would like to be notified whenever a certain event occurs. For example a button programmer will create a Click event to indicate a mouse press over the control.  A business class such as a customer may raise an event indicating the customer is overdrawn or credit limit reached.

    Once these classes have been defined and the events created, typically methods within the class will cause the event to be fired for example as the customer purchases products, the outstanding balance is increased by the amount of the purchase.  As soon as the outstanding balance is going to exceed the available credit the CreditLimitReached event is fired.

    Example

    The code below shows an example of a customer class with a Name property and field.  It also demonstrates a Print method.  In future lessons other components of a class will be explained.

    namespace BrettM.Training.OO.Classes
    {
        using System;
    
        /// <summary>
        /// The customer class defines a business client that purchases
        /// products and services from our company.
        /// </summary>
        class Customer
        {
            #region // Fields
    
            /// <summary>
            /// A field variable to hold the customers name
            /// </summary>
            private string _name;
    
            #endregion
    
            #region // Properties     
               
            /// <summary>
            /// The name of the customer
            /// </summary>
            public string Name
            {
                // The get accessor to return the name field
                get { return _name; }
                // A set accessor to change the name field
                set { _name = value; }
            }
    
            #endregion
    
            #region // Methods
    
            public void Print()
            {
                Console.WriteLine("Customer details");
                Console.WriteLine("----------------");
                Console.WriteLine("Name: {0}", this.Name);
            }
    
            #endregion
        }
    
        /// <summary>
        /// The test program
        /// </summary>
        class Program
        {
            static void Main(string[] args)
            {
                // Create a new object instance of the customer 
                // and set refer to it as 'cust'
                Customer cust = new Customer();
                // Set the name property
                cust.Name = "Mr Tom Jones";
                // Execute the print method
                cust.Print();
            }
        }
    }
    
    Posted Oct 09 2007, 12:40 PM by Brett with no comments
    Filed under:
  • Object Orientation - Abstraction

    Abstraction is a important software principal to generalise a class.  In everyday life you and I generalise by saying things like, I am going to the shops, I watched some TV, I sold some products or even I wrote a program.  It is not specific to a specific shop, or TV show or even a particular product brand; however we all understood the statements.

    When defining objects we often encounter similarities between different classes and in these cases we define abstract classes.  Take for example the following business where we sell products to customers.  On questioning what a customer is, we may realise that we sell either to companies and individuals. 

    A company has a registered name, trading as name, VAT number where a private person has a title, first and last name, a national identity number.  In this scenario we label and discuss both as “customer”, yet they are completely different.  One will also notice that there are common attributes such as a postal and delivery address, telephone number and account number.

    The simplified UML class diagram below represents the relationship:

    Abstract Customer Diagram

    There are benefits to using abstraction

    • The child classes automatically get all defined attributes of the parent class
    • Code duplication is reduced
    • The child class can be passed around as the parent class
    • Describes the business objects in a generalised form.
    Sample Code

    The sample code below implements the above UML diagram. 

    namespace BrettM.Training.OO.Abstraction
    {
        using System;
    
        abstract class Customer
        {
            #region // Fields
            private string _accountNumber;
            private string _telephoneNumber;
            private string _postalAddress;
            private string _physicalAddress;
            #endregion
    
            #region // Properties
    
            public string AccountNumber
            {
                get { return _accountNumber; }
                set { _accountNumber = value; }
            }
           
            public string TelephoneNumber
            {
                get { return _telephoneNumber; }
                set { _telephoneNumber = value; }
            }
    
            public string PostalAddress
            {
                get { return _postalAddress; }
                set { _postalAddress = value; }
            }
    
            public string PhysicalAddress
            {
                get { return _physicalAddress; }
                set { _physicalAddress = value; }
            }
        
            #endregion
        }
    
        class Person : Customer
        {
            #region // Fields
            private string _firstName;
            private string _lastName;
            private string _title;
            private string _nationalIdentityNumber;
            #endregion
    
            #region // Properties
            
            public string FirstName
            {
                get { return _firstName; }
                set { _firstName = value; }
            }
    
            public string LastName
            {
                get { return _lastName; }
                set { _lastName = value; }
            }
    
            public string Title
            {
                get { return _title; }
                set { _title = value; }
            }
    
            public string NationalIdentityNumber
            {
                get { return _nationalIdentityNumber; }
                set { _nationalIdentityNumber = value; }
            }
    
            #endregion
        }
    
        class Company : Customer
        {
            #region // Fields
            private string _registeredName;
            private string _tradingAsName;
            private string _registrationNumber;
            private string _VATNumber;
            #endregion
    
            #region // Properties
    
            public string RegisteredName
            {
                get { return _registeredName; }
                set { _registeredName = value; }
            }
    
    
            public string TradingAsName
            {
                get { return _tradingAsName; }
                set { _tradingAsName = value; }
            }
    
    
            public string RegistrationNumber
            {
                get { return _registrationNumber; }
                set { _registrationNumber = value; }
            }
    
    
            public string VATNumber
            {
                get { return _VATNumber; }
                set { _VATNumber = value; }
            }
            
            #endregion
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                Person theCustomer = new Person();
                theCustomer.Title = "Ms";
                theCustomer.FirstName = "Sue";
                theCustomer.LastName = "Jones";
                theCustomer.NationalIdentityNumber = "7805260565086";
                theCustomer.AccountNumber = "1234-5678-9876";
                theCustomer.TelephoneNumber = "+27 11 555-1234";
                theCustomer.PostalAddress = "PO Box 1235, Johannesburg, 2000";
                theCustomer.PhysicalAddress = "Flat 234, 342 Main Street, Johannsburg, 2001";
            }
        }
    }
    
    Posted Oct 09 2007, 01:34 AM by Brett with no comments
    Filed under:
  • Sandcastle September 2007 CTP released

    The Sandcastle CTP release was released on Tuesday 2 Oct 2007,  view the blog Announcing September 2007 Sandcastle Release post on the Sandcastle blog site.

    In a nutshell; Sandcastle is the tool to generates MSDN documentation form your .NET assemblies using reflection, a must for dev teams. 

  • Microsoft is releasing the Source Code for the .NET Framework Libraries

    OH My Greatness!  Well done MS!

    Scott Guthrie announced today that Microsoft will be releasing the Source Code for .NET Framework Libraries.  Read ScottGu's blog Releasing the Source Code for the .NET Framework Libraries .

    This is some awesome news as I am sure it will help with debugging and teaching developers good standards.  Secondly I think this will help improve the Framework base in years to come. 

    Posted Oct 04 2007, 06:26 AM by Brett with no comments
    Filed under:
More Posts
Add to Technorati Favorites
Powered by Community Server (Commercial Edition), by Telligent Systems
Afrigator