jueves, 26 de julio de 2018

PDF documents about .NET Patterns & practices.

In 2007, Microsoft published a series of documents about .NET architecture. Although the documents reference to old technologies, such as Enterprise Library, Web Services Enhancements, etc. Some themes have not lost their validity. Remember that the architectural principles are agnostic.

  1. Application Architecture for .NET: Designing Applications and Services
  2. Designing Data Tier Components and Passing Data Through Tiers
  3. Caching Architecture Guide for .NET Framework Applications
  4. .NET Data Access Architecture Guide
  5. Deploying .NET Applications Lifecycle Guide
  6. Designing Application-Managed Authorization
  7. Data Patterns
  8. Design and Implementation Guidelines for Web Clients
  9. Guidelines for Application Integration
  10. Exception Management in .NET
  11. Describing the Enterprise Architectural Space
  12. Enterprise Solution Patterns Using Microsoft .NET
  13. Integration Patterns
  14. Web Service Security
  15. Application Interoperability: Microsoft .NET and J2EE
  16. Smart Client Architecture and Design Guide
  17. Improving .NET Application Performance and Scalability
  18. Building Secure ASP.NET Applications
  19. Security Engineering Explained
  20. Team Development with Visual Studio® .NET and Visual SourceSafe
  21. Improving Web Application Security: Threats and Countermeasures

Documentos acerca de Microsoft patterns & practices

En 2007, Microsoft publicó una serie de documentos acerca de arquitectura y buenas prácticas. Aunque los documentos se refieren a tecnologías ya descontinuadas, algunos temas no han perdido vigencia.

  1. Application Architecture for .NET:Designing Applications and Services
  2. Designing Data Tier Components and Passing Data Through Tiers
  3. Caching Architecture Guide for .NET Framework Applications
  4. .NET Data Access Architecture Guide
  5. Deploying .NET Applications Lifecycle Guide
  6. Designing Application-Managed Authorization
  7. Data Patterns
  8. Design and Implementation Guidelines for Web Clients
  9. Guidelines for Application Integration
  10. Exception Management in .NET
  11. Describing the Enterprise Architectural Space
  12. Enterprise Solution Patterns Using Microsoft .NET
  13. Integration Patterns
  14. Web Service Security
  15. Application Interoperability: Microsoft .NET and J2EE
  16. Smart Client Architecture and Design Guide
  17. Improving .NET Application Performance and Scalability
  18. Building Secure ASP.NET Applications
  19. Security Engineering Explained
  20. Team Development with Visual Studio® .NET and Visual SourceSafe
  21. Improving Web Application Security: Threats and Countermeasures

martes, 24 de julio de 2018

Oracle Recipe #3: How to Execute a query that returns a Single Row with the method GetOracleValues.

if you want to obtain multiple values from a database, you can call the executeReader method once on a OracleCommand object, to execute a SQL statement that returns a collection of values in a single row result.

The ExecuteReader method returns an instance of a class that implements the IDataReader interface. Each of the data reader classes provided by .NET Framework has a GetValues method, which returns an array of column values for the current row.

To obtain a single row from a database.

  1. Open a OracleConnection.
  2. Create and initialize a OracleCommand object.
  3. Call the ExecuteReader method on the command object. Assign the return value from this method to a data reader variable.
  4. Call the Read method on the data reader object to move to the first(and only) row in the result set.
  5. Call the GetOracleValues method on the data reader object. Pass an object array as a parameter to retrieve the scalar results of the query.
  6. Convert each element in the array to an appropriate data type, if necessary.
  7. Close the OracleDataReader object.
  8. Dispose the OracleCommand object.
  9. Close the database connection.

The following example shows how to execute a query that returns a set of values. The example place the results into an array named results.

Fig 1. Using the GetOracleValues of an OracleDataReader object.


Fig 2. Testing the program.


Download example source code.

lunes, 9 de julio de 2018

Oracle Recipe #2: How to execute a query that returns a Scalar result with OracleCommand.

  1. Microsoft ADO.NET command objects have an ExecuteScalar method, which enables you to execute a query that returns a single result.
  2. Open a database connection.
  3. Create and initialize a command object.
  4. Call the ExecuteScalar method on the command object.
  5. Convert the return value from ExecuteScalar into an appropriate data type.
  6. Dispose the command object.
  7. Close the database connection.

The following example, show how to execute a query that determines the average salary from the table employees on the HR schema provided by Oracle Database XE. The example assume that the query does not return a NULL result.

Fig 1. OracleCommand ExecuteScalar method code example.


Download example source code.

jueves, 5 de julio de 2018

Utilizando las clases de ADO.NET en Oracle.

Hace bastante tiempo que hice unas clases de ADO.NET para Oracle (un tipo helper de manera elemental). Quizás no es la manera más optima de acceder a una base de datos, pero al menos en ambientes restringidos en donde existen aplicaciones legadas donde no es posible actualizar otro proveedor de ADO.NET para Oracle que no sea el que viene predeterminado por .NET.

Aquí esta la clase para manejar la conexión, se llama OracleDataBase

Fig 1. Clase para manejar la conexion a la base de datos.


Utilizo otra clase llamada OracleDataBaseCommand para auxiliarme con los comandos.
Fig 2. Clase auxiliar para ejecutar los comandos en la base de datos.


Su utilización dentro de una clase que sirva para persistir o extraer datos sería de la siguiente manera.

Fig 3. Clase que utiliza las clases auxiliares para guardar un objeto.


Fig 4. Clase principal que crea, actualiza y consulta un cliente en la base de datos.


Descargar ejemplo.

viernes, 22 de junio de 2018

C# Recipe 3: How to format a string as currency

You can use the String.Format() method to localize the format of data such as dates,times, numbers, and currencies, according to the culture in the currently executing thread. The following example shows how to display a currency according to the current culture.

Fig 1. Example of how strings are formatted.


Fig 2. Displays a localized currency value.


Download source code.

jueves, 21 de junio de 2018

How to connect an Oracle Data Source by using ADO.NET

Step 1: Provide a connection string

To connect to a database, you must provide a connection string to identify the database. The following list describes several common parameters of connection strings.

  • Persist Security Info: if is false, the data source does not return security-sensitive if the connection is open.
  • User ID and Password: The data source login and password to use if you are not using integrated security.
  • Integrated Security or Trusted_Connection: if true, the data source uses the current account credentials for authentication, if false, you must specify the User ID and Password in the connection string.
  • Data Source: The name or network address of the data source instance.
  • Initial Catalog or Database: the name of the database.
  • Connection Timeout: The length of time in seconds to wait for a connection to the server before the data source terminates the attempt and returns an error. The default timeout is 15 seconds.
Fig 1. Provide a connection string.


Step 2: Retrieve a connection string from an application configuration file.

You can either store connection strings in an application configuration file or you can hard-code them directly in your application. If you store connection strings in the configuration file, you can modify them easily, without having to edit the source code and recompile the application. Each connection string that is stored in an application configuration file has its own assigned name. In an application, you can access a connection string by its programmatic name.

Fig 2. Create and return an OracleConnection object.


Step 3: Handle connection events

ADO.NET connection objects have two events that you can use to retrieve informational messages from a data source or to determine if the state of a connection has changed.

  • InfoMessage: Occurs when a data source returns an informational message. Informational messages are messages from a data source that do not result in an exception being thrown.
  • StateChage: Occurs when a connection changes from the closed state to the open state or from the open state to the closed state.

If an error occurs at the data source, the data provider throws an exception. However, if the data source returns an informational message, the data provider raises an InfoMessage event instead.

Step 4: Handle connection exceptions

The .NET Data provider for Oracle throws an OracleException when it encounters an error or warning generated by an Oracle database. OracleException objects have a Code property that gets the code portion of the error as an integer and message property that gets a description of the error.

Fig 3. Step 3 and 4: Handle connection events and exceptions, you can see the example below.


The following code show how to test each step in C# code.

Fig 4. The code to test our classes.


Fig 5. We run the program and verify the events in the log.


Fig 6. The program wrote the events in the log.


Download source code.

domingo, 10 de junio de 2018

Oracle Recipe #1: How to generate an IDENTITY column using a sequence

Primary keys can be created using either numeric or character data types, with one exception: Oracle does not have the same concept of identity columns as MS SQL Server.

What is an Identity Column?

It is a property that automatically generates a unique sequential value when it is assigned to a numeric data type. Oracle handles this concept using a database object called sequence.

The Sequence database object enables you to generate a unique sequence number. Each user of the sequence can increment it and obtain numbers for their use. Because multiple users can obtain sequence numbers, there is no guarantee that the numbers you get will not have gaps.

A sequence does not have to be related to a single table, and therefore could be used to provide unique numbers to multiple tables. As a general rule, having one sequence per table or at least one for each major table results in easier diagnostics and a better overall experience. The following examples show how you can add an identity column for two tables: categories and publishers.

Each table will use a IDENTITY column as PRIMARY KEY.
Fig 1. The categories and publishers catalog.


Fig 2. Script to create both tables.


The following code shows an example of how to select the NEXTVAL from a sequence. Upon executing this trigger, the sequence value is incremented by 1.

Fig 3. Script to create database objects: triggers and sequences.


Each time we add a new row, the trigger will automatically create a new unique number for that row. With this concept, the first row ID would be 1, and the next ID would be last ID number plus one.

Fig 4. Inserting rows without primary key.


Fig 5.Querying the tables.


Download Scripts

jueves, 7 de junio de 2018

Understanding delegates with C#

A delegate is similar to a function pointer in C or C++ except that delegates are type-safe. The term type-safe means that code is specified in a well-defined manner that can be recognized by a compiler. In this case it means that an incorrect use of a delegate is a compile-time error. This is quite different than in C++, where an incorrect use of a function pointer may not cause an error until the program is running.

Delegates allow you to write code that can dynamically change the methods that it calls.

A delegate contains a reference to a method rather than the method name.

By using delegates, you can invoke a method without knowing its name. Calling the delegate will actually execute the method referenced by the delegate.

To use a delegate, you must follow these steps:

  1. First, define it using the reserved keyword delegate.
  2. Second, instantiate it.
  3. Third, write the implementation with the same return value and signature of your delegate.

Fig 1. Steps to use a delegate.


A delegate is similar to an interface. It specifies a contract between a caller and an implementer.

The following code shows how to define, create and call delegates, It creates an array of delegates with instances of delegates that refers to the methods that represent each arithmetic operation. We execute each delegate with a foreach keyword that iterates through this array.

Fig 2. Sample using delegates.


Using delegates is a solution much simpler than using function pointer.

Fig 3. Testing the program.


Fig 4. Another test.


Download source code

sábado, 19 de mayo de 2018

C# Recipe 2: How to calculate the date of the Easter Sunday.

Easter is the celebration of Christ's resurrection from the dead. It is celebrated on Sunday, and marks the end of Holy Week, the end of Lent, the last day of the Easter Triduum (Holy Thursday, Good Friday and Easter Sunday), and is the beginning of the Easter season of the liturgical year.

As we know from the Gospels, Jesus Christ rose from the dead on the third day following his crucifixion, which would be Sunday. Since the early Middle Ages, all Christians have used the same method for determining the date of Easter, though they arrive at a different result.

The following code calculates the easter sunday for a given year:

Listing 1. The main program


Listing 2. The Util class


Fig 1. Running the sample, output 1


Fig 2. Running the sample, output 2


Fig 3. Running the sample, output 3


Download source code

jueves, 25 de enero de 2018

C# Recipe 1: How to calculate a leap year.

The Gregorian Calendar is the most widely used calendar in the world today.It is a reform of the Julian calendar, proposed by Aloysius Lilius, and decreed by Pope Gregory XIII, from whom it was named, on 24 February 1582 by papal bull Inter gravissimas

The changes made by Gregory also corrected the drift in the civil calendar which arose because the mean Julian calendar year was slightly too long, causing the vernal equinox, and consequently the date on which Easter was being celebrated, to slowly drift forward in relation to the civil calendar and the seasons. The Gregorian Calendar system dealt with these problems by dropping 10 days to bring the calendar back into synchronization with the seasons, and adopting the following leap year rule:

Every year that is exactly divisible by four is a leap year, except for years that are exactly divisible by 100; the centurial years that are exactly divisible by 400 are still leap years. For example, the year 1800 is not a leap year; the year 1984 is a leap year and the year 2000 too.

Fig 1 The following example calculates a leap year.


Fig 2 Running the sample, output 1


Fig 3 Running the sample, output 2


Download source code

domingo, 7 de enero de 2018

Understanding Interfaces with C#

The public interface of a class is a contract between the client code and the class that provides the service. Concrete classes implement each method. However, an abstract class can defer the implementation by declaring the method to be abstract, and a C# interface declares only the contract and no implementation.

A concrete class implements an interface by defining all methods declared by the interface. Many classes can implement the same interface. These classes do not need to share the same class hierarchy. Also, a class can implements more than one interface.

Imagine a group of objects that all share the same ability: they fly. You can construct a public interface, called Flyer, that supports three operations: TakeOff, Land and Fly.

Fig 1. The interface flyer and airplane class diagram


Listing 1 The Flyer code


Listing 2 The Airplane code


There can be multiple classes that implement the Flyer interface, as shown of the next figure

Fig 2. Multiple implementations of the Flyer interface.


This sounds like multiple inheritance, but it is not quite that. The danger of multiple inheritance is that a class could inherit two distinct implementation of the same method.

Fig 3. A mixture of inheritance and implementation.


An Airplane is a Vehicle, and it can fly. A bird is an Animal, and it can fly. These examples show that a class can inherit from one class but also implement some other interface.

This sounds like multiple inheritance, but it is not quite that. The confusion of multiple inheritance is that a class could inherit two distinct implementations of the same method. This is not possible with interfaces because an interface method declaration does not supply implementation. Suppose that you are constructing an aircraft control software system. The following diagram shows its class hierarchy

Fig 4. A mixture of inheritance and implementation.


The airport must grant permission to land and take off for flying objects of all types, then the code for the airport could look like the following.

Listing 3 The code for granting permission


Fig 5. Running the sample


Download source code