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.


martes, 13 de agosto de 2019

How to use Multiple Active Result Sets with ADO.NET

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.

To access multiple result sets using SqlDataReader objects, multiple SqlCommand objects will need to be used. When MARS is enabled, each command object used adds an additional session to the connection.

The following program demonstrates how to use a Sql Server Connection with MARS enabled.

Fig 1. MARS-enabled connection string

martes, 16 de julio de 2019

How to execute simple Database Queries with VB .NET

The SqlCommand class in the .NET Framework Data Provider has four methods that you can use to execute SQL statements:

  1. ExecuteScalar: Executes a query that returns a single scalar value.
  2. ExecuteReader: Executes a query that returns a result set.
  3. ExecuteNonQuery: Executes a data update statements or a catalog update statement.
  4. ExecuteXmlReader: Executes a query that returns an Extensible Markup Language (XML) result set, this method is only avaliable in the SqlCommand class.

To execute a simple database query

  1. Import the System.Configuration namespace
  2. Use the ConfigurationManager.ConnectionStrings property to get a collection of connection strings from the application configuration file.
  3. Index into the collection of connection strings by using the programmatic name of the connection string you want to access.
  4. Use the ConnectionString property to get the connection string information.
  5. Create a connection object.
  6. Create a command object.
  7. If you want to execute an SQL statement, set the CommandType property of the command object to the CommandType.Text enumeration value. If you want to call a stored procedure, set the CommandType property of the command object to the CommandType.StoredProcedure enumeration value.
  8. Call the Open method on the connection object.
  9. Call the ExecuteScalar method on the command object. Assign the result to a suitably typed variable.
  10. Call the Close method on the connection object.

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.

Fig 1. Main program
Fig 2. App config
Fig 3. Output program

jueves, 11 de julio de 2019

Understanding OOP Inheritance with Python

One of the most common goals for the OOP is code reusability. Characteristics such as inheritance contributes to achieving this goal.

Inheritance

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 Person as its superclass.

Fig 1. Inheritance
Fig 2. Person Class

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.

Fig 3. Employee Class

Who inherits the talk() method of the Person class to implement inheritance in this example:

Fig 4. Main program

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.

Fig 4. Run the example
$ py Sample1OOP.py

lunes, 29 de abril de 2019

Understanding RESTFul (POST, PUT and DELETE) services with Windows Communication Foundation (WCF) and Oracle XE.

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.

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.

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.

Use the [WebInvoke] 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.

In the following example, I will build a REST WCF Service to enable insert, update and delete operations for Oracle HR Schema.

You can learn about the HR Schema in this post.

The following table shows the URIs and the parts of the interface that I will implement for each URI in the example.

URI Method Output Input
/employees POST bool An Employee Object
/employees/{id} PUT bool An employee Object with id specified.
/employees/{id} DELETE bool An employee Id

The main steps for this exercise are as follows:

  1. Use the EmployeesDac class, which contains the method for accessing the database.
  2. Write the EmployeesServiceImplementation class with the following code (fig 1).
    Fig 1. EmployeeServiceImplementation.cs
  3. Write a new interface called IEmployeesServiceContract and type the following code(fig 2).
    Fig 2. IEmployeeServiceContract.cs
  4. Write the EmployeesService.svc file that references the service implementation with the following code (fig 3).
    Fig 3. EmployeeService.svc
  5. Finally, add the following config file (fig 4)
    Fig 4. Web.config

Testing the service with Soap UI.

The WCF service that you have built runs the same way as a regular Web application and is hosted by a Web Server.

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.

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.

Testing the HTTP-POST request, after completing the execution, the result window displays the JSON Response.
Fig 5. HTTP-POST Request

Testing the HTTP-PUT request after completing the execution, the result window displays the JSON Response.
Fig 6. HTTP-PUT Request

Testing the HTTP-DELETE request after completing the execution, the result window displays the JSON Response.
Fig 7. HTTP-DELETE Request

sábado, 9 de marzo de 2019

User Identification and Authentication with Transact-SQL

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.

Fig 1. The database diagram.

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.

A simple but fully functional example is shown below.

Fig 2. The T-SQL code.

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 HASHBYTES .

lunes, 18 de febrero de 2019

Oracle Recipe #5 How to execute Oracle parameterized commands with ODP.NET

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:

  1. Open a database connection,use OracleConnection.
  2. Create and initialize an OracleCommand object.
  3. 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.
  4. Execute the command by calling the ExecuteScalar, ExecuteReader, ExecuteXmlReader, or ExecuteNonQuery method, as appropriate for the type of SQL statement.
  5. Use the return value obtained by executing the command.
  6. Dispose the command object.
  7. Close the database connection.

The following example shows how to execute a SQL statement that updates employee by employee id (please, check this post for further information).
The SQL statement requires the following parameters: prmFirstName , prmLastName, prmEmail, prmPhoneNumber, prmHireDate, prmSalary,prmCommission and prmEmployeeId.

Fig 1. The application code.

sábado, 12 de enero de 2019

Understanding RESTFul services with Windows Communication Foundation (WCF) and Oracle HR Schema

What Are RESTful Web Services?

REST 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:

  • HTTP or HTTPS may be used as the transfer protocol.
  • URLs including query strings are used to address resources.
  • Representation formats supported range from HTML and XML to JSON and ATOM.
  • A Simple and intuitive programming interface is achieved by using HTTP verbs and status codes.
  • Statelessness in the interaction between clients and services.

REST 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: resources and actions. 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.

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.

  • GET is used exclusively to retrieve data and, therefore, the result can also be buffered.
  • POST is used to add new records.
  • PUT is used to add or change a resource.
  • DELETE is used for delete resources.
The data can be returned in a number of formats, but for portability the most common formats include XML (POX) and JSON.

WCF and REST

The REST 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.

  • WebHttpBinding: An binding that uses the HTTP transport and text message encoder.
  • WebBehavior: 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.
  • WebServiceHost: This is a ServiceHost-derived class that simplifies the configuration of a web-based service.
  • WebOperationContext: This is a new context object, which contains the state of the incoming request and ongoing response, and simplifies coding against HTTP using WCF.
  • WebGetAttribute/WebInvokeAttribute: Operation behaviors that are applied as attributes on a ServiceContract's methods. WebGetAttribute is for GET verb and WebInvokeAttribute 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.
The following table shows the properties of both WebGetAttribute and WebInvokeAttribute.
Method The HTTP verb the method should respond to.
UriTemplate The definition of the URI the CLR method should respond to.
RequestFormat Enumeration that specifies the format for deserializing the request (Xml or Json).
ResponseFormat Enumeration that specifies the format for serializing the response (Xml or Json).
BodyStyle 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.

The essential components to construct a REST Service with WFC can be found in System.ServiceModel.Web 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 REST 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.

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.

Implementing a simple RESTful Service Example with WCF and Oracle.

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 post, 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.

Fig 1. Components of our Employee RESTFul service.

Step 1:Write the POCO object.

Fig 2. Employee entity class.

Step 2: Write the following utility class.

Fig 3. Utility class.

Step 3: Write the following helper class adding the Oracle Data Provider for .NET.

Fig 4. DAC data access class.

Step 4:Define and write the service contract.

Fig 5. Service contract interface.

Step 5: Write the service implementation class.

Fig 6. Service implementation class.

Step 6: Write the following Employee.svc file. Use the WebServiceHost class, the WebServiceHost class inherits from ServiceHost 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.

Fig 7. EmployeeService.svc File.

Step 7: Write the configuration file and store the connection string for the Oracle HR schema.

Fig 8. Configuration File.

In this example a GET at http://localhost/WcfRest/EmployeeService.svc/Employees shows all the employees in the HR database.
Fig 9. Running the example, querying all the employees.

Here a GET at http://localhost/WcfRest/EmployeeService.svc/102 show only one employee with the ID 102.
Fig 10. Querying only one employee.

Also, a GET at http://localhost/WcfRest/EmployeeService.svc/110 show the employee with the ID 110.
Fig 11. Querying another employee.

domingo, 6 de enero de 2019

How to retrieve the list of schema objects with Oracle Data Provider for .NET (ODP.NET)

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.

I've found two definitions for the same term, a schema basically can be:

  • A logical container for data structures
  • A collection of objects associated with the database.

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:

  • Table: A table is the basic logical storage unit in the Oracle database; composed of rows and columns.
  • Cluster: A cluster is a set of tables physically stored together as one table.
  • Index: An index is a structure created to help retrieve data more quickly and efficiently.
  • View: Logically represents subsets of data from one or more tables.
  • Store procedure: Stored procedures are predefined SQL queries stored in the data dictionary designed to allow more efficient queries.
  • Sequence: Numeric value generator.
  • Package: Named PL/SQL modules that group related stored procedures, functions, and identifiers.
  • Synonyms: Gives alternative names to objects.

The HR schema sample

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:

Fig 1. Entity Relationship Diagram for HR Schema.

Schemas present a layer of abstraction for your data structure and it helps to avoid a problem called name collision. Let me show you an example: if we don't use schemas a user called Bob can create a table called Employees, and then another user called Alice cannot create a table called Employees 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.

List schema objects using .NET

The following code example uses Oracle Developer Tools for Visual Studio (ODT) to retrieve the list of schema objects that are available and then displaying them. You can download the project source code for this link.

Fig 2. Retrieving the list of schema objects of hr user.
Fig 3. Retrieving the list of schema objects of system user.
  • Note 1: You will find in many Oracle's texts that some people using schema and user indistinctly.
  • Note 2: Oracle validates that the users have permissions to use the schema objects being accessed by theirs.

martes, 24 de julio de 2018

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

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

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

To obtain a single row from a database.

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

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

Fig 1. Using the GetOracleValues of an OracleDataReader object.

lunes, 9 de julio de 2018

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

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

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

Fig 1. OracleCommand ExecuteScalar method code example.

jueves, 5 de julio de 2018

Utilizando las clases de ADO.NET en Oracle.

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

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

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

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

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

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

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

viernes, 22 de junio de 2018

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

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

Fig 1. Example of how strings are formatted.

Fig 2. Displays a localized currency value.

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.