tag:blogger.com,1999:blog-64944198612404461872024-03-14T01:52:27.016-07:00Programming in the consoleProgramming, tutorials, documents and code.Martín A. Márquezhttp://www.blogger.com/profile/10939957618126542300noreply@blogger.comBlogger172125tag:blogger.com,1999:blog-6494419861240446187.post-8245074536561172062020-07-02T12:11:00.008-07:002023-06-17T21:14:46.238-07:00Performing Disconnected Operations: Programming with DataSets and Datatables with C#<h3>DataSets and DataTables</h3>
<p align="justify">
You create an instance of a <b>DataSet</b> by calling the <b>DataSet</b> constructor. Specify an optional name argument. If you do not specify a name for the DataSet, the name is set to "NewDataSet".
ADO.NET enables you to create <b>DataTable</b> objects and add them to an existing <b>DataSet</b>. You can add <b>DataColumn</b> objects to the Columns collection of the DataTable. You can set constraint information for a <b>DataTable</b> by using the <b>Primary Key</b> property of the <b>DataTable</b> and the <b>Unique</b> property of the <b>DataColumn</b> objects.
</p>
<p align="justify">
The schema, or structure, of a table is represented by columns and constraints.
You define the schema of a <b>DataTable</b> by using <b>DataColumn</b> objects as well as <b>ForeignKeyConstraint</b> and <b>UniqueConstraint</b> objects. The columns in a table can map to columns in a data source, contain calculated values from expressions, automatically increment their values, or contain primary key values.
DataTable objects are not specific to any data source, that's why .NET Framework types are used when specifying the data type of a DataColumn.
</p>
<p align="justify">
To ensure that the values in a column are unique, you can set the column values to increment automatically when new rows are added to the table. To create an auto-incrementing <b>DataColumn</b>, set the <b>AutoIncrement</b> property of the column to true. The <b>DataColumn</b> will then start with the value defined in the <b>AutoIncrementSeed</b> property, and with each row added the value of the <b>AutoIncrement</b> column will increase by the value held in the <b>AutoIncrementStep</b> property of the column.
For <b>AutoIncrement</b> columns, it is recommended that the <b>ReadOnly</b> property of the <b>DataColumn</b> be set to <b>true</b>.
</p>
<p align="justify">
When you identify a single <b>DataColumn</b> as the <b>Primary Key</b> for a <b>DataTable</b>, the table automatically sets the <b>AllowDBNull</b> property of the column to <b>false</b> and the <b>Unique</b> property to <b>True</b>.
For multiple-column primary keys, the <b>AllowDBNull</b> property is automatically set to <b>false</b>, but the <b>Unique</b> property is not set to <b>true</b>. However, a <b>UniqueConstraint</b> corresponding to the primary key is added to the <b>Constraints</b> collection of the <b>DataTable</b>.
</p>
<p align="justify">
You can use <b>Constraints</b> to enforce restrictions on the data in a <b>DataTable</b> to maintain the integrity of the data. Constraints are enforced when the <b>EnforceConstraints</b> property of the <b>DataSet</b> is <b>true</b>.
There are two kinds of constraints in ADO.NET: the <b>ForeignKeyConstraint</b> and the <b>UniqueConstraint</b>. By default, both constraints are created automatically when you create a relationship between two or more tables by adding a <b>DataRelation</b> to the <b>DataSet</b>.
</p>
<p align="justify">
<pre>
DataSet ds = new DataSet("CoursesDb");
DataTable categoryTable = ds.Tables.Add("Category");
DataColumn pkCol = categoryTable.Columns.Add("CategoryId",typeof(Int32));
pkCol.AutoIncrement = True;
pkCol.AutoIncrementSeed = 200;
pkCol.AutoIncrementStep = 3;
categoryTable.PrimaryKey = new DataColumn[] { pkCol };
DataColumn categoryCol = categoryTable.Columns.Add("Category",typeof(String));
categoryCol.AllowDBNull = false;
categoryCol.Unique = true;
categoryTable.Columns.Add(categoryCol);
</pre>
</p>
<h3>Understanding DataAdapters</h3>
<p align="justify">
Because the <b>DataSet</b> is independent of the data source, a <b>DataSet</b> can include data local to the application, as well as data from multiple data sources, so the interaction with existing data sources is controlled through the <b>DataAdapter</b>.
Each ADO.NET provider has a <b>DataAdapter</b> object.
A <b>DataAdapter</b> is used to retrieve data from a data source and populate tables within a <b>DataSet</b>. The <b>DataAdapter</b> also persists changes made to the <b>DataSet</b> back to the data source.
</p>
<p align="justify">
The <b>DataAdapter</b> has four properties that are used to retrieve data from and persist data to the data source. The <b>SelectCommand</b> returns data from the data source. The <b>InsertCommand</b>,<b>UpdateCommand</b>, and <b>DeleteCommand</b> are used to manage changes at the data source.
</p>
<p align="justify">
The following
<a href="">example</a> demonstrates how to use Datasets, DataAdapters, Datatables,Constraints and Relations for performing disconnected operations on a database, also shows how to use the properties of a <b>SqlDataAdapter</b> with Store procedures.
This example uses the following database to manage a collection of courses and one category per course.
</p>
<div><b>Fig 1. The structure of the sample database.</b></div>
<a href="" target="_blank">
<img src=""/>
</a>
<div><b>Fig 2. Running the example, showing the courses.</b></div>
<a href="" target="_blank">
<div class="separator" style="clear: both;"><a href="" style="display: block; padding: 1em 0; text-align: center; "><img alt="" border="0" data-original-height="192" data-original-width="400" src=""/></a></div>
</a>
<div><b>Fig 3. Adding a new category.</b></div>
<a href="" target="_blank">
<img src=""/>
</a>
<div><b>Fig 4. Deleting a row.</b></div>
<a href="" target="_blank">
<img src=""/>
</a>
<div><b>Fig 5. Adding a new course on the DataTable.</b></div>
<a href="" target="_blank">
<img src=""/>
</a>
<div><b>Fig 6. Save changes of the DataSet back to the Data Source.</b></div>
<a href="" target="_blank">
<img src=""></img>
</a>
<div>
<a href="" target="_blank">
<img border="0" src="" />
Download the visual studio project for this example.
</a>
</div>
<div>
<a href="" target="_blank">
<img border="0" src="" />
Download the database and store procedures scripts for this example.
</a>
</div>Martín A. Márquezhttp://www.blogger.com/profile/10939957618126542300noreply@blogger.comtag:blogger.com,1999:blog-6494419861240446187.post-10061539074923077492020-05-15T00:18:00.002-07:002023-06-17T21:16:39.717-07:00Arreglos unidimensionales en C#<p align="justify">
Un arreglo es un grupo de variables o elementos del mismo tipo que contienen valores. Los arreglos son tipos por referencia.
Los elementos de un arreglo pueden ser tipos por valor, otros arreglos o tipos por referencia, para referirse a un elemento en especial en un arreglo, especificamos el nombre de la referencia al arreglo y el número de la posición de ese elemento en el arreglo. A la posición se le conoce como el índice del elemento.
</p>
<p align="justify">
Una aplicación hace referencia a cualquiera de estos elementos mediante una expresión de acceso a un arreglo, la cual incluye el nombre del arreglo, seguido del índice del elemento especifico entre corchetes ([]). El primer elemento en cualquier arreglo tiene el índice cero.
</p>
<div><b>Fig 1. Estructura de un arreglo</b></div><br>
<a href="" target="_blank">
<img src=""/>
</a>
<p align="justify">
Un índice debe ser un entero no negativo; también puede ser una expresión.
El índice del arreglo debe ser un valor de tipo <i>int, uint, long o ulong</i>. o un valor de un tipo que pueda promoverse en forma implícita a uno de estos tipos.
</p>
<p align="justify">
Cada instancia de un arreglo conoce su propia longitud y proporciona acceso a esta información a través de la propiedad <b>Length</b> esta propiedad es de solo lectura y no puede cambiarse.
</p>
<h3>Declaración de arreglos</h3>
<p align="justify">
Las instancias de los arreglos ocupan espacio en memoria. Al igual que los objetos, los arreglos se crean con la palabra reservada new. Para crear una instancia de un arreglo, se especifica el tipo y el número de elementos del arreglo, y el número de elementos como parte de la expresión. Dicha expresión devuelve una referencia que puede almacenarse en una variable tipo arreglo.
</p>
<div><b>Fig 2. Declaración de arreglos</b></div><br>
<a href="" target="_blank">
<img src=""/>
</a>
<p align="justify">
La siguiente aplicación nos muestra cómo crear un arreglo de los elementos que recibe separados por comas, también aplica las siguientes operaciones promedio (AVG), mínimo (MIN), máximo (MAX) y la suma (SUM) al conjunto de elementos.
</p>
<div><b>Fig 3. Aplicando la función promedio (AVG) a un arreglo</b></div><br>
<a href="" target="_blank">
<img src=""/>
</a>
<div><b>Fig 4. Aplicando la función suma (SUM) a un arreglo</b></div><br>
<a href="" target="_blank">
<img src=""/>
</a>
<div>
<a href="" target="_blank">
<img border="0" src="" /> Descarga el código fuente</a>
</div>Martín A. Márquezhttp://www.blogger.com/profile/10939957618126542300noreply@blogger.comtag:blogger.com,1999:blog-6494419861240446187.post-65816602326870140862020-04-25T13:30:00.006-07:002023-06-17T22:01:17.377-07:00Stored Procedures in MS SQL Server
<P align="justify">Stored procedures offer many advanced features not available in
the standard SQL language. The ability to pass parameters and perform
logic allows the application designer to automate complex tasks. In
addition, these procedures being stored at the local server reduces
the amount of bandwidth and time required to execute the procedure.</P>
<P align="justify">There are several advantages to writing your own procedures, first
you are able to write complex SQL statements into the procedure,
second, to execute those SQL statements, all the user has to do is to
run the procedure.</P>
<P align="justify">With the use of parameters, you can make your stored procedures
much more useful as well as powerful. The following sample database,
will show you the syntax for creating some stored procedures for CRUD
operations.</P>
<a href="" target="_blank">
<img src=""/>
</a>
<P align="justify">There is also a security advantage to
using stored procedures. After the stored procedure has been created,
all access to the underlying tables can be revoked to the users.</P>
<H3>Reading Data with Stored Procedures</H3>
<P align="justify">The following example creates a stored
procedure to return all authors in the table.</P>
<a href="" target="_blank">
<img src=""/>
</a>
<P align="justify">After you create this stored procedure, you will execute it by
running the following statement:</P>
<a href="" target="_blank">
<img src=""/>
</a>
<P align="justify">This will return the authors which Surname is equal to 'Deitel'.
One of the problems is that if you do not pass it one of the
parameters that is expecting, you will get an error. One way to get
around this is to set up the parameters to use a default value.</P>
<H3>Adding Data with Stored Procedures</H3>
<P><B>The OUTPUT Parameter</B></P>
<P align="">The OUTPUT parameter is a very special type of parameter. It
allows you to return data directly into a variable that can be used
in other processing. The value that is returned is the current value
of that parameter when processing of the stored procedure completes.</P>
<P>The following example shows how to create a simple store procedure
that utilizes the OUTPUT keyword:</P>
<a href="" target="_blank">
<img src=""/>
</a>
<P align="justify">To execute this store, run the following script:</P>
<a href="" target="_blank">
<img src=""/>
</a>
<H3>Modifying Data with Stored Procedure</H3>
<P align="justify">Stored procedures can also be used to modify data. Any valid
insert, update or delete can be made into a stored procedure and can
be run by executing a single line of code instead of running many
lines of code.</P>
<P>The following example will delete a book and erase all its
relations in the table <I>[Authorbook]</I></P>
<a href="" target="_blank">
<img src=""/>
</a>
<P>To test this store run the following script</P>
<a href="" target="_blank">
<img src=""/>
</a>
<h3>
<a href="" target="_blank">
<img src="" border="0">Download the scripts for this example.
</a>
</h3>Martín A. Márquezhttp://www.blogger.com/profile/10939957618126542300noreply@blogger.comtag:blogger.com,1999:blog-6494419861240446187.post-52152379713589371312020-03-05T21:31:00.002-08:002023-06-17T22:03:20.486-07:00Operaciones Bitwise (a nivel de bits) con C# <p align="justify">Además de los operadores condicionales lógicos y de relación C# cuenta con operadores a nivel de bits (bitwise operators o logical operators) que permiten realizar operaciones con las representaciones binarias de las variables que internamente utiliza la computadora, esto es útil en ciertos casos donde se requiere interactuar directamente con el hardware o utilizar una variable entera como un arreglo de bits donde por ejemplo un tipo short representaría un arreglo de bits con una longitud de 16 valores y cada bit podría ser utilizado como si fuera un valor booleano 1 igual true y 0 igual a false.
</p>
<p align="justify">
Los tipos de datos donde usualmente aplican estos operadores son: los numéricos y las enumeraciones.
</p>
<p align="justify">
La siguiente tabla muestra los tipos numéricos, su longitud en bytes y su valor en decimal.</p>
<div><a href="" target="_blank">
<img src="" /></a></div><br />
<p align="justify">
Así por ejemplo si tenemos valores decimales representados en variables byte (8 bits hasta 255 en decimal)
<br /><br />byte a = 22;
<br />byte b = 33;
<br /><br />
Internamente su representación en binario es:
<br /><br />22 = 00010110
<br />33 = 00100001<br /><br />
si utilizamos variables de tipo short (16 bits hasta 65,535) <br /><br />
short c = 666;<br />
short d = 6666;<br /><br />
su representación en binario es:<br />
<br />666 = 00000010 10011010 <br />
6666 = 00011010 00001010<br /><br />
Así con cada tipo numérico siempre agrupando las cadenas de bits de 8 en 8.<br />La siguiente tabla muestra los operadores bitwise, su significado y su resultado.<br />
</p>
<div><a href="" target="_blank">
<img src="" /></a></div><br />
<br />
<div>Para ejecutar el programa de ejemplo, descargar el proyecto desde este <a href="" target="_blank">enlace. </a></div><br />
<div>Al ejecutarlo veremos los siguientes resultados:</div><br /><div><a href="" target="_blank"><img src="" /></a></div><br />
<div><a href="" target="_blank"><img src="" /></a></div><br />
<div><a href="" target="_blank"><img src="" /></a></div><br />
<div><a href="" target="_blank"><img src="" /></a></div><br />
<br /><h3><a href="" target="_blank"><img border="0" src="" /> Descarga el proyecto.</a></h3>Martín A. Márquezhttp://www.blogger.com/profile/10939957618126542300noreply@blogger.comtag:blogger.com,1999:blog-6494419861240446187.post-35043036909322916542019-10-25T21:42:00.002-07:002023-10-01T13:30:51.336-07:00Understanding method overriding with Python<p align="justify">
It is called method overriding to a new definition created within a class, for one or more methods inherited from its superclass.
The following example shows how to do it. This example is based on this previous entry: <a href="https://xomalli.blogspot.com/2019/07/understanding-oop-inheritance-with.html">Understanding OOP Inheritance with Python</a>
</p>
<p align="justify">
To override the inherited constructor of the <i>Person</i> class, follow these steps:
Enter a new declaration of the constructor method within the <i>Employee</i> class.
Add the parameters name,lastname,birthdate,department,email. Within the definition of the constructor add the attributtes self.name, self.lastname,self.birthdate,self.department and self.email then assign the corresponding parameters.
Add the following print instruction to the end of the constructor.
<div><b>Fig 1. Modified constructor</b></div>
</p>
<p align="justify">
In the main program add two new lines with the following two phrases: <pre>"John works in department"</pre> and concatenate the department attribute of the object John, with a period and <pre>"John's email is "</pre> and concatenate the email attribute of the object John with a period.
</p>
<div><b>Fig 2. Main program</b></div>
<p align="justify">
Run the code. As you can see the <i>Jonh</i> instance of the <i>Employee</i> class now accepts three parameters, because the <i>Person</i> constructor has been overriding.
In addition, the <i>talk</i> method remains the same inherited from Person.
</p>
<div><b>Fig 3. Running the example</b></div>
<div><pre><tt>$ py SampleOverriding.py</tt></pre></div>
<p>
<h3>
</h3>
</p>Martín A. Márquezhttp://www.blogger.com/profile/10939957618126542300noreply@blogger.comtag:blogger.com,1999:blog-6494419861240446187.post-57948223674238135362019-10-19T21:13:00.003-07:002023-10-01T13:28:54.693-07:00Understanding principles of security: Integrity, Creating a Hash<h3>Hashing Properties</h3>
<p>
Hashing is one-way mathematical function that is relatively easy to compute, but significantly harder to reverse.
</p>
<ol>
<li>The input can be any length.</li>
<li>The output has a fixed length.</li>
<li>The hash function is one way and is not reversible.</li>
<li>Two different input values will almost never result in the same hash values.</li>
</ol>
<h3>Hashing algorithms</h3>
<p align="justify">
The 8-bit checksum is one of the first hashing algorithms, and it is the simple form of a hash function. An 8-bit checksum calculates the hash by converting the message into binary numbers and then organizing the string of binary numbers into 8-bit chucks. The algorithm adds up the 8-bit values. The final step is to convert the result using a process called 2's complement.
</p>
<h3>Modern Hashing Algorithms</h3>
<p align="justify">
Two of the most popular modern hashing algorithms are MD5 and SHA.
</p>
<h3>Message Digest 5 (MD5) Algorithm</H3>
<p align="justify">
MD5 is one-way function that makes it easy to compute a hash from the given input data but makes it very difficult to compute input data given only a hash value. MD5 produces a 128-bit hash value.
</p>
<h3>Secure Hash Algorithm</h3>
<p align="justify">
SHA-2 algorithms are the secure hash algorithms that the U.S government requires by law for use in certain applications. This includes use in other cryptographic algorithms and protocols, for the protection or sensitive unclassified information.
SHA-2 replaced SHA-1 with four additional hash functions:
</p>
<ol>
<li>SHA-224 (224 bits)</li>
<li>SHA-256 (256 bits)</li>
<li>SHA-384 (384 bits)</li>
<li>SHA-512 (512 bits)</li>
</ol>
<p align="justify">
SHA-2 is a stronger algorithm, and it is replacing MD5. The SHA family is the next-generation algorithms.
The following program shows how to implement modern hashing algorithms with C#.<br>
Download the source code here.
</p>
<div><b>Fig 1. Running the program, compare different algorithms.</b></div>
<div><b>Fig 2. Running the program, comparing and contrasting different outputs. </b></div>
<p align="justify">
When choosing a hashing algorithm, use SHA-256 or higher as they are currently the most secure.
In production implement SHA-256 or higher.
</p>
<h3>
</h3>
<h3>
</h3>Martín A. Márquezhttp://www.blogger.com/profile/10939957618126542300noreply@blogger.comtag:blogger.com,1999:blog-6494419861240446187.post-74821821097464331222019-09-05T09:47:00.002-07:002023-10-01T13:26:23.454-07:00Understanding principles of security: Integrity<h3>The principles of Security</h3>
<p align="justify">
The foundational principles of security are: <b>confidentiality</b>, <b>integrity</b> and <b>availability</b>.
These principles known as the CIA triad is a guideline for information security for an organization.
</p>
<h3>Integrity</h3>
<p align="justify">
Integrity is accuracy, consistency, and trustworthiness of the data during its entire life cycle. Another term for integrity is quality.
Data must be unaltered during transit and not changed by unauthorized entities.
Methods used to ensure data integrity include hashing, data validation checks, data consistency checks, and access controls.
</p>
<h3>Hashes and Checksum</h3>
<p align="justify">
The process of <b>hashing</b> involves passing data through a cryptographic function, called a hash or digest function.
This process yields a small - relative to the size of the original data- value that uniquely identifies the data.
Depending on the algorithm used, the value's size is usually 128 or 160 bits.
Checksum hashing can be used to verify integrity of the data during transfer.
</p>
<p align="justify">
<b>Hashing</b> is a one-way function that creates a fixed-length output (known as the hash, hashing value, fingerprint, message digest, and so on)
from an input of any length.
Common hash functions include MD5, SHA-1, SHA-256, and SHA-512. These <b>hash</b> functions use complex mathematical algorithms.</p>
<p align="justify">For example, Message Digest 5 (MD5) is a 128-bit hash algorithm. This means that no matter what the size of the input data, the output <b>hash</b> will
always be 128 bits long.
<b>Hashing</b> is not an encryption algorithm. Instead, <b>hashing</b> is used to produce a unique identifier of data without modifying the original data. The data could be a file, a hard drive,
a network-traffic packet, or an email message. <br/>
The <b>hashed value</b> is used to detect when changes have been made to a resource.
For example, when a hard drive is being imaged to create an exact duplicate, a hash is produced of the original drive before the duplication process.
</p>
<div><b>Fig 1. Summary of hashing algorithms</b></div>
<p align="justify">A hash tells you nothing about the data, but it uniquely identifies it.
The <b>hashed value</b> is simply there for comparison.
</p>
<div><b>Fig 2. The hash function operates on fixed-size blocks of data</b></div>
<h3>Writing a simple Hash Calculator with AngularJS, HTML5, C# and WCF.</h3>
<p align="justify">
I've written an app to demonstrate how to implement hash functions in a REST Service.
The app communicates with a WCF REST service that uses the C# abstract class <i><a href="https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.hashalgorithm?view=netframework-4.8"> System.Security.Cryptography.HashAlgorithm</a></i> to achieve encryption.
<ol>
<li>The user enters the text to encrypt, selects the algorithm to use.</li>
<li>The user submits the information to the service in order to get the hash code.</li>
<li>The hash web service presents the hash code to the user.</li>
</ol>
Testing with different algorithms, we can see the length of the output.
</p>
<div><b>Fig 3. Using the MD5 algorithm.</b></div>
<div><b>Fig 4. Using the SHA1 algorithm.</b></div>
<div><b>Fig 5. Using the SHA256 algorithm.</b></div>
<div><b>Fig 6. Using the SHA384 algorithm.</b></div>
<div><b>Fig 7. Using the SHA512 algorithm.</b></div>
<div><b>Fig 8. Changing the text, we can see a totally different output, but without no changes in the length.</b></div>
<h3>Conclusion</h3>
<p align="justify">
Keeep in mind that hash functions do not encrypt the data. They use the data to make a fingerprint or snapshot of the data that is given to you as a code.
That code is used to determine whether or not the data has been altered. If the data you receive has been altered, you will not get the same code number as the original data.
</p>
<br/>
<p>
<h3>
</h3>
</p>Martín A. Márquezhttp://www.blogger.com/profile/10939957618126542300noreply@blogger.comtag:blogger.com,1999:blog-6494419861240446187.post-69088343234229833902019-08-13T23:00:00.004-07:002023-10-01T13:24:05.824-07:00How to use Multiple Active Result Sets with ADO.NET<p align="justify">
Multiple Active Result Sets (MARS) is a feature supported by ADO.NET that allows the execution of multiple batches on a single connection. In previous versions, only one batch could be executed at a time against a single connection. When using a MARS-enabled connection, multiple logical batches can be executed on a single connection. Executing multiple batches with MARS does not imply simultaneous execution of operations.
</p>
<p align="justify">
To access multiple result sets using <b>SqlDataReader</b> objects, multiple <b>SqlCommand</b> objects will need to be used. When MARS is enabled, each command object used adds an additional session to the connection.
</p>
<p align="justify">
The following program demonstrates how to use a Sql Server Connection with MARS enabled.
</p>
<div><b>Fig 1. MARS-enabled connection string</b></div>
<div><a href="http://destyy.com/w3Eraw" target="_blank">
<br/>
<div><b>Fig 2. Data access class with two commands.</b></div>
<div><a href="http://destyy.com/w3Eraw" target="_blank">
<br/>
<div><b>Fig 3. Main program.</b></div>
<div><a href="http://destyy.com/w3Eraw" target="_blank">
<br/>
<div><b>Fig 4. Running the example.</b></div>
<div><a href="http://destyy.com/w3Eraw" target="_blank">
<br/>
<p>
<h3>
</h3>
</p>Martín A. Márquezhttp://www.blogger.com/profile/10939957618126542300noreply@blogger.comtag:blogger.com,1999:blog-6494419861240446187.post-30507579052684480832019-07-16T13:27:00.001-07:002023-10-01T13:22:27.113-07:00How to execute simple Database Queries with VB .NET<p align="justify">
The <b>SqlCommand</b> class in the .NET Framework Data Provider has four methods that you can use to execute SQL
statements:
<ol>
<li><b>ExecuteScalar:</b> Executes a query that returns a single scalar value.</li>
<li><b>ExecuteReader:</b> Executes a query that returns a result set.</li>
<li><b>ExecuteNonQuery:</b> Executes a data update statements or a catalog update statement.</li>
<li><b>ExecuteXmlReader:</b> Executes a query that returns an Extensible Markup Language (XML) result set, this method is only avaliable in the <b>SqlCommand</b> class.</li>
</ol>
</p>
<h3>To execute a simple database query</h3>
<p align="justify">
<ol>
<li>Import the <b>System.Configuration</b> namespace</li>
<li>Use the <b>ConfigurationManager.ConnectionStrings</b> property to get a collection of connection strings from the application configuration file.</li>
<li>Index into the collection of connection strings by using the programmatic name of the connection string you want to access.</li>
<li>Use the <b>ConnectionString</b> property to get the connection string information.</li>
<li>Create a connection object.</li>
<li>Create a command object.</li>
<li>
If you want to execute an SQL statement, set the CommandType property of the command object to the
<b>CommandType.Text</b> enumeration value. If you want to call a stored procedure, set the <b>CommandType</b> property of the command
object to the <b>CommandType.StoredProcedure</b> enumeration value.
</li>
<li>Call the <b>Open</b> method on the connection object.</li>
<li>Call the <b>ExecuteScalar</b> method on the command object. Assign the result to a suitably typed variable.</li>
<li>Call the <b>Close</b> method on the connection object.</li>
</ol>
</p>
<p align="justify">
The following example shows how to execute a query to determine the number of products in the AdventureWorks2016CTP3 database
on the local SQL Server instance.
</p>
<div><b>Fig 1. Main program</b></div>
<div><b>Fig 2. App config</b></div>
<div><b>Fig 3. Output program</b></div>
<p>
</p>Martín A. Márquezhttp://www.blogger.com/profile/10939957618126542300noreply@blogger.comtag:blogger.com,1999:blog-6494419861240446187.post-27995619118900760242019-07-11T21:59:00.001-07:002023-10-01T13:20:31.667-07:00Understanding OOP Inheritance with Python <p align="justify">
One of the most common goals for the OOP is code reusability.
Characteristics such as inheritance contributes to achieving this goal.
</p>
<h3>Inheritance</h3>
<p align="justify">
Inheritance is the most used mechanism to optimise the coding, since it allows
to reuse methods defined in superclasses, to define new subclasses.
The following example uses the class <i>Person</i> as its superclass.
</p>
<div><b>Fig 1. Inheritance</b></div>
<div><b>Fig 2. Person Class</b></div>
<p align="justify">
We know that a person also can be an employee in addition to talking, and Employee can show its earnings so we will
declare a class called Employee.
</p>
<div><b>Fig 3. Employee Class</b></div>
<p align="justify">
Who inherits the <b>talk()</b> method of the Person class to implement inheritance in
this example:
</p>
<div><b>Fig 4. Main program</b></div>
<p align="justify">
You will notice how the "John" object, which is now an instance of Employee
continues to behave as an instance of Person because it has inherited its
methods.
</p>
<div><b>Fig 4. Run the example</b></div>
<div><code>$ py Sample1OOP.py</code></div>Martín A. Márquezhttp://www.blogger.com/profile/10939957618126542300noreply@blogger.comtag:blogger.com,1999:blog-6494419861240446187.post-31227854918205205912019-04-29T22:00:00.001-07:002023-10-01T12:54:16.698-07:00Understanding RESTFul (POST, PUT and DELETE) services with Windows Communication Foundation (WCF) and Oracle XE. <p align="justify">
The REST model relies on the application that accesses the data sending the appropriate HTTP verb as part of the request used to access the data. HTTP besides GET, the HTTP protocol supports other forms of verbs such as POST, PUT, and DELETE, which you can use in a REST service to create, modify, and remove resources, respectively. Using these verbs you can build WCF services that can insert, update, and delete data.
</p>
<p align="justify">
The good practice is that you use HTTP POST requests to specify operations that can add new records, HTTP PUT requests for operations that update existing data, and HTTP DELETE requests to define operations that can remove records.
</p>
<p align="justify">
POST is an exception in certain regards. POST is frequently misused as DELETE and PUT, because the use of DELETE and PUT is either not permitted or technically impossible from the browser's perspective, and you could use HTTP POST requests to update and delete data.
</p>
<p align="justify">
Use the <b>[WebInvoke]</b> attribute for scenarios POST, PUT and DELETE, you use this attribute to identify a URI, but you can also indicate the type of the request message to which to respond.</p>
<p align="justify">In the following example, I will build a REST WCF Service to enable insert, update and delete operations for Oracle HR Schema.</p>
<p align="justify">You can learn about the HR Schema in this <a href="http://xomalli.blogspot.com/2019/01/oracle-recipe-4-how-to-retrieve-list-of.html">post</a>.</p>
<p align="justify">The following table shows the URIs and the parts of the interface that I will implement for each URI in the example.</p>
<table>
<thead>
<tr>
<td><b>URI</b></td>
<td><b>Method</b></td>
<td><b>Output</b></td>
<td><b>Input</b></td>
</tr>
<tr>
<td>/employees</td>
<td>POST</td>
<td>bool</td>
<td>An Employee Object</td>
</tr>
<tr>
<td>/employees/{id}</td>
<td>PUT</td>
<td>bool</td>
<td>An employee Object with id specified.</td>
</tr>
<tr>
<td>/employees/{id}</td>
<td>DELETE</td>
<td>bool</td>
<td>An employee Id</td>
</tr>
</thead>
</table>
</p>
<p align="justify">
The main steps for this exercise are as follows:
<ol>
<li>
<div>Use the <b><i>EmployeesDac</i></b> class, which contains the method for accessing the database.</div>
</li>
<li>
<div>Write the <b><i>EmployeesServiceImplementation</i></b> class with the following code (fig 1).</div>
<div><b>Fig 1. EmployeeServiceImplementation.cs</b></div>
</li>
<li>
<div>Write a new interface called <b><i>IEmployeesServiceContract</i></b> and type the following code(fig 2).</div>
<div><b>Fig 2. IEmployeeServiceContract.cs</b></div>
</li>
<li>
<div>Write the <b><i>EmployeesService.svc</i></b> file that references the service implementation with the following code (fig 3).</div>
<div><b>Fig 3. EmployeeService.svc</b></div>
</li>
<li>
<div>Finally, add the following config file (fig 4)</div>
<div><b>Fig 4. Web.config</b></div>
</li>
</ol>
</p>
<h3>Testing the service with Soap UI.</h3>
<p align="justify">
The WCF service that you have built runs the same way as a regular Web application and is
hosted by a Web Server.
</p>
<p align="justify">
If you browse the .svc file, you can view the help page for the WCF service. It verifies that the WCF
service has been configured correctly (you will see error messages if the WCF service cannot start) and
provides information showing how you can connect to the service.
</p>
<p align="justify">
Once we've made all the required settings, running the tests are very easy with SOAP UI. Before running, we can
define the json request or query string parameters. Use the Green button to start running the test.
</p>
<p align="justify">
<div>Testing the HTTP-POST request, after completing the execution, the result window displays the JSON Response.</div>
<div><b>Fig 5. HTTP-POST Request</b></div><br/>
</p>
<p>
<div>Testing the HTTP-PUT request after completing the execution, the result window displays the JSON Response.</div>
<div><b>Fig 6. HTTP-PUT Request</b></div><br/>
</p>
<p>
<div>Testing the HTTP-DELETE request after completing the execution, the result window displays the JSON Response.</div>
<div><b>Fig 7. HTTP-DELETE Request</b></div><br/>
</p>
Martín A. Márquezhttp://www.blogger.com/profile/10939957618126542300noreply@blogger.comtag:blogger.com,1999:blog-6494419861240446187.post-27533418769940634892019-03-09T22:18:00.005-08:002023-10-01T12:52:03.948-07:00User Identification and Authentication with Transact-SQL<p align="justify">
Doing user authentication in SQL Server can be customized; you can use all kinds of data from a database to authenticate users. Every application needs to deal with security, making sure that sensitive data cannot be accessed by the wrong users.
You can write your own custom logic to verify user names and passwords and make sure the information is stored.</p>
<div><b>Fig 1. The database diagram.</b></div><br/>
<p align="justify">
In the database under a secure account with a password that couldn't easily be guessed by a user. The easiest way to accomplish this is to one-way encrypt user passwords on store procedure.
</p>
<p align="justify">
A simple but fully functional example is shown below.
</p>
<div><b>Fig 2. The T-SQL code.</b></div><br/>
<p align="justify">
This code will insert one row, corresponding to the new user, in the users table.
The SQL Server way to store passwords is by wrapping them in a built-in encrypting function called <a href="https://docs.microsoft.com/en-us/sql/t-sql/functions/hashbytes-transact-sql?view=sql-server-2017">HASHBYTES</a> .
</p>
Martín A. Márquezhttp://www.blogger.com/profile/10939957618126542300noreply@blogger.comtag:blogger.com,1999:blog-6494419861240446187.post-62598700012086716732019-02-18T21:37:00.004-08:002023-10-01T12:49:32.190-07:00Oracle Recipe #5 How to execute Oracle parameterized commands with ODP.NET <p justify="justify">
SQL statements can receive input-only parameters, output-only parameters, and bidirectional parameters.
You can use a OracleCommand object to execute parameterized SQL statements.
To execute a parameterized SQL statement use the following steps:
</p>
<p justify="justify">
<ol>
<li>Open a database connection,use OracleConnection.</li>
<li>Create and initialize an OracleCommand object.</li>
<li>Create a OracleParameter object, for each input parameter required by the SQL statement. Specify the name, type size, and value for each parameter, and add it to the parameters collection of the command object.</li>
<li>Execute the command by calling the ExecuteScalar, ExecuteReader, ExecuteXmlReader, or ExecuteNonQuery method, as appropriate for the type of SQL statement.</li>
<li>Use the return value obtained by executing the command.</li>
<li>Dispose the command object.</li>
<li>Close the database connection.</li>
</ol>
</p>
<p justify="justify">
The following example shows how to execute a SQL statement that updates employee by employee id <a href="https://xomalli.blogspot.com/2019/01/oracle-recipe-4-how-to-retrieve-list-of.html">(please, check this post</a> for further information).<br/>
The SQL statement requires the following parameters: <i>prmFirstName</i> , <i>prmLastName</i>, <i>prmEmail</i>, <i>prmPhoneNumber</i>, <i>prmHireDate</i>, <i>prmSalary</i>,<i>prmCommission</i> and <i>prmEmployeeId</i>.
</p>
<div><b>Fig 1. The application code.</b></div><br/>
Martín A. Márquezhttp://www.blogger.com/profile/10939957618126542300noreply@blogger.comtag:blogger.com,1999:blog-6494419861240446187.post-88812812563757027592019-01-12T21:41:00.001-08:002023-10-01T12:47:32.411-07:00Understanding RESTFul services with Windows Communication Foundation (WCF) and Oracle HR Schema
<h3>What Are RESTful Web Services?</h3>
<p align="justify">
<b>REST</b> stands for Representational State Transfer is an architectural style rather than a prescribed way of building Web services, some of the most important aspects of the REST environment are:
<ul>
<li>HTTP or HTTPS may be used as the transfer protocol.</li>
<li>URLs including query strings are used to address resources.</li>
<li>Representation formats supported range from HTML and XML to JSON and ATOM.</li>
<li>A Simple and intuitive programming interface is achieved by using HTTP verbs and status codes.</li>
<li>Statelessness in the interaction between clients and services.</li>
</ul>
</p>
<p align="justify">
<b>REST</b> is not concerned with the definition of messages and the design of methods, the key point here is that REST describes a stateless, hierarchical scheme for representing resources and business objects over a network.
The main components of this model are: <i>resources</i> and <i>actions</i>.
The action of the resource is determined by four main HTTP verbs: GET, PUT, DELETE and POST, and the action which can affect those resources are mainly CRUD (Create, Read, Update and Delete) methods, the success of the action is found by the HTTP status code.
</p>
<p align="justify">
The <b>REST</b> model relies on the application that accesses the data sending the appropriate HTTP verb as part of the request used to access the data.
<ul>
<li><b>GET</b> is used exclusively to retrieve data and, therefore, the result can also be buffered.</li>
<li><b>POST</b> is used to add new records.</li>
<li><b>PUT</b> is used to add or change a resource.</li>
<li><b>DELETE</b> is used for delete resources.</li>
</ul>
The data can be returned in a number of formats, but for portability the most common formats include XML (POX) and JSON.
</p>
<h3>WCF and REST</h3>
<p align="justify">
The <b>REST</b> architecture is becoming increasingly common, and WCF provides attributes, methods, and types with which you can build and access REST Web Services quickly and easily.
<ul>
<li><b>WebHttpBinding:</b> An binding that uses the HTTP transport and text message encoder.</li>
<li><b>WebBehavior:</b> This is an endpoint behavior that will modify the dispatch layer on all operations on a contract. The modifications cause messages to be dispatched to methods on your service based on URIs and HTTP verbs.</li>
<li><b>WebServiceHost:</b> This is a ServiceHost-derived class that simplifies the configuration of a web-based service.</li>
<li><b>WebOperationContext:</b> This is a new context object, which contains the state of the incoming request and ongoing response, and simplifies coding against HTTP using WCF.</li>
<li><b>WebGetAttribute/WebInvokeAttribute:</b> Operation behaviors that are applied as attributes on a ServiceContract's methods. <tt>WebGetAttribute</tt> is for GET verb and <tt>WebInvokeAttribute</tt> is for all the other verbs. It also tells the dispatcher how to match the methods to URIs and how to parse the URI into method parameters.</li>
</ul>
The following table shows the properties of both <tt>WebGetAttribute</tt> and <tt>WebInvokeAttribute</tt>.
<table>
<tr>
<td><b>Method</b></td>
<td>The HTTP verb the method should respond to.</td>
</tr>
<tr>
<td><b>UriTemplate</b></td>
<td>The definition of the URI the CLR method should respond to.</td>
</tr>
<tr>
<td><b>RequestFormat</b></td>
<td>Enumeration that specifies the format for deserializing the request (Xml or Json).</td>
</tr>
<tr>
<td><b>ResponseFormat</b></td>
<td>Enumeration that specifies the format for serializing the response (Xml or Json).</td>
</tr>
<tr>
<td><b>BodyStyle</b></td>
<td>Enumeration that specifies whether the request and the response data should be wrapped in an element with the same name as the CLR method name. Bare is typically used with RESTful services.</td>
</tr>
</table>
</p>
<p align="justify">
The essential components to construct a <b>REST</b> Service with WFC can be found in <b>System.ServiceModel.Web</b> assembly.
However, the most important part of the process is designing the schema that you will use to provide access to the resources exposed by the service.
So the main idea behind <b>REST</b> is to design your URIs in a way that makes logical sense based on your resource set. The URIs should, if possible, make sense to the application that consumes the data.
</p>
<p align="justify">
Depending on the volume of data in the database, a query might retrieve a large number of items, therefore, it makes sense to provide additional query parameters that a user can specify to limit the number of items returned.
</p>
<h3>Implementing a simple RESTful Service Example with WCF and Oracle.</h3>
<p align="justify">
In this example, we will develop a WCF RESTful service by using Oracle HR Sample Schema, ODP.NET, ADO.NET and Visual Studio 2015.
You can learn about the HR Schema in this <a href="http://xomalli.blogspot.com/2019/01/oracle-recipe-4-how-to-retrieve-list-of.html" target="_blank">post</a>, I have written to introduce you to this schema.
The following illustration shows the components in the Employee service that I have written for this post.
</p>
<div><b>Fig 1. Components of our Employee RESTFul service.</b></div><br/>
<div>Step 1:Write the POCO object.</div><br>
<div><b>Fig 2. Employee entity class.</b></div><br/>
<div>Step 2: Write the following utility class.</div><br/>
<div><b>Fig 3. Utility class.</b></div><br/>
<div>Step 3: Write the following helper class adding the Oracle Data Provider for .NET.</div><br/>
<div><b>Fig 4. DAC data access class.</b></div><br/>
<div>Step 4:Define and write the service contract.</div><br/>
<div><b>Fig 5. Service contract interface.</b></div><br/>
<div>Step 5: Write the service implementation class.</div><br/>
<div><b>Fig 6. Service implementation class.</b></div><br/>
<div>Step 6: Write the following <i>Employee.svc</i> file. Use the <i>WebServiceHost</i> class, the <tt>WebServiceHost</tt> class inherits from <tt>ServiceHost</tt> and automatically assigns the correct binding and behavior to your endpoint. You no longer need to be concerned about the content of your configuration file.</div><br/>
<div><b>Fig 7. EmployeeService.svc File.</b></div><br/>
<div>Step 7: Write the configuration file and store the connection string for the Oracle HR schema.</div><br/>
<div><b>Fig 8. Configuration File.</b></div><br/>
<p align="justify">
<div>In this example a GET at <i>http://localhost/WcfRest/EmployeeService.svc/Employees</i> shows all the employees in the HR database.</div>
<div><b>Fig 9. Running the example, querying all the employees.</b></div><br/>
Here a GET at <i>http://localhost/WcfRest/EmployeeService.svc/102</i> show only one employee with the ID 102.
<div><b>Fig 10. Querying only one employee.</b></div><br/>
<div>Also, a GET at <i>http://localhost/WcfRest/EmployeeService.svc/110</i> show the employee with the ID 110.</div>
<div><b>Fig 11. Querying another employee.</b></div><br/>
</p>
Martín A. Márquezhttp://www.blogger.com/profile/10939957618126542300noreply@blogger.comtag:blogger.com,1999:blog-6494419861240446187.post-26967922914076448242019-01-06T21:17:00.003-08:002023-10-01T12:40:45.987-07:00How to retrieve the list of schema objects with Oracle Data Provider for .NET (ODP.NET)<p align="justify">
In this post, I am going to introduce you one of the sample schemas that Oracle provides as we learn Oracle database: The HR Schema.
But before I introduce it specifically, we need to understand what is a schema.
</p>
<p align="justify">
I've found two definitions for the same term, a schema basically can be:
</p><ul>
<li>A logical container for data structures</li>
<li>A collection of objects associated with the database.</li>
</ul>
<p align="justify">
Oracle draws the distinction between logical and physical structures: structures that are visible at a disk level or operating system level such as data files, control files and redo log files are considered physical structures, on the contrary, objects like tablespaces, schemas, tables, views , and any database objects are considered logical structures.
A container in this context means that a single schema name can contain many different objects, these logical objects are known as schema objects, and they are made up of structures such as:
</p><ul>
<li><b>Table:</b> A table is the basic logical storage unit in the Oracle database; composed of rows and columns.</li>
<li><b>Cluster:</b> A cluster is a set of tables physically stored together as one table.</li>
<li><b>Index:</b> An index is a structure created to help retrieve data more quickly and efficiently.</li>
<li><b>View:</b> Logically represents subsets of data from one or more tables.</li>
<li><b>Store procedure:</b> Stored procedures are predefined SQL queries stored in the data dictionary designed to allow more efficient queries.</li>
<li><b>Sequence:</b> Numeric value generator.</li>
<li><b>Package:</b> Named PL/SQL modules that group related stored procedures, functions, and identifiers.</li>
<li><b>Synonyms:</b> Gives alternative names to objects.</li>
</ul>
<p></p>
<h3>The HR schema sample</h3>
<p align="justify">
The HR schema is a sample schema that Oracle makes available for learning purposes.
You can install sample schemas using DBCA (DataBase Configuration Assistant) or you can get it from the following link:
</p><div><a href="https://www.oracle.com/technetwork/developer-tools/datamodeler/sample-models-scripts-224531.html">https://www.oracle.com/technetwork/developer-tools/datamodeler/sample-models-scripts-224531.html</a></div>
<div><b>Fig 1. Entity Relationship Diagram for HR Schema.</b></div><br />
<p align="justify">
Schemas present a layer of abstraction for your data structure and it helps to avoid a problem called <i>name collision</i>.
Let me show you an example: if we don't use schemas a user called Bob can create a table called <i>Employees</i>,
and then another user called Alice cannot create a table called <i>Employees</i> on the same schema that Bob,
but Alice can create a table in a different schema.
Other users can access or execute objects within a user's schema once the schema owner grants privileges.
</p>
<h3>List schema objects using .NET</h3>
<p align="justify">
The following code example uses <a href="https://www.oracle.com/technetwork/developer-tools/visual-studio/overview/index.html" target="_blank">Oracle Developer Tools for Visual Studio (ODT)</a> to retrieve the list of schema objects that are available and then displaying them.
You can download the project source code for this link.
<div><b>Fig 2. Retrieving the list of schema objects of <i>hr</i> user.</b></div>
<div><b>Fig 3. Retrieving the list of schema objects of <i>system</i> user.</b></div>
<ul>
<li><b>Note 1:</b> You will find in many Oracle's texts that some people using schema and user indistinctly.</li>
<li><b>Note 2:</b> Oracle validates that the users have permissions to use the schema objects being accessed by theirs.</li>
</ul>
Martín A. Márquezhttp://www.blogger.com/profile/10939957618126542300noreply@blogger.comtag:blogger.com,1999:blog-6494419861240446187.post-21252843979816169902018-07-24T21:37:00.003-07:002023-10-01T12:36:51.312-07:00Oracle Recipe #3: How to Execute a query that returns a Single Row with the method GetOracleValues.<p align="justify">
if you want to obtain multiple values from a database, you can call the <b>executeReader</b> method once on a <b>OracleCommand</b> object, to execute a SQL statement that returns a collection of values in a single row result.
</p>
<p align="justify">
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.
</p>
<h3>To obtain a single row from a database.</h3>
<p align="justify">
<ol>
<li>Open a <b>OracleConnection.</b></li>
<li>Create and initialize a <b>OracleCommand</b> object.</li>
<li>Call the ExecuteReader method on the command object. Assign the return value from this method to a data reader variable.</li>
<li>Call the Read method on the data reader object to move to the first(and only) row in the result set.</li>
<li>Call the <i>GetOracleValues</i> method on the data reader object. Pass an object array as a parameter to retrieve the scalar results of the query.</li>
<li>Convert each element in the array to an appropriate data type, if necessary.</li>
<li>Close the <b>OracleDataReader</b> object.</li>
<li>Dispose the <b>OracleCommand</b> object.</li>
<li>Close the database connection.</li>
</ol>
</p>
<p align="justify">
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.
</p>
<div><b>Fig 1. Using the GetOracleValues of an OracleDataReader object.</b></div><br>
Martín A. Márquezhttp://www.blogger.com/profile/10939957618126542300noreply@blogger.comtag:blogger.com,1999:blog-6494419861240446187.post-67949721875242002962018-07-09T19:42:00.001-07:002023-10-01T12:35:21.502-07:00Oracle Recipe #2: How to execute a query that returns a Scalar result with OracleCommand.<p align="justify">
<ol>
<li>Microsoft ADO.NET command objects have an <b>ExecuteScalar</b> method, which enables you to execute a query that returns a single result.</li>
<li>Open a database connection.</li>
<li>Create and initialize a command object.</li>
<li>Call the <b>ExecuteScalar</b> method on the command object.</li>
<li>Convert the return value from <b>ExecuteScalar</b> into an appropriate data type.</li>
<li>Dispose the command object.</li>
<li>Close the database connection.</li>
</ol>
<p align="justify">
The following example, show how to execute a query that determines the average salary from the table employees on the HR schema provided by <a href="https://www.oracle.com/database/technologies/appdev/xe.html" target="_blank">Oracle Database XE</a>.
The example assume that the query does not return a NULL result.
</p>
<div><b>Fig 1. OracleCommand ExecuteScalar method code example.</b></div><br>
Martín A. Márquezhttp://www.blogger.com/profile/10939957618126542300noreply@blogger.comtag:blogger.com,1999:blog-6494419861240446187.post-15763072623832034252018-07-05T08:12:00.004-07:002023-10-01T12:33:41.960-07:00Utilizando las clases de ADO.NET en Oracle.<p align="Justify">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.</p>
<p>Aquí esta la clase para manejar la conexión, se llama <b>OracleDataBase</b></p>
<!-- Oracledatabase Class -->
<div><b>Fig 1. Clase para manejar la conexion a la base de datos.</b></div><br>
<div>Utilizo otra clase llamada <i>OracleDataBaseCommand</i> para auxiliarme con los comandos.</div>
<div><b>Fig 2. Clase auxiliar para ejecutar los comandos en la base de datos.</b></div><br>
<p>Su utilización dentro de una clase que sirva para persistir o extraer datos sería de la siguiente manera.</p>
<div><b>Fig 3. Clase que utiliza las clases auxiliares para guardar un objeto.</b></div><br>
<div><b>Fig 4. Clase principal que crea, actualiza y consulta un cliente en la base de datos.</b></div><br>
Martín A. Márquezhttp://www.blogger.com/profile/10939957618126542300noreply@blogger.comtag:blogger.com,1999:blog-6494419861240446187.post-11479851540594247922018-06-22T13:53:00.002-07:002023-10-01T12:30:38.686-07:00C# Recipe 3: How to format a string as currency<p align="Justify">
You can use the <i>String.Format()</i> 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.
</p>
<div><b>Fig 1. Example of how strings are formatted.</b></div><br>
<div><b>Fig 2. Displays a localized currency value.</b></div><br>
Martín A. Márquezhttp://www.blogger.com/profile/10939957618126542300noreply@blogger.comtag:blogger.com,1999:blog-6494419861240446187.post-1639071611336574532018-06-21T10:05:00.001-07:002023-10-01T12:29:06.613-07:00How to connect an Oracle Data Source by using ADO.NET<h3>Step 1: Provide a connection string</h3>
<p align="justify">
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.
</p>
<ul>
<li><b>Persist Security Info:</b> if is false, the data source does not return security-sensitive if the connection is open.</li>
<li><b>User ID and Password:</b> The data source login and password to use if you are not using integrated security.</li>
<li><b>Integrated Security or Trusted_Connection:</b> 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.</li>
<li><b>Data Source:</b> The name or network address of the data source instance.</li>
<li><b>Initial Catalog or Database:</b> the name of the database.</li>
<li><b>Connection Timeout:</b> 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.</li>
</ul>
<div><b>Fig 1. Provide a connection string.</b></div><br>
<h3>Step 2: Retrieve a connection string from an application configuration file.</h3>
<p align="justify">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.</p>
<div><b>Fig 2. Create and return an OracleConnection object.</b></div><br>
<h3>Step 3: Handle connection events</h3>
<p align="justify">
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.
</p>
<ul>
<li><b>InfoMessage:</b> 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.</li>
<li><b>StateChage:</b> Occurs when a connection changes from the closed state to the open state or from the open state to the closed state.</li>
</ul>
<p align="justify">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 <b>InfoMessage</b> event instead.</p>
<h3>Step 4: Handle connection exceptions</h3>
<p align="justify">
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.
</p>
<div><b>Fig 3. Step 3 and 4: Handle connection events and exceptions, you can see the example below.</b></div><br>
<p align="justify">The following code show how to test each step in C# code.</p>
<div><b>Fig 4. The code to test our classes.</b></div><br>
<div><b>Fig 5. The program wrote the events in the log.</b></div><br>
Martín A. Márquezhttp://www.blogger.com/profile/10939957618126542300noreply@blogger.comtag:blogger.com,1999:blog-6494419861240446187.post-93282409060936112018-06-10T17:52:00.001-07:002023-10-01T12:19:17.494-07:00Oracle Recipe #1: How to generate an IDENTITY column using a sequence <p align="justify">
Primary keys can be created using either numeric or character data types, with one exception: Oracle does not have the same concept of <b>identity columns</b> as MS SQL Server.
</p>
<h3>What is an Identity Column?</h3>
<p align="justify">
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 <b>sequence</b>.
</p>
<p align="justify">
The <b>Sequence</b> 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.
</p>
<p align="justify">
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: <i>categories</i> and <i>publishers</i>.
</p>
<div>Each table will use a IDENTITY column as PRIMARY KEY.</div>
<div><b>Fig 1. The categories and publishers catalog.</b></div><br>
<div><b>Fig 2. Script to create both tables.</b></div><br>
<p align="justify">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.</p>
<div><b>Fig 3. Script to create database objects: triggers and sequences.</b></div><br>
<p align="justify">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.</p>
<div><b>Fig 4.Querying the tables.</b></div><br>Martín A. Márquezhttp://www.blogger.com/profile/10939957618126542300noreply@blogger.comtag:blogger.com,1999:blog-6494419861240446187.post-81490277085751714282018-06-07T19:15:00.001-07:002023-10-01T12:15:47.344-07:00Understanding delegates with C#<p align="justify">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.</p>
<p align="justify">Delegates allow you to write code that can dynamically change the methods that it calls.</p>
<p align="justify">A delegate contains a reference to a method rather than the method name.</p>
<p align="justify">By using delegates, you can invoke a method without knowing its name. Calling the delegate will actually execute the method referenced by the delegate.</p>
<p align="justify">To use a delegate, you must follow these steps:
<ol>
<li>First, define it using the reserved keyword delegate.</li>
<li>Second, instantiate it.</li>
<li>Third, write the implementation with the same return value and signature of your delegate.</li>
</ol>
</p>
<div><b>Fig 1. Steps to use a delegate.</b></div><br>
<p align="jsutify">A delegate is similar to an interface. It specifies a contract between a caller and an implementer.</p>
<p align="justify">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.</p>
<div><b>Fig 2. Sample using delegates.</b></div><br>
<p align="justify">Using delegates is a solution much simpler than using function pointer.</p>
<div><b>Fig 3. Testing the program.</b></div><br>
<div><b>Fig 4. Another test.</b></div><br>
Martín A. Márquezhttp://www.blogger.com/profile/10939957618126542300noreply@blogger.comtag:blogger.com,1999:blog-6494419861240446187.post-9075793096491900372018-05-19T07:35:00.003-07:002023-10-01T12:13:09.594-07:00C# Recipe 2: How to calculate the date of the Easter Sunday.<p align="justify">
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.
</p>
<p align="justify">
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.
</p>
<p>The following code calculates the easter sunday for a given year:</p>
<div><b>Listing 1. The main program</b></div><br>
<div><b>Listing 2. The Util class</b></div><br>
<div><b>Fig 1. Running the sample, output 1</b></div><br>
<div><b>Fig 2. Running the sample, output 2</b></div><br>
<div><b>Fig 3. Running the sample, output 3</b></div><br>
Martín A. Márquezhttp://www.blogger.com/profile/10939957618126542300noreply@blogger.comtag:blogger.com,1999:blog-6494419861240446187.post-23729695912550354302018-01-25T23:12:00.004-08:002023-10-01T12:04:05.858-07:00How to calculate a leap year with C#<p align="justify">
The Gregorian Calendar is the most widely used calendar in the world today.It is a reform of the Julian calendar, proposed by <b>Aloysius Lilius</b>, and decreed by <b>Pope Gregory XIII</b>, from whom it was named, on 24 February 1582 by papal bull <i>Inter gravissimas</i>
</p>
<div><b>Fig 1. Pope Gregory XIII </b></div><br/>
<div>
</div><br />
<p align="Justify">
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:
</p>
<p align="justify">
<q>
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.
</q>
The following application shows how to calculate a leap year.
</p>
<div><b>Fig 2 Testing the application.</b></div><br />
<div><b>Fig 3 Running a second test.</b></div><br />
Martín A. Márquezhttp://www.blogger.com/profile/10939957618126542300noreply@blogger.comtag:blogger.com,1999:blog-6494419861240446187.post-27367595059031862112018-01-07T10:50:00.002-08:002023-10-01T12:00:49.371-07:00Understanding Interfaces with C#<p align="justify">
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.
</p>
<p align="justify">
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.
</p>
<p align="justify">
Imagine a group of objects that all share the same ability: they fly. You can construct a public interface, called <i>Flyer</i>, that supports three operations: <i>TakeOff</i>, <i>Land</i> and <i>Fly</i>.
</p>
<div><b>Fig 1. The interface flyer and airplane class diagram</b></div><br>
<div><b>Listing 1 The Flyer code</b></div><br>
<div><b>Listing 2 The Airplane code</b></div><br>
<p align="justify">There can be multiple classes that implement the Flyer interface, as shown of the next figure</p>
<div><b>Fig 2. Multiple implementations of the Flyer interface.</b></div><br>
<p align="justify">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.</p>
<div><b>Fig 3. A mixture of inheritance and implementation.</b></div><br>
<p align="justify">
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.
</p>
<p align="justify">
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
</p>
<div><b>Fig 4. A mixture of inheritance and implementation.</b></div><br>
<p align="justify">
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.
</p>
<div><b>Listing 3 The code for granting permission</b></div><br>
<div><b>Fig 5. Running the sample</b></div><br>
Martín A. Márquezhttp://www.blogger.com/profile/10939957618126542300noreply@blogger.com