WHAT'S NEW?
Loading...

Day 10 Programming in C# 70-483

Index


  • Introduction
  • Managing integrity
  • Using parsers
  • Regular expressions for validation
  • Validating JSON and XML
  • References

Introduction

This post is part of a series of post to help you prepare the MCSD certification, particularly the certification exam 70-483, based on the book:


You will find all the code available in the following GitHub repository. Lets talk a little bit about threads and how they work using a .Net development environment.

Managing integrity


The data used by your applications is really important and manage it properly will make your users feel they can rely on your tools. We are humans so we can make mistakes when using some particular web or desktop application. It's on our developer condition where we find the debt to handle this data accordingly to its type, so we can provide the best UX. In case your application crashes for some wrong data introduced by the user it's something you have to avoid but it's not the worst thing you can get. Imagine you work with a Live system used by thousands of users and you don't manage some particular information properly, and even that, your app doesn't crash. Then, that information will end up in you database as corrupt information.

Here is when data integrity has a main role. There are four different types of data integrity:
  1. Entity integrity: this refers to the entities saved within a database. Those need to be identified uniquely. This is achieved by using a primary key column which can be auto generated by the database or by the application.
  2. Domain integrity: this one stands for the information saved within an entity. Imagine you are saving the post code in  one of your entities. You need to ensure that the postcode field only saves real postcodes.
  3. Referential integrity: this one stands for the relation between entities. Imagine the relation between a table Employee and a table called Payroll.
  4. User-defined integrity: this refers to particular rules of your business like the number of orders per day your customers can create in the system.
Working with Entity Framework you can define different "conditions" within your entities by decorating its properties with the following attributes (System.ComponentModel.DataAnnotations.dll):
  • DataTypeAttribute: it helps you define which type of data your application will expect to be introduced by the user. This way, if you don't provide a valid email address within the email text field, you'll get an error message after validation is made.
  • RangeAttribute
  • RegularExpressionAttribute: for some special fields there are no standard validation rules like for dates, emails, strings... then you have to define you own ones.
  • RequiredAttribute: very common to have required fields in a web form.
  • StringLengthAttribute
  • CustomValidationAttribute: you can create your entire validation attribute.
  • MaxLengthAttribute
  • MinLenthAttribute
Another important data integrity feature in databases is called transactions. It helps you to create a window time when different queries are triggered against your database and if at some point something failed and the process cannot be continued, then you can revert all those changes applied within the transaction in an action called: rollback.

Using parsers

The use of parser if very common in programming. It is mainly used to transform text variables into its real type. For example, a string variable could contain 'true' and by calling bool.Parse(value); you end up with a real boolean type containing true. In case you are not sure if the transformation process will work without errors, there's a method called TryParse which has the same behavior as the Parse() method but additionally returns a true or false whether the transformation worked or not. This is really helpful in case you're not completely sure if the transformation will work. This method is perfect when you parse user inputs.

In case you want to parse numbers, there are some extra functions you can use to apply some rules during the number transformation process. For example, you can use the CultureInfo class from the System.Globalization namespace to apply rules over currencies regarding the money symbol or the decimal character.

In a similar way you can parse DateTime types and apply rules for different time zones, cultural and so by using the following overload methods:

  • Parse(string)
  • Parse(string, IFormatProvider)
  • Parse(string, IFormatProvider, DateTimeStyles)
The .Net framework offers also the Convert() method to perform transformations between base types (Boolean, Char, Byte, Int, Single, Double, Decimal, DateTime, String...). The only difference between Parse/TryParse and Convert is that the last one allows null values. Instead of trigger an exception, this method supplies the default value for the supplied type. Parse only takes string types as input, Convert accepts other types as input parameter.

Regular expressions for validation


A regular expression is a pattern used to parse or find matches in strings. They are very flexible and you will find lots of them already written and ready to be used in sites like http://regexlib.com/. You can define your own regexs to match your business rules like post codes, email addresses or phone formats allowed in your site. In the following example we define a regex to match email addresses:

^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$

Really useful when working with user inputs to validate.

Validating JSON and XML


This is a format widely used when communicating separated systems. JSON or JavaScript Object Notation is light weight compared with XML which has a stricter schema. .Net offers a library to de-serialize JSON called JavaScriptSerializer (System.Web.Script.Serialization) and turns it into an object you can access, ie:

var result = serializer.Deserialize<Dictionary<string, object>>(json)

With the previous call you are converting your json object into a Dictionary of <string,object> types. If the json object is invalid you'll get an exception with an "Invalid object passed in" message in. See here below an example of a JSON object:

 {"menu": {
   "id": "file",
   "value": "File",
   "popup": {
     "menuitem": [
       {"value": "New", "onclick": "CreateNewDoc()"},
       {"value": "Open", "onclick": "OpenDoc()"},
       {"value": "Close", "onclick": "CloseDoc()"}
     ]
   }
 }
}

In XML you can describe its content with an XSD (XML Schema Definition) providing a way to validate your XML file, as well as defining some rules to fill your xml up. Visual Studio provides a tool called xsd.exe which you can use to generate xsd files. See the following XSD example:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="Address">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="Recipient" type="xs:string" />
        <xs:element name="House" type="xs:string" />
        <xs:element name="Street" type="xs:string" />
        <xs:element name="Town" type="xs:string" />
        <xs:element name="County" type="xs:string" minOccurs="0" />
        <xs:element name="PostCode" type="xs:string" />
        <xs:element name="Country" minOccurs="0">
          <xs:simpleType>
            <xs:restriction base="xs:string">
              <xs:enumeration value="IN" />
              <xs:enumeration value="DE" />
              <xs:enumeration value="ES" />
              <xs:enumeration value="UK" />
              <xs:enumeration value="US" />
            </xs:restriction>
          </xs:simpleType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

This rules define a way to validate your xml file when you request someone to send his address to your system. You can start playing with the XMLReader and XMLDocument classes in your next .Net application in order to validate your xml files through your xsd files

References

https://github.com/tribet84/MCSD/tree/master/mcsd
http://regexlib.com/
https://es.wikipedia.org/wiki/JSON
https://en.wikipedia.org/wiki/XML_Schema_(W3C)

0 comments:

Post a Comment