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

0 comments:

Post a Comment