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. The program wrote the events in the log.

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.Querying the tables.

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.

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

jueves, 25 de enero de 2018

How to calculate a leap year with C#

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

Fig 1. Pope Gregory XIII


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. The following application shows how to calculate a leap year.

Fig 2 Testing the application.

Fig 3 Running a second test.

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

lunes, 25 de diciembre de 2017

Understanding Bitwise Logical Operators with C#

Bit manipulation operations, including logical and shift operations, perform low-level operations directly on the binary representations used in integers. The ability to operate directly on binary might save large amounts of memory, might enable certain computations to be performed very efficiently, and can greatly simplify operations on collections of bits, such as data read form or written to parallel I/O ports.

The C# programming language supports bitwise operations on both numeric and boolean data types. These are represented as the operators ~, &, ^, and | for the bitwise operations of NOT (bitwise complement), bitwise AND, bitwise XOR, and bitwise OR, respectively. The operators work in parallel on all bits of the operands and never cause overflow, even in a checked context.

Unsigned integers are normally used with the bitwise operators.

Bitwise NOT (complement)

The bitwise complement or NOT is used to flip the bits of a value, this operator is unary and inverts the bit value. Since this operator is a unary operator it cannot be combined with the = sign.

Fig 1 Example of bitwise NOT operator

Bitwise XOR

When combining two values with the logical XOR bitwise operator, you get the following result: if both bits are the same, the result is 0 else if 1 bit is 0 and the other is 1, the result is 1

Fig 2 Example of bitwise XOR Operator

Bitwise OR

When combining 2 byte values results in the following: if both bits are 0, the result is 0. If either or both bits are 1, the result is 1.

Fig 3 Example of bitwise OR operator

Bitwise AND

The bitwise AND operator produces a one in the output bit if both input bits are one; otherwise it produces a zero.

Fig 4 Example of bitwise AND operator

When using the bitwise operator, it’s useful to display values in binary to show the precise effects of these operators. The following example demonstrate the use of the bitwise operators, you can download the source code from here.

The application sample is shown below:

Fig 1 Testing the AND operator

Fig 2 Testing the Inclusive OR operator

Fig 3 Testing the exclusive OR operator

Fig 4 Testing the NOT operator, this operator is unary, so there is not result using two integers.