WHAT'S NEW?
Loading...

MCSD Web Applications: Using LINQ to Objets and XML; Fundamentals of serialization

Index

  • Intro
  • Async and Await
  • What is a database
  • What is LINQ
  • LINQ Demo

Intro

Let's talk today about data. Bring data is typically a high cost operation that's why we need to use always the perfect data storage system regarding our requirements. There are techniques like asynchronous communications which will help us on speeding our systems. How to retrieve that data is an important subject and decide which approach to use will be also discussed.


Async and Await

Async and await simplify asynchronous programming in .Net. Async and await allow asynchronous code to resemble the structure of synchronous code. Methods marked with async may return Task as the Task-based Asynchronous Pattern (TAP) defines. The async keyword instructs the compiler to allow await. The await keyword instructs the methods to return The await keyword instructs the compiler to resume execution within the same context after the operation is complete. 

In the following example we run an asynchronous operation in our call to DownloadStringAsync which is defined within the WebClient component in the .Net framework. This functions performs some operation in background, which means, the execution process in our app is never stopped. We don't know when this task will be completed, that's why we've published an event called "Completed" which a class can subscribed to and be notified when the completion occurs.



using System;
using System.Net;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class AsynchronousExample
    {
        public event EventHandler Completed;

        void GetHtml(string url)
        {
            var client = new WebClient();
            client.DownloadStringCompleted += client_DownloadStringCompleted;
            client.DownloadStringAsync(new Uri(url));
        }

        private void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (Completed != null)
                Completed(this, e);
        }
    }
}


In our next example we are using the reserved word "async" to decorate our method. See the type returned here is a Task. This means when we trigger probably a long running process which will return immediately a Task object. It won't stop to the completion of the asynchronous method. This task object will contain the result but it will be uncompleted until the DownloadStringTaskAsync finishes.


using System;
using System.Net;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class AsynchronousExample
    {
        private async Task GetHtmlWithAsync(string url)
        {
            var client = new WebClient { };
            return await client.DownloadStringTaskAsync(new Uri(url));
        }
    }
}

What is a database

  • A database is a data store
  • Data stored in a database is structured
  • Data stored in a database may be related (Referential integrity)
  • A database provides a way to access / query data (Optimized by indexes)

SQL DB Types

  • Windows Azure SQL Database
  • Local Network SQL Database
  • Local Machine SQL Server Express 
  • Application SQL LocalDB
  • Application SQL CE
  • Other providers: Oracle, SqLite, MySql, DB2

Types of access to a database: how do we talk to the database
  • Low-Level
    • Manual queries
    • DbDataReader
  • Object Relationship Models (ORM): allow you to conceptualize the model of you db.
    • Entity Framework
    • nHibernate

What is LINQ

Language Integrated Query:

  • is a general-purpose Query Language
  • is an integrated part of the .Net languages
  • is Type Safe and has Intellisense
  • includes operators like Traversal, Filter and Projection
  • can be optimized with compiler versions
  • can be invoked using its Query Syntax
  • can be invoked using its Method Syntax

LINQ Demo

See here enclosed some examples about how to use the LINQ library in a .Net environment. I'll try to show you how to get the even and odds number from a list. Then we'll move forward sorting a bunch of letters in a handy way

var data = Enumerable.Range(1, 50);

// even or odd
// method syntax
var method = // IEnumerable
    data.Where(x => x % 2 == 0)
        .Select(x => x.ToString()); // Projection: take data and transform it into text

// query syntax
var query = // IEnumerable
    from d in data
    where d % 2 == 0
    select d.ToString();

var projection =
    from d in data
    select new
    {
        Even = (d % 2 == 0),
        Odd = (d % 2 != 0),
        Value = d,
    };


I'm using different approaches in order to get odd's and even numbers. I'm presenting the result in different ways also. For the method and the query variable, I'm storing the values as strings. Within the projection variable, I'm actually creating small structures containing three values, the first two save a boolean true/false and the last one stores the current value.

var letters = new[] { "A", "C", "B", "E", "Q" };

// query syntax
var sortAsc =
    from d in data
    orderby d ascending
    select d;

// method syntax
var sortDesc =
    letters.OrderByDescending(x => x);


var values = new[] { "A", "C", "A", "C", "A", "D" };

var distinct = values.Distinct();   // remove duplicates
var first = values.First();         // error if "values" is empty
var firstOr = values.FirstOrDefault();  // default if "values" is empty
var last = values.Last();
var page = values.Skip(2).Take(2);


See how in the previous example I'm working with a couple of character lists. For the first list I sort the characters using linq query sintax and linq method syntax respectively. For the last list, I wanted to show you the potential of  this language which allows you to performs actions like, remove duplicates, get the first/last or even skip some values and take more than one.

Really powerful library which I'm sure will help you to short out your code and present your future projects in a really professional way.

References

http://www.microsoftvirtualacademy.com/training-courses/developer-training-with-programming-in-c
https://msdn.microsoft.com/en-us/library/hh873175.aspx
https://msdn.microsoft.com/es-es/library/bb397926.aspx

Really interesting MVC resource

Hiya,

Recently I faced this interesting resource from James Chambers, definitely worth to take a look at it.

James will guide you in how to create your own MVC web application using technologies as C#, Bootstrap, Razor and more.

All of them contained in your Visual Studio application.

Please, see here below a summary with the main topics of this 30 days course:


The 30 Day Breakdown

Warming Up

Enhancing Our Views

Exploring Bootstrap

Special Announcement!
Adding Some Sparkle
So, You’ve Got People Logging In
Wrapping Up With Some More Bootstrap
Thanks a lot James!


MCSD Web Applications: File System and leveraging Web services

Index

  • Intro
  • File System
  • Modify files
  • What are web services
  • REST Services
  • Asynchronous programming

Intro

I want to talk today about how to work with the file system and why we need it, so let's talk about the different scenarios where you'll be using the System.IO .Net library.


Besides we'll be scratching the surface of a couple of web services called "SOAP" and "REST", which you could be already familiar with. Finally, asynchronous programming will come over.

File System

Benefits of read and write from the file system:

  • Show existing data to user
  • Integrate user-provided data
  • Serialize objects out of memory
  • Persist data across sessions
  • Determine environment configuration

How to write:

  • This is simplified with Framework methods; 
    • open / shut (File.WriteAllText / File.ReadAllText) (see example below)
  • Open for reading to keep open and keep writing.
  • Open as stream for large payloads and real-time processing: let's say you want to see a movie through Netflix, you don't download the entire movie file into your PC and then you start watching. You download just a small peace of that huge file depending on where you are in the movie.
See an example of how write/read a file using .Net


var dir = System.IO.Directory.GetCurrentDirectory();
var file = System.IO.Path.Combine(dir, "File.txt");
var content = "how now brown cow?";

// write
System.IO.File.WriteAllText(file, content);

// read
var read = System.IO.File.ReadAllText(file);
Trace.Assert(read.Equals(content));


How do we find files?

  • Get Windows folder with Environment Special Folder
  • Get the Current folder with File.IO.GetCurrentDirectory()
  • Use Isolated Storage dedicated to the current application: 
    • dedicated application storage not used very often by developers.
  • Anything Else.Caveat: Windows Store App development

// special folders
var docs = Environment.SpecialFolder.MyDocuments;
var app = Environment.SpecialFolder.CommonApplicationData;
var prog = Environment.SpecialFolder.ProgramFiles;
var desk = Environment.SpecialFolder.Desktop;

// application folder
var dir = System.IO.Directory.GetCurrentDirectory();

// isolated storage folder(s)
var iso = IsolatedStorageFile
    .GetStore(IsolatedStorageScope.Assembly, "Demo")
    .GetDirectoryNames("*");

// manual path
var temp = new System.IO.DirectoryInfo("c:\temp");

In the previous example you can see how to reach the typical windows directories, your app and your isolated storage folder in .Net. Finally directoryInfo provides you useful info about certain directory like size, rights, etc. You are not allowed to do whatever you want in your PC, at some folder you probably need some rights in order to read, write or... delete!

Modify files

Please see here a small piece of code to show you how to edit files, following these steps:

  • Iterate through files using GetFiles()
  • Rename / Move with System.IO methods
  • Get File Info with System.UI.FileInfo

// files
foreach (var item in System.IO.Directory.GetFiles(dir))
    Console.WriteLine(System.IO.Path.GetFileName(item));

// rename / move
var path1 = "c:\temp\file1.txt";
var path2 = "c:\temp\file2.txt";
System.IO.File.Move(path1, path2);

// file info
var info = new System.IO.FileInfo(path1);
Console.WriteLine("{0}kb", info.Length / 1000);


See how we get all the files defined in the "dir" variable (let say "C:\temp") using GetFiles. Then we print all those files placed in the "dir" directory using GetFileName. Then moving a file to the same folder which purely it's a renaming operation. Finally, we'll get some meta data using the FileInfo method and we use the result of that method to print on the console the length of that file.

What are web services

See some web services (WS) features:

  • Web services encapsulate implementation: this means we don't know how a third party service is implemented. You can be using Facebook web services but you don't know how their WS are implemented.
  • WS expose to disparate system.
  • WS allow client systems to communicate servers: which is great because allow you to separate the different parts when you're building a new application.
    • Web protocols (HTTP, GET, POST, etc)
  • WS are important to Service Oriented Architecture
    • With and without metadata
    • Loose coupling: when a system has different moving parts depending on others and add something new means add a lot of extra changes.

What is SOAP? Easy, it's a type of web service. See some features:


  • SOAP is a standard for returning structured data from a Web Service as XML
    • Envelope (Header / Body / ...)
  • SOAP handling is a built-in feature of Visual Studio
The idea is to serialize the information provided by our application into our web service to send that information to our clients. Then our clients will de serialize that information in order to be able to read it.

The downside of this is the de/serialization process is heavy. At first, save 400 bytes it's not a big deal, but in case of companies like Facebook which could face millions of requests per day means a lot. There is a few emerging new technologies to bypass this problem...

REST Services

REST (Representative State Transfer)

  • ...is becoming a common, industry standard
  • ...does not require XML parsing
  • ...does not require message header
  • ...is generally human-readable
  • ...uses less band-with than SOAP
  • ...services typically return XML or JSON
  • ...JSON is JavaScript Object notation
    • JSON is becoming a common industry standard
    • JSON is generally a lighter payload than XML (or SOAP)

See how to implement a basic JSON reader using the .Net framework:

using System;
using System.Collections.Generic;
using System.Net;
using System.Web.Script.Serialization;

namespace ConsoleApplication1
{
    public class Program
    {
        public static void Main()
        {
            var url = new Uri("http://footballpool.dataaccess.eu/data/info.wso/TopGoalScorers/JSON/debug?iTopN=10");
            var client = new WebClient();
            var json = client.DownloadString(url);

            // deserialize JSON into objects
            var serializer = new JavaScriptSerializer();
            var data = serializer.Deserialize>(json);

            // use the objects
            foreach (var item in data)
                Console.WriteLine("Player: {0,16}, Goals: {1}", item.sName, item.iGoals);

            Console.Read();

            // Output
            // Player:  James Rodríguez, Goals: 6
            // Player:   Thomas Mueller, Goals: 5
            // Player:            Messi, Goals: 4
            // Player:           Neymar, Goals: 4
            // Player:       van Persie, Goals: 4
            // Player:   Andre Schurrle, Goals: 3
            // Player:          Benzema, Goals: 3
            // Player:   Enner Valencia, Goals: 3
            // Player:    Islam Slimani, Goals: 3
            // Player:           Robben, Goals: 3
        }
    }

    public class ObjectReturnedByTheWebService
    {
        public string sName { get; set; }
        public int iGoals { get; set; }

    }
}


If you want to try this solution, you could create a new console application and then add a new reference to System.Web.Extensions in order to get the JavaScriptSerializer class working. The URL I'm using it's a free web service with free football stats called: http://footballpool.dataaccess.eu/. I'm passing the value 10 when building the URL, but you can change that in order to get top3, top5...

I use the WebClient class to call the service and then I de-serialize the message because it comes as a JSON message. Try to go to that URL to see how it looks. There is a small class called ObjectReturnedByTheWebService which is used to convert that json message from plain text into a proper .Net class using a auto mapper.


As an example of how using REST services, please see how to implement an image recognition system in one of my first posts for this blog.

Asynchronous programming

Asynchronous maximizes resources on multi core systems, by allowing units of work to be separated and completed. Asynchronous programming frees up the calling system, especially a user interface, as to not wait for long operations. Don't using this approach will constrain your resources. It improves the user experience using your application by freezing the screen giving a feel like your app is hanging in a long running task.

References

MCSD Web Applications: Assemblies, WinMD Diagnostics and Instrumentations

Index


  • Intro
  • What are assemblies
  • Sharing assemblies
  • WinMD
  • What is instrumentation
  • References

Intro

Today we'll talk about assemblies and their relation with namespaces. How to share code between different projects in Windows 8 and what instrumentation refers to (see image below)


What are assemblies

Assemblies:
  • An assembly is a container for a set of resources and types.
  • Assemblies can be referenced by other assemblies.
  • Some assemblies are specific to certain technologies.
  • In Visual Studio, an assembly equates to a Project, so normally, you will find different namespaces in your solution, but that solution will create just a single assembly. 
Namespaces:
An example of a typical namespace is "System". At some point, you'll finish creating different namespaces like a web component, a data access layer, a windows service and all of them will be interacting between them, but not in the same place, not in the same namespace. Namespace is a logical container.

Assembly vs Namespace

Assembly Namespace
An assembly is a grouping or physical container of code A namespace is a grouping or logical container of code
Can contain one or more namespace Can span multiple files
Can be granted security permissions Can span multiple assemblies
Can be digitally signed Defines a scope
Defines a scope

You need to be careful with assemblies you want to add to your solution and you get from a web site you're not sure can trust. Even if they provide the functionality they are supposed, that assembly could have some nefarious code or be a back-door to your application creating a huge vulnerability in your app. That's why the assemblies normally are digitally signed. 

So, we got an assembly and we can mark it as strong named, which will allow us to specify a particular private key, that will be used into the compilation process. Visual Studio will inject that signature (RSA remember our previous class about encryption) into our component, so if we purchased that signature from a trusted site then you are digitally singing that assembly with your identifier so anyone can verify this assembly comes from you. It's also a prerequisite to sign your assemblies in order to install them into the GAC (Global Assembly Cache).

The GAC will help us to add "using" statements at the top of our classes which will be referencing a particular class that could be placed in the GAC folder of our computer.

Sharing assemblies

Class Libraries are the Visual Studio project type that creates an assembly that can be shared

Portable Class Libraries are the Visual Studio project type that creates an assembly that can be shared across platforms. Imagine you create some logic for a desktop application but you want to share it with an Xbox and Windows Mobile applications. 

Unfortunately, you don't have all the functionality in a desktop application for the other two projects because they use different versions of the .Net framework. You could finish using a portable class library (uses only the lowest-common-denominator), specify the projects you want to target (Xbox, mobile...) and done. Bare in mind, you need to use the shared features between those separated project, which means, the more projects you want to target the less functionalities available you will be using.

WinMD

WinMD (Windows Meta Data) applications (...or Windows RunTime component) are used specifically for Windows 8 development. It comes really handy when you want to share code among your different project applications. They create an assembly for Windows Store Apps and can be shared across languages. JavaScript cannot be used to create WinMDs (but can use other WinMD projects), only the .Net languages or C++.

Example: simple sum function defined in a Windows RunTime Component project between a Windows Store application and a JavaScript application.

  1. First, you'll need to create a new Windows Store project (XAML). Within this project add the minimum graphic components to perform a sum operation (three textboxes for each number, one for the '+' and one last box for the equal). 
  2. Now we can add the logic to perform that numerical operation but we don't want to add that business logic into our interface, we want to do it in a separate project. Create a new Windows RunTime Component Project and add the following logic to perform sum operations:
  3. namespace WindowsRuntimeComponent1
    {
        public sealed class Operator
        {
            public static double SumThemUp(double v1, double v2)
            {
                return v1 + v2;
            }
        }
    }
    
  4. Now is the time to add a call to our sum method from our Window Store project. First of all, you'll need to a reference to the Windows Runtime project into our windows store solutions, see the code below:
  5. using Windows.UI.Xaml.Navigation;
    
    namespace App1
    {
        public sealed partial class MainPage : Page
        {
            public MainPage()
            {
                this.InitializeComponent();
            }
    
            private void Button_Click_1(object sender, RoutedEventArgs e)
            {
                var v1 = double.Parse(t1.Text);
                var v2 = double.Parse(t2.Text);
                t3.Text = WindowsRuntimeComponent1.Class1.SumThemUp(v1, v2);
            }
        }
    
    }
    
  6. Now we have our graphic interface (Windows Store App) and our business logic (the sum op.) split, we can add a new project and make a similar call to our plus operation. This will show you how to share assemblies and more important, how to split functionality logically. 
  7. Add a new project and select Other languages/JavaScript/Windows Store/Blank app. See how the magic of WinMD allow us to call a C# method from a JavaScript file:
  8. <!DOCTYPE html>
    
    <html lang="en" xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta charset="utf-8" />
        <title>App2</title>
    
        <script>
            function dowork() {
                t3.value = WindowsRuntimeComponent1.Class1
                    .sumThemUp(t1.value, t2.value);
            }
        </script>
    </head>
    <body>
    <input type="text" name="t1" value="1"/>
    +
    <input type="text" name="t2" value="2"/>/>
    <button onclick="dowork();">=</button>
        <input type="text" name="t3" value="0" />
    </body>
    </html>
    
    


  9. What is instrumentation

    Instrumentation is code that reports performance information. We are not interested in every part of our program, that's why we select only some important parts: a method, a db call... Analytics for your code.
    Telemetry aggregates instrumentation for analysis. In case of some applications, you can find out some menus not that accessible for the user and react changing the interface. You might want to create a baseline first time you run your code using telemetry, in order to know if the performance goes better or not.
    Diagnostics or Analysis is the use a telemetry to track causes of errors or identify trends. Finally, the main purpose is provide a great UX, by designing our interface or validating its performance.

    Performance Counter is a key point in instrumentation and it refers to sampling for a single operation. It can be the time your app takes to authenticate a user login, the time a password encryption process takes, anything. It's helpful to show the trends in a process and find out performance gaps. You need to have special permissions to use them and use counters responsibly, you don't want to take down the performance of you app while you are measuring the performance of your app. See an example of using PerformanceCounter class in a .Net app: 

    var perfCounter = new PerformanceCounter {
         CategoryName = category,
         CounterName = counter,
         MachineName = machine,
         ReadOnly = false,
    };
    perfCounter.IncrementBy(10);
    

    References



MCSD Web Applications: Encryption techniques, Hashing and Symmetric encryption

Index


  • Intro
  • Encryption techniques
  • Hashing
  • Symmetric and asymmetric encryption
  • References

Intro

Welcome back! Today is all about how to encrypt your data, different types of encryption, hashing messages and symmetric encryption



Encryption techniques

An encryption algorithm makes data unreadable to any person or system until the associated decryption algorithm is applied. It does not hide data; it makes it unreadable. People use to confuse encryption with compression and they are not the same.

Types:

  • File encryption: this is the most basic encryption pattern for .net developers. It's very useful because you will end encrypting your files and any windows user won't be able to read the content of your encrypted messages. This method uses Windows data protection mechanism behind the scenes but this is a kind of short cut. Ex:
  • const string dataToProtect = "This is a bunch of super secret content!";
    var dataToProtectAsArray = Encoding.Unicode.GetBytes(dataToProtect);
    
    var fileName = Path.Combine(Environment.GetFolderPath(
        Environment.SpecialFolder.MyDocuments),
        "MyDataFile.txt");
    
    // Encrypt a file in the file system
    File.WriteAllText(fileName, dataToProtect);
    
    // now we can encrypt it - only we can access it now
    File.Encrypt(fileName);
    
  • Windows data protection: this allows you to protect data in memory you might want to save into a database or provide via some web service. In the following example I'm encrypting some data defining a particular scope, which will be used to decrypt it, so it's an extra level of security. Ex:
  • // Windows Data Protection (we can also protect for the LocalMachine too)
    // note, the null can be replaced with a byte[] for additional entropy
    var wdpEncryptedData = ProtectedData.Protect(
        dataToProtect, null, DataProtectionScope.CurrentUser);
    
    var wdpUnEncryptedData = ProtectedData.Unprotect(
        wdpEncryptedData, null, DataProtectionScope.CurrentUser);
    var wdpUnencryptedString = Encoding.Unicode.GetString(
        wdpUnEncryptedData);
    
    Debug.Assert(dataToProtect.Equals(wdpUnencryptedString));
    
  • Hashing: the main usage is signing data, which you could think like a wax sealed in an envelope which proves it hasn't been opened since the last time that whoever signed it.
  • Symmetric and asymmetric: this encryption technique is focused in sharing data beyond your user's space.

Think about encryption as a process you ran over the message you want to hide. It's a intensive process and the more intensive the more secure but more resources/time you'll need to perform the conversion of your message.

Hashing

Mainly used for signing and validation. A hash is a value which always is generated in the same way for the data that needs to be encrypted. Is a one-way encryption algorithm, which basically means you can't revert the transformation applied (except, maybe, by brute-force attack). It's fast depending on the algorithm. It's also useful to storing information in a shorter way. For example, you might want to store a hashed password in a database.

There are different approaches to create this codes like:
  • MD5: 16 characters which could produce collisions (same hash from different messages) because of the small amount of characters.
  • SHA (SHA1, SHA256, SHA384, SHA512): 256 is the most common. Both 384 and 512 take the same amount of time to execute, so go for the 512 in order to get more security.
The longer the hash you want to create the smaller the chances to get any collisions. In the following example, I'll show you how to encrypt a message using SHA256:

// hashing - one-way encryption

// this represents a hashed password stored in a database
var storedPasswordHash = new byte[]
{
    148, 152, 235, /* ... more characters ... */
};

var password = Encoding.Unicode.GetBytes("P4ssw0rd!");
var passwordHash = SHA256.Create().ComputeHash(password);

// nice convenience method - can also supply a custom comparator
if (passwordHash.SequenceEqual(storedPasswordHash))
{
    Console.WriteLine("Password match!");
}

As you can see in the previous example, first we are performing a conversion of our password into an array of bytes. That will be the content we'll provide into the SHA256 algorithm instance. Finally we compare the result of the encryption saved in "passwordHash" with the already storedPasswordHash variable which contains the value from the database. If everything matches we'll get the "Password match!" message printed in the console.

Symmetric and asymmetric encryption

For this particular encryption approach, we need to use a key in order to perform our encryption. For the symmetric type we use just one key, and for the asymmetric two. First type is faster. There are five algorithms in the .Net framework:

  • AES (recommended)
  • DES
  • RC2
  • Rijndael
  • TripleDES


Asymmetric aka "Public key" encryption uses two keys as you know. One is used for encryption and the other for decryption. Commonly used for digital signatures and typical .Net frameworks are:

  • DSA
  • ECDiffielHellman
  • ECDsa
  • RSA (recommended)


References




MCSD Web Applications: Data validation, Data contracts and Unhandled exceptions

Index


  • Intro
  • Data validation
  • Data contracts
  • Unhandled exceptions
  • References

Intro

Today I'm talking about some interesting topics about how to defend your applications from users. Why do you have to know this? Simply. It's because users never know what they are doing and this is fact. In this post we'll try to validate the information provided by the user so we can get rid of some errors.


Data validation

Data validation is testing values introduced to an application, via a service, file or data entry) against expected values and ranges. Imagine a typical register form in a web and a naughty user setting is name in the DOB field, his DOB inside the name textbox and so... This technique will help you to avoid these users and some errors like these:

  • Prevent overflow
  • Prevent incorrect results
  • Prevent undesirable side-effects
  • Provide guidance to systems of users
  • Prevent security intrusions

But... before starting validating the info introduced by our users (or any other source), first we need to validate our data as developers. At this stage the compiler appears but not validating data, mainly validating object type, better said, validates the envelope but not the content.

Another tool you can use to prevent wrong data is Assert. You can create a test set in your application to prevent bad use or modification of your methods.

As a reaction to wrong data you can raise exceptions in your code. Depending on which one is the error you've detected you can trigger one of the following exceptions (there are plenty of these in the .net framework):
  • System.ArgumentException
  • System.ArgumentOutOfRangeException
  • System.ArgumentNullException
See the following example of exception usage:

public override void SetName(string value)
{
    // validate empty
    if (string.IsNullOrWhiteSpace(value))
        throw new ArgumentNullException("value");

    // validate conflict
    if (value == this.Name)
        throw new ArgumentException("value is duplicate");

    if (value.Length > 10)
        throw new ArgumentException("value is too long");

    this.Name = value;
}

In the previous example you can appreciate how we can validate (if) the content of a particular property and react proving an exception to the caller class.

Data contracts

Again, data validation. The phrase "design by contract" comes from the ancient programming language "Eiffel" and is a unique system that can replace all other approaches to data validation.

Microsoft data contract is an add-on you can install in Visual Studio. The add-on will help you to stablish all the assumptions you want in your code to be validated. The aim of a contract is to document your code as well as external APIs and then, as part of the compiling phase you will get your code checked.

The big difference between using Exceptions or Data contracts is that the first one, only validates data when our app is running, but Data contracts validate our conditions in runtime and statically in design. Code contracts have preconditions (requires) and post-conditions (ensures). 

Please see here below an example of data contracts usage:


In the set method of our awesome dog class we call the static method "requires" from the Contract class where we first pass a condition and the we setup a message when that condition is not covered. In our get method we stablish a contract to avoid returning empty strings by using the "ensures" method.

With data contract we can even configure build errors in order to avoid data validation mistakes. We can also call "Contract.EndContractBlock();" method just after our bunch of if-then-throw statements and this will turn all of those exceptions into contract violations.

Note: As a good practice you shouldn't use contracts for security checking because security exception could ignore that contract violation, but everything else makes complete sense.

Unhandled exceptions

Now is time to handle exceptions, not just throw them, but also, track the flow of our app to provide proper error messages and validations.

What happens with all of those exceptions thrown by your code or the runtime outside of a try block. The runtime handles all exceptions protecting the system, not your app. This causes: instability and termination. It's now when a try/catch/finally statement is really useful, see:

public void UpdateGeoCoordinates(Job job)
{
    var address = job.GetAddress(); // get the address as string

    var gps = _locator.GetGpsCoordinates(address); // get the gps coords

    try
    {
        job.Lat = Double.Parse(gps.Item1, CultureInfo.InvariantCulture);
        job.Lng = Double.Parse(gps.Item2, CultureInfo.InvariantCulture);
    }
    catch (FormatException)
    {
        Logger.Warn("Job [{0}], format error when convert '{1}', '{2}' to a Double.", job.Id, gps.Item1, gps.Item2);
    }
    catch (OverflowException)
    {
        Logger.Warn("Job [{0}], overflow when convert '{1}', '{2}' to a Double.", job.Id, gps.Item1, gps.Item2);
    }
    catch (Exception ex)
    {
        Logger.Warn("Job [{0}], Exception message: {1}", job.Id, ex.Message);
    }
    finally
    {
        ReleaseResources();
        Logger.Warn("Process executed");
    }
}


In the code above, I'm converting some GPS coordinates from string into a double data type. This is a real example from a production project.

I've defined some different catch blocks (FormatException and OverflowException) to show you how you can grab a particular error and react accordingly to that error. As last catch, I've used generic Exception to assure that I'll always got any error from my code.

You can think of "finally" as a kind of optional promise. It's something reliable that you know will always be executed, maybe releasing resources or by providing a message. Keep in mind is an optional block in the try/catch statement so don't have to provide it by default.

What is also important to think about here is assumptions. Consider you opened files in the "try" block, then, one of those files couldn't be opened, which produces run your catch block because the exception. If you planned to close those resources (files) within the finally statement you probably end in another error because of that invalid resource which produced the first exception. So be very careful with your finally blocks in order to introduce more errors.

References

http://www.microsoftvirtualacademy.com/training-courses/developer-training-with-programming-in-c
http://techterms.com/definition/compiler