jueves, 2 de julio de 2020

Performing Disconnected Operations: Programming with DataSets and Datatables with C#

DataSets and DataTables

You create an instance of a DataSet by calling the DataSet 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 DataTable objects and add them to an existing DataSet. You can add DataColumn objects to the Columns collection of the DataTable. You can set constraint information for a DataTable by using the Primary Key property of the DataTable and the Unique property of the DataColumn objects.

The schema, or structure, of a table is represented by columns and constraints. You define the schema of a DataTable by using DataColumn objects as well as ForeignKeyConstraint and UniqueConstraint 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.

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 DataColumn, set the AutoIncrement property of the column to true. The DataColumn will then start with the value defined in the AutoIncrementSeed property, and with each row added the value of the AutoIncrement column will increase by the value held in the AutoIncrementStep property of the column. For AutoIncrement columns, it is recommended that the ReadOnly property of the DataColumn be set to true.

When you identify a single DataColumn as the Primary Key for a DataTable, the table automatically sets the AllowDBNull property of the column to false and the Unique property to True. For multiple-column primary keys, the AllowDBNull property is automatically set to false, but the Unique property is not set to true. However, a UniqueConstraint corresponding to the primary key is added to the Constraints collection of the DataTable.

You can use Constraints to enforce restrictions on the data in a DataTable to maintain the integrity of the data. Constraints are enforced when the EnforceConstraints property of the DataSet is true. There are two kinds of constraints in ADO.NET: the ForeignKeyConstraint and the UniqueConstraint. By default, both constraints are created automatically when you create a relationship between two or more tables by adding a DataRelation to the DataSet.

		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);
		

Understanding DataAdapters

Because the DataSet is independent of the data source, a DataSet 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 DataAdapter. Each ADO.NET provider has a DataAdapter object. A DataAdapter is used to retrieve data from a data source and populate tables within a DataSet. The DataAdapter also persists changes made to the DataSet back to the data source.

The DataAdapter has four properties that are used to retrieve data from and persist data to the data source. The SelectCommand returns data from the data source. The InsertCommand,UpdateCommand, and DeleteCommand are used to manage changes at the data source.

The following example 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 SqlDataAdapter with Store procedures. This example uses the following database to manage a collection of courses and one category per course.

Fig 1. The structure of the sample database.
Fig 2. Running the example, showing the courses.
Fig 3. Adding a new category.
Fig 4. Deleting a row.
Fig 5. Adding a new course on the DataTable.
Fig 6. Save changes of the DataSet back to the Data Source.

viernes, 15 de mayo de 2020

Arreglos unidimensionales en C#

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.

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.

Fig 1. Estructura de un arreglo

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 int, uint, long o ulong. o un valor de un tipo que pueda promoverse en forma implícita a uno de estos tipos.

Cada instancia de un arreglo conoce su propia longitud y proporciona acceso a esta información a través de la propiedad Length esta propiedad es de solo lectura y no puede cambiarse.

Declaración de arreglos

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.

Fig 2. Declaración de arreglos

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.

Fig 3. Aplicando la función promedio (AVG) a un arreglo

Fig 4. Aplicando la función suma (SUM) a un arreglo

sábado, 25 de abril de 2020

Stored Procedures in MS SQL Server

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.

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.

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.

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.

Reading Data with Stored Procedures

The following example creates a stored procedure to return all authors in the table.

After you create this stored procedure, you will execute it by running the following statement:

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.

Adding Data with Stored Procedures

The OUTPUT Parameter

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.

The following example shows how to create a simple store procedure that utilizes the OUTPUT keyword:

To execute this store, run the following script:

Modifying Data with Stored Procedure

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.

The following example will delete a book and erase all its relations in the table [Authorbook]

To test this store run the following script

Download the scripts for this example.

jueves, 5 de marzo de 2020

Operaciones Bitwise (a nivel de bits) con C#

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.

Los tipos de datos donde usualmente aplican estos operadores son: los numéricos y las enumeraciones.

La siguiente tabla muestra los tipos numéricos, su longitud en bytes y su valor en decimal.


Así por ejemplo si tenemos valores decimales representados en variables byte (8 bits hasta 255 en decimal)

byte a = 22;
byte b = 33;

Internamente su representación en binario es:

22 = 00010110
33 = 00100001

si utilizamos variables de tipo short (16 bits hasta 65,535)

short c = 666;
short d = 6666;

su representación en binario es:

666 = 00000010 10011010
6666 = 00011010 00001010

Así con cada tipo numérico siempre agrupando las cadenas de bits de 8 en 8.
La siguiente tabla muestra los operadores bitwise, su significado y su resultado.



Para ejecutar el programa de ejemplo, descargar el proyecto desde este enlace.

Al ejecutarlo veremos los siguientes resultados:






  Descarga el proyecto.

viernes, 25 de octubre de 2019

Understanding method overriding with Python

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: Understanding OOP Inheritance with Python

To override the inherited constructor of the Person class, follow these steps: Enter a new declaration of the constructor method within the Employee 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.

Fig 1. Modified constructor

In the main program add two new lines with the following two phrases:

"John works in department"
and concatenate the department attribute of the object John, with a period and
"John's email is "
and concatenate the email attribute of the object John with a period.

Fig 2. Main program

Run the code. As you can see the Jonh instance of the Employee class now accepts three parameters, because the Person constructor has been overriding. In addition, the talk method remains the same inherited from Person.

Fig 3. Running the example
$ py SampleOverriding.py

sábado, 19 de octubre de 2019

Understanding principles of security: Integrity, Creating a Hash

Hashing Properties

Hashing is one-way mathematical function that is relatively easy to compute, but significantly harder to reverse.

  1. The input can be any length.
  2. The output has a fixed length.
  3. The hash function is one way and is not reversible.
  4. Two different input values will almost never result in the same hash values.

Hashing algorithms

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.

Modern Hashing Algorithms

Two of the most popular modern hashing algorithms are MD5 and SHA.

Message Digest 5 (MD5) Algorithm

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.

Secure Hash Algorithm

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:

  1. SHA-224 (224 bits)
  2. SHA-256 (256 bits)
  3. SHA-384 (384 bits)
  4. SHA-512 (512 bits)

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#.
Download the source code here.

Fig 1. Running the program, compare different algorithms.
Fig 2. Running the program, comparing and contrasting different outputs.

When choosing a hashing algorithm, use SHA-256 or higher as they are currently the most secure. In production implement SHA-256 or higher.

jueves, 5 de septiembre de 2019

Understanding principles of security: Integrity

The principles of Security

The foundational principles of security are: confidentiality, integrity and availability. These principles known as the CIA triad is a guideline for information security for an organization.

Integrity

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.

Hashes and Checksum

The process of hashing 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.

Hashing 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 hash functions use complex mathematical algorithms.

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 hash will always be 128 bits long. Hashing is not an encryption algorithm. Instead, hashing 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.
The hashed value 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.

Fig 1. Summary of hashing algorithms

A hash tells you nothing about the data, but it uniquely identifies it. The hashed value is simply there for comparison.

Fig 2. The hash function operates on fixed-size blocks of data

Writing a simple Hash Calculator with AngularJS, HTML5, C# and WCF.

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 System.Security.Cryptography.HashAlgorithm to achieve encryption.

  1. The user enters the text to encrypt, selects the algorithm to use.
  2. The user submits the information to the service in order to get the hash code.
  3. The hash web service presents the hash code to the user.
Testing with different algorithms, we can see the length of the output.

Fig 3. Using the MD5 algorithm.
Fig 4. Using the SHA1 algorithm.
Fig 5. Using the SHA256 algorithm.
Fig 6. Using the SHA384 algorithm.
Fig 7. Using the SHA512 algorithm.
Fig 8. Changing the text, we can see a totally different output, but without no changes in the length.

Conclusion

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.