martes, 5 de diciembre de 2017

Understanding abstract classes with C#

The C# programming language enables a class designer to specify that a base class declares a method that does not supply an implementation. This is called an abstract method. The implementation of this method is supplied by the derived classes. Any class with one or more abstract method is called an abstract class.

Fig 1 UML model of the abstract class.

The purpose of an abstract class is primarily to provide an appropriate base class from which other classes can inherit and thus share a common design. However, abstract classes can have data attributes, concrete methods, and constructors. For example, the Vehicle class might include load and maxLoad attributes and a constructor to initialize them. Not all inheritance hierarchies contain abstract classes. However, programmers often write client code that uses only abstract base class types to reduce the client code's dependencies on a range of specific derived class types. The C# compiler always prevents you form instantiating an abstract class, for example the following statement is illegal.

 Vehicle v = new Vehicle(); // this is illegal and the compiler generates an error.

Although we cannot instantiate objects of abstract base classes, we will see that we can use abstract base classes to declare variables that can hold references to objects of any concrete classes derived from those abstract classes.

The employee abstract class: A example using Polymorphism through inheritance

What is polymorphism?

The term polymorphism refers to the ability of two or more objects belonging to different classes to respond to exactly the same message (method call) in different class-specific ways, thus polymorphism enables us to "program in the general" rather than "program in the specific".

Polymorphism allows:

  • Different behavoirs from the same type.
  • Runtime polymorphism is done via overriding.
  • Compile time polymorphism is done via method overloading.
  • Invoke methods of a derived class through a base class.
I think the best way to learn about this concept is through an example, so I wrote a set of examples using an inheritance hierarchy containing types of employees in a company.

Fig 2 Employee hierarchy UML class diagram.

We use abstract class Employee to represent the general concept of an employee. The classes that inherit from Employee are: CommissionEmployee, PieceEmployee and HourlyEmployee.

1. I use abstract class Employee to represent the general concept of an employee. The classes that inherit from Employee are: CommissionEmployee, PieceEmployee and HourlyEmployee.

Listing 1. Abstract base class Employee

In this example, class Employee will provide two methods Earnings and Details, and properties that manipulate an Employee's instance variables, the method Earnings certainly applies generally to all employee's, but each earnings calculation depends on the derived employee's class. So these two methods must be abstract in the Employee class because an implementation does not make sense there, so each derived class must override those methods with an appropriate implementation.

2. I wrote three concrete classes: HourlyWorker, CommissionWorker and PieceWorker. Such classes provide implementations of the abstracts methods declared in our abstract class, because abstract base classes are too general to create real objects.

Listing 2. Concrete derived class HourlyEmployee

Listing 3. Concrete derived class CommissionEmployee

Listing 4. Concrete derived class PieceWorker

To test our example, the following program creates an array of our abstract base class Employee, then assigns the four instances of our concretes classes to the array variable. Finally, the program iterates through array Employee and polymorphically invokes methods Earnings and Details to display the output of each of these methods.

Listing 5. Test program for our example.

Fig 3. The output for our example.

Note: Those examples were based on the examples included in: Deitel's developer series C# 2010 for programmers.

jueves, 30 de noviembre de 2017

The static keyword in C#

The static keyword declares members (attributes, methods) that are associated with the class rather than the instances of the class.

Sometimes it is desirable to have a variable that is shared among all instances of a class. For example, you could use this variable as the basis for communication between instances or to keep track of the number of instances that have been created.

You achieve this shared effect by making the variable with the keyword static. Such a variable is sometimes called a class variable to distinguish it from a member of instance variable, which is not shared.

Fig1. UML Object Diagram showing the Client class and two unique instances.

In this example, every object that is created is assigned a unique serial number, starting at 1 and counting upwards. The variable counter is shared among all instances, so when the constructor of one object increments counter, the next object to be created receives the incremented value.

A static variable is similar in some ways to a global variable in other languages.

Listing 1. Example marking the variable counter with the keyword static.

If a static is not marked as private, you can access it from outside the class. To do this, you do not need an instance of the class, you can refer to it through the class name.

Listing 2. Example referring to the static variable counter.

Sometimes you need to access program code when you do not have an instance of a particular object available. A method that is marked using the keyword static can be used in this way and is sometimes called a class method.

Listing 3. A method marked using the static keyword.

Fig 2. Output of the program is.

You should access methods that are static using the class name rather than an object reference.

Because you can invoke a static method without any instance of the class to which it belongs, there is no this reserved keyword applicable, because static variables and methods exist independently of any class objects, even when there are no objects of that class. The consequence is that a static method cannot access any variables other than the local variables, static attributes, and its parameters. Attempting to access non-static attributes causes a compiler error.

Listing 4. A complete example

Fig 3. Output for the complete example

You should be aware of the following when using static methods:

  • Inside the basic console application, we have the startup procedure Main. Main is defined as a static member, which means we do not have to have an instance of the enclosing class
  • Constants are considered static members. Therefore, they do not need to be-for that matter, they cannot be-marked with the static keyword.

miércoles, 27 de septiembre de 2017

Overriding Methods in C#

In addition to producing a new class based on an old one by adding additional features, you can modify existing behavior of the parent class.

If a method is defined in a derived class so that the name, return type, and argument list match exactly those of a method in the parent class, then the new method is said to override the old one.

The keyword virtual

In C#, a class can declare virtual methods, properties, and indexers, and derived classes can override the implementation of these function members.

The keyword virtual allows programmers to specify methods that a derived class can override, C# methods are non-virtual by default and must be explicitly declared as virtual.

The implementation of a non-virtual method is invariant: The implementation is the same whether the method is invoked on an instance of the class in which it is declared or an instance of derived class. In contrast, the implementation of a virtual method can be changed by derived classes.

The keyword override

To override a base-class method definition, a derived class must specify that the derived-class method overrides the base-class method with keyword override in the method header.

If the override modifier is not used, the new member hides the inherited member, and a compiler warning occurs. If a derived class attempts to override a non-virtual inherited member, a compiler error will occur. The following examples illustrate the using of virtual and override keywords.

Fig 1. Class diagram for Employee and Manager using Inheritance.

Listing 1: Sample code for Employee class

Listing 2: Sample code for Manager class

Consider these sample methods in the Employee and Manager classes:
Fig 2. The GetDetails method of the Employee class.

Fig 3. The GetDetails method of the Manager class.

The Manager class has a GetDetails method by definition because it inherits one from the Employee class. However, the original method has been replaced, or overridden, by the derived class’s version.

Listing 3 A simple program to demonstrate how method overriding works.

Fig 4 The output of executing this program is the following.

viernes, 15 de septiembre de 2017

Understanding Inheritance in C#

Inspired from biological modeling, inheritance allows new classes to be constructed that inherit characteristics (fields and methods) from ancestor classes while typically introducing more specialized characteristics, new fields, or methods. A subclass is logically considered to be a specialized version or extension of its parent and by inference its ancestor classes.

In programming, you often create a model of something, and then need a more specialized version of that original model.

Fig 1. Shows the UML class diagrams that model the Employee and Manager classes.

Listing 1. A possible implementation of Employee class.

Listing 2. A possible implementation of Manager class.

These codes illustrate the duplication of attributes between Manager class and the Employee class. Additionally, there could be a number of methods applicable to both classes. In object-oriented languages, special mechanisms are provided that enable you define a class in terms of a previously defined class.

One of its main mechanism is called Inheritance. Inheritance is a form of software reusability in which classes are created by absorbing an existing class’s data and behaviors and embellishing them with new capabilities. The next figure shows the diagram in which the Manager is a derived class of Employee base class.

Fig 2. Class diagram using Inheritance.

Listing 3. The Employee class.

Listing 4. The Manager class that inherits from class Employee.

Single Inheritance

The C# programming language permits a class to extend one other class only. This restriction is called single inheritance. With single inheritance, a class is derived from one base class. C# does not support multiple inheritance.

Once created, each derived class can become the base class for future derived classes. Typically, the derived class contains the behaviors of its base class. Therefore, a derived class is more specific than its base class and represents a more specialized group of objects.

The next image shows the base class Employee and three derived classes: Engineer, Manager and Secretary. The Manager is also the base class from which the derived class Director explicitly inherits.

Fig 3. An example Inheritance tree.

The Employee class contains three attributes (Name, Salary, and BirthDate), as well as one method (GetDetails). The Manager class inherits all of these members and specifies an additional attribute, department, as well as the GetDetails method. The Director class inherits all of the members of Employee and Manager and specifies a CarAllowance attribute and a new method, IncreaseAllowance.

domingo, 3 de septiembre de 2017

Fetching JSON Data with Angular $http.get() function.

Angular has built-in support for communication with remote HTTP servers and includes some low-level methods of fetching and posting the data. Angular comes with the $http service which includes a few methods we can utilize with all verbs of the REST protocol.

We'll look at a example using the .$http.get() request. The $http.get() method accepts two parameters: URL and config object.

The first parameter URL is always required and the config is optional, the shortcut $http.get() method initiates a GET request to the server to retrieve data from the server. This example has the following files:

  • books.js: it contains the data in JSON format.
  • app.js: it contains the functional logic for the example
  • getexample.html: contains the front for the example

Fig.1. The source code for the JSON file

Fig 2. The source code for the app.js

In the previous example the controller defines a dependency to the $scope and the $http module. An HTTP GET request to the data “books.json” endpoint is carried out with the get method. It returns a $promise object with a success and error method.

Fig 3. The code for the web page

Fig 4. Running the example

If you open the web page up in your browser, you'll see a standard HTML button created, when you press the button the $http service makes an ajax call and set response to the scope's property books. Thus books can be used to draw a list in the HTML page.

jueves, 10 de agosto de 2017

The this Reference

Every object can access a reference to itself, called the this reference. The this reference can refer implicitly to the instance variable, properties and methods of an object.

Two uses of the this keyword are:

  1. To resolve ambiguity between instance variables and parameters
  2. To pass the current object as a parameter to another method
The following class demonstrates these uses.

Fig 1 The Use of the this Keyword

The first constructor receives three uint parameters which names are identical to the instance variables of the class. I did this to illustrate explicit use of the this reference.

Fig 2 This reference output

The explicit use of the this reference can increase program clarity in some contexts where this is optional.

martes, 1 de agosto de 2017

(Windows Communication Foundation): Construir el proxy de manera programática

WCF es el marco de desarrollo de aplicaciones que agrupa las tecnologías distribuidas de Microsoft para la construcción de aplicaciones orientadas a servicios.

Fig 1 WCF agrupa las tecnologías distribuidas de MS en un solo marco de trabajo

WCF ayuda a construir aplicaciones orientadas a servicios de forma práctica

  • Proporciona herramientas para la creación, el consumo y la puesta en operación de los servicios.
  • Todas las funcionalidades son administradas por el runtime
  • No es necesario aprender o conocer a profundidad WSDL.
La arquitectura de WCF puede resumirse en el siguiente esquema.

Fig 2 Una vista general de la arquitectura de WCF

En este esquema se muestra los siguientes pasos de comunicación:

  1. Los clientes utilizan un objeto proxy para enviar mensajes al servicio. Este proxy se encarga de todo el mecanismo de comunicación y funciona como si fuera un objeto local.
  2. Los clientes envían mensajes y reciben respuestas mediante el uso de un Endpoint que los conecta con el servicio.
  3. Un servicio WCF utiliza un dispatcher para convertir el mensaje de petición en la invocación de un método en el servicio.
  4. Los servicios escuchan por los mensajes en uno o más Endpoints.

La estructura de un servicio WCF: El contrato y la implementación

Para ejemplificar cada uno de los componentes de la estructura estándar de un servicio WCF escribí un servicio conversor de temperaturas para convertir entre las diferentes escalas de temperatura: Celsius, Kelvin, Fahrenheit. Este servicio WCF conversor de temperaturas tiene los siguientes elementos:

1.Un contrato para el servicio: qué es la interfaz que define las operaciones y como es el proceso de comunicación para el intercambio de mensajes. Este contrato contiene los siguientes elementos:

a) La referencia al ensamblado System.ServiceModel, este ensamblado proporciona los objetos necesarios para construir los servicios WCF.
b) Una interfaz con el atributo ServiceContract que identifica a la interfaz que el servicio implementará.
c) El atributo OperationContract para identificar cada uno de los métodos que el servicio expondrá.
Fig 3 Código del contrato (Service Contract) para el servicio convertidor de temperatura.

2. La implementación del servicio: Es la clase que implementará la interfaz Service Contract, esta clase utilizará los componentes del .NET Framework con unos atributos WCF opcionales para controlar las características del servicio tales como el tiempo de vida y las sesiones.

Fig 4 Código de la clase de implementación de servicio (Service class)

Ambos archivos, (el contrato IGradeConverter y la implementación GradeConverterImplementation) deben compilarse como biblioteca :NET con el siguiente comando.

$ mcs /t:library -pkg:wcf IGradeConverter.cs GradeConverterImplementation.cs 
/out:Examples.WCFGradeConverter.Service.dll

El proceso huesped (Self-hosted application)

3. Un proceso huésped: Este proceso huésped debe proporcionar el ambiente de ejecución para un servicio WCF. Para hospedad un servicio WCF existen 3 opciones principales:

  1. Self hosted managed application
  2. IIS
  3. WAS

En este ejemplo utilizaré la opción Self hosted managed application.

Fig 5 Código del programa huésped WCF (Self-hosted).

Este proceso huésped requiere información de configuración, por lo que esta información se proporciona en un archivo de configuración.

Fig 6 El archivo App config del proceso huesped.

Para compilar el proceso huésped utilizamos los siguientes comandos:

 $ mcs -r:Examples.WCFGradeConverter.Service.dll -pkg:wcf GradeConverterHost.cs 
 

Construyendo el programa cliente GTK# temperature converter.

Para consumir el servicio WCF, escribí un proyecto cliente GTK# en Monodevelop que invoca las operaciones del servicio, en la siguiente imagen se puede ver la GUI del programa cliente.

Fig 7 El aspecto final del convertidor de temperaturas.

Fig 8 El proyecto y la GUI del convertidor de temperaturas GTK# en MonoDevelop

Hay dos maneras para que un cliente consuma un servicio WCF:

  1. Puedes generar un objeto proxy manualmente, utilizando la herramienta: svcutil desde la línea de comandos.
  2. Puedes usar la clase ChannelFactory para crear un proxy de manera programática.

Fig 9 Utilizando la clase Channel para crear un proxy

Para probar el ejemplo, primero hay que iniciar el proceso host.

Fig 10 Ejecutando el proceso host

Como último paso abrimos el proyecto cliente GTK# y lo ejecutamos desde Mono Develop

Fig 11 Ejecutando el programa desde Monodevelop y convirtiendo 100 grados celsius.

Fig 12 Ejecutando el programa y convirtiendo 451 grados farehnheit.