miércoles, 27 de septiembre de 2017

Python programming books

Python programming books in PDF format.

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.


Download the source code.

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.

Download source code

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.

Download the project for Visual Studio

viernes, 18 de agosto de 2017

PHP programming books

PHP programming books in PDF format.

Java programming books part II

Java programming books in PDF format. Part II

Java programming books

Java programming books in PDF format.

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.

Download the example source code

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.


Descarga el código fuente del servicio WCF

Descarga el código fuente del Self-hosted process

Descarga el código fuente del proyecto Cliente GTK#

viernes, 21 de julio de 2017

C# Networking Basics: Sockets

Socket is the name given to an abstraction through which an application may send and receive data. The term “Socket” refers to the Berkeley Sockets Interface, which was developed in 1978 for network programming with UNIX and was popularized by C programmers.

Because of the popularity of that abstraction, this term has been reused in many programming model including .NET technology. The main types of sockets in TCP/IP today are: stream sockets and datagram sockets, both use TCP as the end-to-end protocol with IP underneath, the .NET framework provides a clear distinction between using TCP and UDP, defining a separate set of classes for both protocols.

Stream Sockets

Socket based communications in C# employ stream sockets, when processes communicate over a network .NET Framework technology uses the streams model to establish a connection between two o more processes. With stream sockets, a process (running program) establishes a connection to another process.

A socket can hold two streams: one input stream and one output stream when the sender sends data to another process through the network by writing to the output stream associated with the socket, the receiver reads data written by the sender by reading from the input stream associated with the socket. While the connection is in place, data flows between the processes in continuous stream.

Addressing the connection

When you make a network connection, you need to know the address or the name of the remote machine, IPv4 uses 32 bit binary addresses to identify communicating hosts a client must specify the IP address of the host running the server program when it initiates the communication. In addition, a network connection requires a port number, after you connect to the proper host, you must identify a particular purpose for the connection. So, you can use a particular port number to communicate with the specific program.

Port Numbers

In TCP/IP port numbers are 16-bit numbers and the values range from 0-65535. In practice, port numbers below 1024 are reserved for predefined services, and you should not use them unless communicating with one of those services, client port numbers are allocated by the operating system to something not in use, while server port numbers are specified by the programmer, and are used to identify a particular service. Both client and server must agree in advance on which port to use. If the port numbers used by the two parts of the system do not agree, communication does not occur. Ports are divided into the following ranges:

  • 0-1023: well-known ports
  • 1024-49151: registered ports
  • 49152-65535: dynamic or private ports

Minimal TCP/IP Server

The System.Net.Sockets.TcpListener class is used to create server applications. TcpListener provides a simple wrapper around the socket classes, here is a simple TCP Server that accepts a single client connection.

Example 1: Implementing a network streaming server


To compile this program using mono, type the following command at your command prompt:
$ mcs /t:exe -out:SimpleTCPServer.exe SimpleTCPServer.cs
And to run it, type this command line:
$mono SimpleTCPServer.exe
And you’ll see the following output on your screen:

Fig 1: Result of running the SimpleTCPServer program.


Minimal TCP/IP Client

The client is a simple console application, this application uses the TcpClient class to connect to the running server, and receives the returned message.

Example 2: Implementing a client


To compile this program using mono, type the following command at your command prompt:
mcs /t:exe -out:SimpleTCPClient.exe SimpleTCPClient.cs
And to run it, type this command line:
$mono SimpleTCPClient.exe
And you’ll see the following output on your screen:

Fig 2: Result of running the SimpleTCPClient program.


Download the SimpleTCPServer source code.

Download the SimpleTCPClient source code.

viernes, 28 de abril de 2017

Utilizando la clase NpgsqlError de la enumeración NpgsqlException.Errors

Una forma precisa de diagnosticar los errores PostgreSQL en una aplicación :NET es mediante el uso de la clase NpgsqlError de la cual se pueden obtener detalles adicionales a la excepción generada esta clase esta incluida en la enumeración Errors la cual al recorrerse y consultar las propiedades de la clase NpgsqlError podemos obtener información específica acerca de los errores y advertencias que se generan al ejecutar los comandos SQL o Store procedures en PostgreSQL por medio de una aplicación .NET que haga uso del driver Npgsql.

A continuación mostramos una aplicación de consola que se conecta a una base de datos PostgreSQL, ejecuta un comando SQL para crear un nuevo registro en una tabla y envia la excepción generada hacia un archivo de texto.


Aquí el código para crear la tabla Books


Aqui el código de la clase Book



Aquí el código de la clase BooksManager


using System;
using System.Data;
using Npgsql;
using NpgsqlTypes;
using TestNpgsqlError;

namespace TestNpgsqlError
{
    public class BooksManager
    {

        public static int Insert(Book b)
        {
            var resp = 0;
            var commandText = @"INSERT INTO Books(title,numpages,pubyear,created)
VALUES(:title, :numpages, :pubyear, :created)";
            try
            {
                string connStr = @"Server=127.0.0.1;Port=5432;Database=testBook;
         User ID=postgres;Password=Pa$$W0rd";
                using (NpgsqlConnection conn = new NpgsqlConnection(connStr))
                {
                    conn.Open();
                    using (NpgsqlCommand cmd = new NpgsqlCommand(commandText, conn))
                    {
                        cmd.CommandType = CommandType.Text;
                        cmd.Parameters.Add("title", NpgsqlDbType.Varchar).Value = b.Title;
                        cmd.Parameters.Add("numpages", NpgsqlDbType.Numeric).Value = b.NumPages;
                        cmd.Parameters.Add("pubyear", NpgsqlDbType.Numeric).Value = b.PubYear;
                        cmd.Parameters.Add("created", NpgsqlDbType.Timestamp).Value = DateTime.UtcNow;
                        resp = cmd.ExecuteNonQuery();
                    }
                }
                return resp;
            }
            catch (NpgsqlException ex)
            {
                LogErrors(ex);
                throw new ApplicationException(@"A DataBase error has occurred, 
please see the log file.");
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                throw new Exception("A exception has occured, please see the log file.");
            }
        }

        static void LogErrors(NpgsqlException ex)
        {
            string msg = null;
            foreach (NpgsqlError item in ex.Errors)
            {
                msg = String.Format("Code: {0}\n", item.Code);
                msg += String.Format("Detail: {0}\n", item.Detail);
                msg += String.Format("Error: {0}\n", item.ErrorSql);
                msg += String.Format("File: {0}\n", item.File);
                msg += String.Format("Hint: {0}\n", item.Hint);
                msg += String.Format("Line: {0}\n", item.Line);
                msg += String.Format("Message: {0}\n", item.Message);
                msg += String.Format("Position: {0}\n", item.Position);
                msg += String.Format("Routine: {0}\n", item.Routine);
                msg += String.Format("Severity: {0}\n", item.Severity);
                msg += String.Format("Where: {0}\n", item.Where);
                msg += String.Format("======{0}======\n", DateTime.Now.ToString());
            }
            Logger.Error(msg);
        }
    }
}

Aquí el código de la clase Logger


Finalmente, el código la clase principal MainClass.


En la clase BooksManager se encuentra el método estático LogErrors en donde se realiza toda la funcionalidad, aquí es donde se itera por la enumeración Errors de la clase NpgsqlException y se escribe la información en el archivo de texto.


Antes de compilar y ejecutar la aplicación vamos a ocasionar un error en la sentencia de la consulta SQL. Por ejemplo no escribir correctamente el nombre de la tabla.



var commandText = "INSERT INTO Booksssss(title,numpages,pubyear,created)
VALUES(:title, :numpages, :pubyear, :created)";

Al compilar y ejecutar la aplicación veremos la excepción generada a propósito para poder consultar el archivo log y ver más detalles acerca de la excepción generada.
Compilamos la aplicación con los siguientes comandos:

$ dmcs -t:library -r:System.Data,Npgsql Book.cs BooksManager.cs Logger.cs 
/out:TestNpgsqlError.dll

$ dmcs -r:TestNpgsqlError.dll Main.cs

Ejecutamos la aplicación, como se muestra en la siguiente imagen:



Otra prueba es si escribimos erróneamente los parámetros de la cadena de conexión, por ejemplo cambiar el usuario de la base de datos o no teclear correctamente el nombre de la base de datos.



string connStr = "Server=127.0.0.1;Port=5432;Database=testBooks;User ID=postgressss;
Password=Pa$$W0rd";

Podemos consultar la bitácora y ver como por cada excepción se genera un código y los detalles de la excepción.


Descargar el código fuente del ejemplo (Download the source code)