quinta-feira, 8 de dezembro de 2016

How to use Blade Without Laravel

Blade is so nice, but sometimes you have to work on legacy projects or with frameworks not friendly. So, looking at the web i found the windwalker that until now is doing great. So, here i'll show a basic step-by-step to use Blade without Laravel. First, we'll configure composer, so install composer if you don't have it.
Create the composer.json:
 {  
      "autoload":{  
           "psr-4":{  
                "App\\": "app",  
                "Windwalker\\": "vendor/windwalker"  
           }  
      },  
      "require": {  
     "windwalker/renderer": "2.*",  
     "illuminate/view": "4.*"  
   }  
 }  
Here, i set the namespace for my work environment: App and Windwalker to use in my initial load. The require pull the libs. Now composer install(if you did not have) && composer update(if you updated) && composer auto-load
Create a folder init and write blade.php:
 <?php   
 use Windwalker\Renderer\BladeRenderer;  
 $paths = array('./view');  
 $renderer = new BladeRenderer($paths, array('cache_path' => './cache'));  
Set the path to your view folder and to a cache folder.
 <?php  
 require 'vendor/autoload.php';  
 require 'init/blade.php';  
 $data = ['title' => 'Nice!'];  
 $html = $renderer->render('index', $data);  
 echo $html;  

Create index.blade.php file in view folder.
 @section('title')  
      @if( isset($title) )  
           {{ $title }}  
      @else  
           Without Title  
      @endif       
 @stop  
 <html>  
 <head>  
 <title>@yield('title')</title>  
 </head>  
 <body>  
 <p>Body</p>  
 @include('footer')  
 </body>  
 </html>  
I created a footer.blade.php file to show the include.
Check this on: Github
References:
http://asika.windspeaker.co/post/3975-use-blade-template-engine-outside-laravel
https://packagist.org/packages/philo/laravel-blade

quarta-feira, 23 de novembro de 2016

Using Intermediate Language Disassembler

Sometimes, with me very often, we do some “nonsense”. Some code analysis tool may help us. If you’re not very confident you could use Intermediate Language Disassembler or ildasm.exe. Here i present some little tips using Intermediate Language Disassembler. First make sure you have VS, and open vs native tools. With vs native tools open enter ildasm. Now we’ll make a basic program with C#.
 class Program  
   {  
     static void Main(string[] args)  
     {  
       Console.WriteLine("ok");  
     }  
   }  
Now you can build and after, open ildasm File > open and select your .exe and double click in main method, you will see this:
 .method private hidebysig static void Main(string[] args) cil managed  
 {  
  .entrypoint  
  // Code size    13 (0xd)  
  .maxstack 8  
  IL_0000: nop  
  IL_0001: ldstr   "ok"  
  IL_0006: call    void [mscorlib]System.Console::WriteLine(string)  
  IL_000b: nop  
  IL_000c: ret  
 } // end of method Program::Main  
So, no big deal, we have the string literal stored opcode following call to the WriteLine. Now we’ll do a potentially dangerous operation, we’ll write a method that expects an object, following we’ll pass a double. This will generate a box operation, so:
 class Program  
   {  
     static void Main(string[] args)  
     {  
       Console.WriteLine("ok");  
       double wrong = 2.3;  
       pass(wrong);  
     }  
     static void pass(Object wrong)  
     {  
       Console.WriteLine(wrong);  
     }  
   }  
Now we build and following we use ildasm:
 .method private hidebysig static void Main(string[] args) cil managed  
 {  
  .entrypoint  
  // Code size    35 (0x23)  
  .maxstack 1  
  .locals init ([0] float64 wrong)  
  IL_0000: nop  
  IL_0001: ldstr   "ok"  
  IL_0006: call    void [mscorlib]System.Console::WriteLine(string)  
  IL_000b: nop  
  IL_000c: ldc.r8   2.2999999999999998  
  IL_0015: stloc.0  
  IL_0016: ldloc.0  
  IL_0017: box    [mscorlib]System.Double  
  IL_001c: call    void Generics.Program::pass(object)  
  IL_0021: nop  
  IL_0022: ret  
 } // end of method Program::Main  
Now, we can see some nice things. First, we “discover” that our double is called float64, the 2.3 value(could not be different) is put as 2.2999999999999998 with the ldc.r8 opcode that pushes the value to the evaluation stack. Following we have our potentially Dracula: in the IL_0017 we have our box.
In MSDN:
In relation to simple assignments, boxing and unboxing are computationally expensive processes. When a value type is boxed, an entirely new object must be allocated and constructed. To a lesser degree, the cast required for unboxing is also expensive computationally. For more information, see Performance.

https://msdn.microsoft.com/en-us/library/yz2be5wk(v=vs.80).aspx

References:
https://msdn.microsoft.com/en-us/library/yz2be5wk(v=vs.80).aspx
https://app.pluralsight.com/library/courses/csharp-generics/table-of-contents

segunda-feira, 7 de novembro de 2016

Testing Repository with Laravel and Mockery

I was reading the awesome Taylor Otwell’s Book - Laravel From Apprentice To Artisan- https://leanpub.com/laravel and i’ll show some nice examples mixed with some code i did. So, let’s do dependency Injection:
 namespace App\Contracts;  
 interface ProductRepositoryInterface{  
      public function all();  
 }  
Now our Repo:
 <?php  
 namespace App\Repositories;  
 use App\Contracts\ProductRepositoryInterface;  
 use App\Product;  
 class ProductRepository implements ProductRepositoryInterface{  
      public function all(){  
           return Product::all()->toArray();  
      }  
 }  
Now we can use the Repo:
 namespace App\Http\Controllers;  
 use Illuminate\Http\Request;  
 use App\Http\Requests;  
 use App\Product;  
 use App\Contracts\ProductRepositoryInterface;  
 use Response;  
 class ProductController extends Controller  
 {  
      public function __construct(ProductRepositoryInterface $products){  
           $this->products = $products;  
      }  
      public function index(){  
           $products = $this->products->all();  
           return view('products.index', compact('products'));  
      }  
 }  
Don’t forget the Routes!!!! Now we can test:
 <?php  
 use App\Product;  
 use Illuminate\Foundation\Testing\WithoutMiddleware;  
 use Illuminate\Foundation\Testing\DatabaseMigrations;  
 use Illuminate\Foundation\Testing\DatabaseTransactions;  
 class ExampleTest extends TestCase  
 {  
   use DatabaseTransactions;  
   public function tearDown(){  
     Mockery::close();  
   }  
   public function testIndexActionBindsProductsFromRepository(){  
     $mock = Mockery::mock('App\Contracts\ProductRepositoryInterface');  
     $mock->shouldReceive('all')->once()->andReturn(['lol', 'kk']);  
     App::instance('App\Contracts\ProductRepositoryInterface', $mock);  
     $response = $this->action('GET', 'ProductController@index');  
     $this->assertResponseOk();  
     $this->assertViewHas('products', ['lol', 'kk']);  
   }  
 }  
We use DatabaseTransactions; to rollback the changes. In the test we mock our Interface and arrange telling that it gonna receive a call for all() and return array [‘lol’, ‘kk’]. Using App::instance we register that in the execution when the interface is requested it will throw our mock. With this we simulate a GET request with action(). The assertion is ok and our view has the array. Now we’ll use the factory, in database > factories register the following:
 $factory->define(App\Product::class, function (Faker\Generator $faker) {  
   return [  
     'title' => $faker->sentence  
   ];  
 });  
We used only the title for simplicity. Now we can do the following test:
 public function testProductsCreationAndJsonList(){  
     factory(Product::class, 3)->create();  
     $response = $this->action('GET', 'ProductController@getProducts');  
     $this->assertResponseStatus(200);  
 }  
With create() we insert 3 products in the database. With the action we simulate the request and assert the status. Now we put the getProducts():
 public function getProducts(){  
           $products = $this->products->all();  
           //refactoring this -> next POST!!!! we gonna make a class to implement the return and extend  
           if (empty($products)){  
                $arrResponse = ['error' => ['message' => 'No Product found', 'code' => 'Internal Code']];  
                return Response::json($arrResponse, 404);  
           }  
           return Response::json(['data' => $products], 200);  
      }  
In the next post we will refactor getProducts and extract a class. TY References: https://leanpub.com/laravel
https://laracasts.com/series/phpunit-testing-in-laravel
https://laravel.com/docs/5.2/mocking

quinta-feira, 29 de setembro de 2016

JS all the way

Angular, Node, Electron, Ionic, JS all the way. But, are these things good and proper for all kinds of apps? Of course, the answer is no, but i’m using these things a lot and these guys are saving me with portability and awesome apis. Use with caution. Is this JS domination or JS doom?

quarta-feira, 28 de setembro de 2016

A Drink App with Ionic

I'm developing a drink game with Ionic. In College, I played this so many times and now i've decided to make an app. The new version[v3] has support for english and Friends Mode. New things coming. Unfortunately, at the moment only Android is available and with apk. I'll try to put this on Play Store and App Store. The v3 can be downloaded at :

https://drive.google.com/file/d/0B-MDes2BI4gZVWNhTDFXSEhZcEk/view?usp=sharing

The v4 can be downloaded at :

https://drive.google.com/file/d/0B-MDes2BI4gZQTRELVFBcmFiOWs/view?usp=sharing



The v2 in Amazon Store:

https://www.amazon.com/Aldo-Lemos-drunkMe/dp/B01M197ROO/ref=sr_1_1?s=mobile-apps&ie=UTF8&qid=1475109747&sr=1-1&keywords=drunkme

terça-feira, 27 de setembro de 2016

Um App Simples com Ionic - Link para APK

Um dia desses brincando com o framework Ionic, resolvi criar um app baseado no jogo que muitos chamam de apertadinho, acabei não achando um jogo parecido para android ou ios. Um jogo simples, que consiste em escolher 3 números tal que o terceiro está entre os dois primeiros. Quem acertar o número escolhido pelo app ou por um jogador bebe ou paga o mico. Se o número escolhido durante a rodada não permite o próximo jogador escolher, quem pensou no número inicial tem que beber. A melhor forma de aprender é jogando, então baixe o apk e instale pelo link abaixo(não esqueça de permitir arquivos de fora da google play). Infelizmente, por enquanto só usuários de Android terão acesso, mas se poucos bugs forem achados faço um esforço para subir o app para Ios e Windows e fazer uma integração com facebook para você mostrar aos seus amigos que tem sorte. Por enquanto o app ficará no link abaixo e na amazon store.


Link para Amazon Store: https://www.amazon.com/Aldo-Lemos-drunkMe/dp/B01M197ROO/ref=sr_1_1?s=mobile-apps&ie=UTF8&qid=1475064324&sr=1-1&keywords=drunkme


Link direto: https://drive.google.com/open?id=0B-MDes2BI4gZRTNYSDJLWmh2OEE


sexta-feira, 23 de setembro de 2016

A Filter Problem: Using Angular and Laravel

It’s a common problem, mainly in web development, filter requests of all kinds. As an example, imagine that you have a table with products and your users must be able to filter data using status, codes, availability, price and so on. A simple (but bad) solution is verify the fields, concatenate some strings and build a query at runtime. This can generate problems, especially if you’re not using patterns and concatenating strings to build the query. At some point, the query is a monster that you cannot maintain. In this post, i present a solution based in some techniques. In the client i’ll use Angular to make requests. I’ll change the Angular symbol, because i’m using Laravel and Blade{{}}.But you can use @{{}}. However, i'll change to [[]] with:
 (function () {  
  'use strict';  
  let signChange = function($interpolateProvider){  
   $interpolateProvider.startSymbol('[[');  
   $interpolateProvider.endSymbol(']]');  
  };  
  angular.module("productsApp", [], signChange);  
 })();  
Following, we need to build the API:
 (function() {  
   'use strict';  
   angular.module('productsApp').factory('productsApi', ['$http', '$q', productsApi]);  
   function productsApi($http, $q) {  
     function getItems(params) {  
       var deferred = $q.defer();          
       $http.get(params)  
         .success(function(data) {  
           deferred.resolve(data);  
         })  
         .error(function() {  
           deferred.reject();  
         });  
       return deferred.promise;  
     }  
     return {  
       getItems: getItems  
     };  
   };  
 })();  
In the code above, we build the factory, that will return our object (revealing module pattern). Now, with the getItems() method we can use HTTP GET and defer promises. With the API, we can build our ListProductsController:
 (function () {  
  'use strict';  
  angular.module("productsApp")  
  .controller("ListProductsController", ['productsApi', '$scope',  
   ListProductsController]);  
  function ListProductsController(api, vm) {  
   function filter(params){  
    vm.dataLoading = true;  
    api.getItems(params).then(function(data){  
     vm.products = data.data;  
    }).finally(_=>{  
     vm.dataLoading = false;  
    });  
   }  
   vm.filter = function(){  
    filter("/api/products?"+ buildParams());  
   }  
   vm.filter();  
  };  
 })();  
In the Controller, we inject the api and the scope, the vm has a filter method to be called from the view. A simple dataLoading is created to feedback the user. The getItems() method is called and when it’s deferred we can access the data. You can build the params with angular or jquery, the attributes will represent the fields to filter. Now, we can do the server side. We’ll make a route for ‘/api/products’ and call getProducts() in the controller, code below:
 public function getProducts(ProductFilters $filters){  
  $quant = request()->get('quant');  
  $quant = empty( $quant ) ? 5 : $quant;  
  $products = Product::filter($filters)->simplePaginate($quant);  
  return json_encode($products);  
 }  
In getProducts(), we get the number($quant) of items that we’ll put for page. By default we set 5. And we call filter passing the ProductsFilters that we’ll use. Next, with simplePaginate to generate pages and return json encoded. Now, the model Product:
 <?php  
 namespace App;  
 use Illuminate\Database\Eloquent\Model;  
 use App\Traits\Filterable;  
 class Product extends Model  
 {  
   use Filterable;  
 }  
In Product, we just state that we’ll use the Trait Filterable:
 <?php  
 namespace App\Traits;  
 use Illuminate\Database\Eloquent\Builder;  
 use App\Filters\QueryFilters;  
 trait Filterable  
 {  
   /**  
    * Filter a result set.  
    *  
    * @param Builder   $query  
    * @param QueryFilters $filters  
    * @return Builder  
    */  
   public function scopeFilter($query, QueryFilters $filters)  
   {  
     return $filters->apply($query);  
   }  
 }  
Now, we are using Laravel scope and calling the QueryFilters method apply, to apply the filters. QueryFilters is the base Filter for our project, we could call this a Filterable-Strategy Pattern.
 <?php  
 namespace App\Filters;  
 use Illuminate\Database\Eloquent\Builder;  
 use Illuminate\Http\Request;  
 abstract class QueryFilters  
 {  
   /**  
    * The request object.  
    *  
    * @var Request  
    */  
   protected $request;  
   /**  
    * The builder instance.  
    *  
    * @var Builder  
    */  
   protected $builder;  
   /**  
    * Create a new QueryFilters instance.  
    *  
    * @param Request $request  
    */  
   public function __construct(Request $request)  
   {  
     $this->request = $request;  
   }  
   /**  
    * Apply the filters to the builder.  
    *  
    * @param Builder $builder  
    * @return Builder  
    */  
   public function apply(Builder $builder)  
   {  
     $this->builder = $builder;  
     foreach ($this->filters() as $name => $value) {  
       if (! method_exists($this, $name)) {  
         continue;  
       }  
       if (strlen($value)) {  
         $this->$name($value);  
       }  
     }  
     return $this->builder;  
   }  
   /**  
    * Get all request filters data.  
    *  
    * @return array  
    */  
   public function filters()  
   {  
     return $this->request->all();  
   }  
 }  
The QueryFilters apply method look at the request params and verify if the method exists, if the method exists, the param value will be passed to execute. With it, you can make the simple question, where are those methods? And the response is: We need to create A ProductFilters class that extends QueryFilters to put our strategy. So:
 <?php  
 namespace App\Filters;  
 use Illuminate\Database\Eloquent\Builder;  
 class ProductFilters extends QueryFilters  
 {  
   public function price($param){  
     if ($param)  
       return $this->builder->orderBy('price', 'desc');   
     return $this->builder->orderBy('price');   
   }  
   public function name($param){  
     return $this->builder->where('name', 'like', '%'.$param.'%');  
   }  
 }  
In the ProductFilters we implement our filters, in the example i ordered by price and searched by name. So, with this strategy, you can create new filters and filter models, we’ll just create the class to extend QueryFilters and implement our filters. You can/must use repositories, i’ll make another post about repositories. No big deal, no big sql, of course this can be improved. So improve this. TY References:
https://github.com/JeffreyWay
https://laracasts.com/skills/laravel
https://app.pluralsight.com/library/courses/angularui-fundamentals/table-of-contents
https://app.pluralsight.com/paths/skills/angular-js
https://app.pluralsight.com/library/courses/patterns-library/table-of-contents
https://angularjs.org/
https://laravel.com/docs/5.2/queries

segunda-feira, 4 de julho de 2016

Broadcast with pusher and Laravel

Imagine that you have a stocks web app and when some stock change or become something that you have to tell your clients, your app must send e-mail and push data to clients using your app. So, with Laravel and pusher.com, you can build this (broadcast this). First, we need to configure it all, so open your mail.php and configure to send email. Nothing special here, but pay attention in:
  'from' => ['address' => 'yourmail@mail.com', 'name' => 'Your awesome app'],  
Now we need to create an account in pusher.com and configure our app. After create pusher account, go to config/broadcasting.php and verify:
 'default' => env('BROADCAST_DRIVER', 'pusher'),  
 'pusher' => [  
       'driver' => 'pusher',  
       'key' => env('PUSHER_KEY'),  
       'secret' => env('PUSHER_SECRET'),  
       'app_id' => env('PUSHER_APP_ID'),  
       'options' => [  
         'cluster' => 'ap1',  
         'encrypted' => true  
       ],  
     ],  
Don’t forget the options, cluster. Get this on pusher.com dashboard. Now we need to set our .env with info provided by pusher.com
 PUSHER_KEY=25a75617457490364db66  
 PUSHER_SECRET=0eaab165d010e2626da4bb  
 PUSHER_APP_ID=222644517  
Now, use composer to get the libs:
 composer require pusher/pusher-php-server  
After all this, we have our app set to code the main hand, go and create the listener and the event. Open EventServiceProvider and put the list/event:
 protected $listen = [  
     'App\Events\SendEmailEvent' => [  
       'App\Listeners\SendEmailEventListener@sendEmail',  
     ],  
   ];  
With this, we can generate the list/event:
 php artisan event:generate  
So, when the SendEmailEvent is called, the SendEmailEventListener will execute sendEmail(). Go and code SendEmailEvent:
 <?php  
 namespace App\Events;  
 use App\Events\Event;  
 use Illuminate\Queue\SerializesModels;  
 use Illuminate\Contracts\Broadcasting\ShouldBroadcast;  
 class SendEmailEvent extends Event implements ShouldBroadcast  
 {  
   use SerializesModels;  
   public $richGuy;  
   /**  
    * Create a new event instance.  
    *  
    * @return void  
    */  
   public function __construct($richGuy)  
   {  
     $this->richGuy = $richGuy;  
   }  
   /**  
    * Get the channels the event should be broadcast on.  
    *  
    * @return array  
    */  
   public function broadcastOn()  
   {  
     return ['stock'];  
   }  
 }  
We need to implement ShouldBroadcast to tell pusher-php that we will broadcast. In broadcastOn(), we specify the name of the channel (stock). We need use the SerializesModels trait because we will send the $richGuy attribute. Now, let’s code SendEmailEventListener:
 <?php  
 namespace App\Listeners;  
 use App\Events\SendEmailEvent;  
 use Illuminate\Queue\InteractsWithQueue;  
 use Illuminate\Contracts\Queue\ShouldQueue;  
 use Illuminate\Support\Facades\Mail;  
 class SendEmailEventListener  
 {  
   /**  
    * Create the event listener.  
    *  
    * @return void  
    */  
   public function __construct()  
   {  
     //  
   }  
   /**  
    * Handle the event.  
    *  
    * @param SendEmailEvent $event  
    * @return void  
    */  
   public function sendEmail(SendEmailEvent $event)  
   {  
     $specialOffer = $event->richGuy;  
     Mail::send('emails.stock',  
           ['specialOffer' => $specialOffer],  
           function ($message) use ($specialOffer) {  
             //$message->from('optional@gmail.com', 'Super Stock');  
             $message->to($specialOffer['email'], $specialOffer['name'])->subject($specialOffer['subject']);  
           }  
     );  
     //return false will stop propagation  
   }  
 }  
In the sendEmail method, we put our logic to send email. We specify a view emails.stock with html for the email and an $specialOffer array that will be used in the stock email view. The $message->from() method is optional because we defined in config. The emails.stock view offer the stock for the client:
 <!DOCTYPE html>  
 <html lang="en-US">  
 <head>  
   <meta charset="utf-8">  
 </head>  
 <body>  
 <div>  
      <h1>Buy this stock now</h1>  
      <h2>Code: {{ $specialOffer['stock']->getCode() }}</h2>  
      <h2>Price: {{ $specialOffer['stock']->getPrice() }}</h2>  
   <h2>Buy and be a rich guy!</h2>  
 </div>  
 </body>  
 </html>  
Let’s define our routes.php:
 Route::get('/', 'PagesController@welcome');  
 Route::get('analyzeStock', 'PagesController@analyzeStock');  
Create the Stock class and in the PagesController code the analyzeStock method:
 use App\Events\SendEmailEvent;  
 class Stock{  
   protected $price;//why protected?  
   protected $code;  
   public function __construct($price, $code){  
     $this->price = $price;  
     $this->code = $code;  
   }  
   public function getPrice(){  
     return $this->price;  
   }  
   public function getCode(){  
     return $this->code;  
   }  
 }  
 public function analyzeStock(){  
     //... analyzing stock  
     $mySpecialStock = new Stock(250, '4a9k1qui');  
     event(new SendEmailEvent( ['stock' => $mySpecialStock, 'subject'=>'Buy this stock now!', 'email' => 'stock@myapp.com', 'name' => 'Rich Guy'] ) );  
     return view('stocks.stockConfirmationView');  
   }  
In the analyzeStock(), we call event(), passing the event and the constructor parameters. We protected $price and $code, later we’ll get back to this. We can show a confirmation building a simple view stocks.stockConfirmationView. Last, code the client page that will receive information:
 <script src="https://js.pusher.com/3.1/pusher.min.js"></script>  
   <script>  
     (function(){  
       var pusher = new Pusher('2575617457490364db66', {  
         cluster: 'ap1',  
         encrypted: true  
       });  
       var channel = pusher.subscribe('stock');  
       console.log('Binding...');  
       channel.bind('App\\Events\\SendEmailEvent', function(data) {  
         console.log(data);  
       });  
     })();  
   </script>  
We’ll load pusher.min.js and call a sia function to connect. Again, we need to put our key and cluster, all this available at pusher.com dashboard. Following, we’ll open our channel, stock, the same in the Event class and bind our event. Now we can open this page and see in the console the object sent. Every time, somebody hits /analyzeStock, an e-mail will be sent and the object will be sent to all pages with open channels, then you can use Knockout.js, jQuery and other cool things to show nice animations and updates to users. Now, think, why price and code in Stock are protected? What will happen if we change those for public?
TY, more info in:
https://pusher.com/
https://laravel.com/docs/5.2/mail
https://laravel.com/docs/5.2/events
https://laracasts.com/series/whats-new-in-laravel-5-1/episodes/12
http://knockoutjs.com/

sábado, 18 de junho de 2016

using System.Xml.Linq

So, for learning purpose, imagine that you need to generate something like this:
 <bills>  
 <bill>  
      <value>1270.45</value>  
      <date>  
           <day>21</day>  
           <month>12</month>  
           <year>2012</year>  
      </date>  
      <from> Space Shop </from>  
      <to> Bill Gates </to>  
      <status> Closed </status>  
 </bill>  
 <bill>  
      <value>1245.55</value>  
      <date>  
           <day>25</day>  
           <month>11</month>  
           <year>2011</year>  
      </date>  
      <from> Business Center </from>  
      <to> Steve Jobs </to>  
      <status> Closed </status>  
 </bill>  
 </bills>  
It's not my favorite type to write xml(when i can choose), it shows verbosity and blah.... and once you have it, now you need to show this for people: Bill: From: ................. To: .............. (...) It can be boring depending on how you do it. Xml.Linq can do this with elegance, let's see: 1) Creating Bill class
 public enum StatusEnum { Closed, Open, Removed };  
   class Bill  
   {  
     public decimal Value { get; set; }  
     public DateTime Date { get; set; }  
     public string From { get; set; }  
     public string To { get; set; }  
     public StatusEnum Status { get; set; }  
     public Bill(decimal Value, DateTime Date, string From, string To, StatusEnum Status)  
     {  
       this.Value = Value;  
       this.Date = Date;  
       this.From = From;  
       this.To = To;  
       this.Status = Status;  
     }  
   }  
2) Creating objects:
 private static List<Bill> Bills = new List<Bill>()  
     {  
       new Bill (1250.75m, new DateTime(2012, 12, 21), "Space Shop", "Bill Gates", StatusEnum.Closed),  
       new Bill (1785.55m, new DateTime(2007, 10, 15), "Business Center", "Steve Jobs", StatusEnum.Closed),  
       new Bill (193.75m, new DateTime(2012, 12, 21), "Gym", "Arnold", StatusEnum.Removed),  
       new Bill (5845.70m, new DateTime(2012, 12, 21), "Chanel", "Gisele", StatusEnum.Open)  
     };  
3) Generating Xml:
 XDocument docBillsXml =  
         new XDocument(new XElement("bills",  
                 (from bill in Bills  
                 orderby bill.Value descending,  
                     bill.Date descending  
                 select new XElement("bill",  
                   new XElement("value", bill.Value),  
                   new XElement("date", new XElement("day", bill.Date.Day),  
                              new XElement("month", bill.Date.Month),  
                              new XElement("year", bill.Date.Year)),  
                   new XElement("from", bill.From),  
                   new XElement("to", bill.To),  
                   new XElement("status", bill.Status.ToString())  
                 )  
               )  
         ));  
So, here we create a Document(bills) and for each object we generate an element(bill). Ordering by the value of the bill and the date, both descending (ascending is default). So the bills with highest values comes first and inside of that order the newest bills comes first. Now we have docBillsXml and we need show this to people. The first way is using a simple foreach:
 var bills = docBillsXml.Element("bills").Elements("bill");  
       foreach(var bill in bills)  
       {  
         Console.WriteLine("Bill:");  
         Console.WriteLine("\tFrom: {0}", bill.Element("from").Value);  
         Console.WriteLine("\tTo: {0}", bill.Element("to").Value);  
         var date = bill.Element("date");  
         Console.WriteLine("\tDate: {0}\\{1}\\{2}", date.Element("day").Value,  
                              date.Element("month").Value,  
                              date.Element("year").Value);  
         Console.WriteLine("\tValue: {0}", bill.Element("value").Value);  
         Console.WriteLine("\tStatus: {0}", bill.Element("status").Value.ToString());  
         Console.Write("\n");  
       }  
using .Element("bills") we get the root element and with Elements("bill") we get all the bills. The second way to show this to people is using projection:
 var billsWithLinq = from bill in docBillsXml.Descendants("bill")  
                 where (bill.Element("status").Value.ToString().StartsWith("Cl"))  
                 select new  
                 {  
                   Company = bill.Element("from").Value,  
                   Client = bill.Element("to").Value  
                 };  
       foreach(var bill in billsWithLinq)  
       {  
         Console.WriteLine("Bill:");  
         Console.WriteLine("\tClient: {0}", bill.Client);  
         Console.WriteLine("\tCompany: {0}", bill.Company);  
         Console.Write("\n");  
       }  
with . Descendants("bill") we get all the bill elements. Using Where to filter and get the closed bills. To Think: if we insert the following line of code between the creation of docBillsXml and the exhibition, New Client will be in the exhibition?
 Bills.Add(new Bill(200.75m, new DateTime(2016, 01, 21), "New", "New Client", StatusEnum.Removed));  
suggestions-> leave comments. TY. More on:
https://msdn.microsoft.com/pt-br/library/system.xml.linq(v=vs.110).aspx
https://app.pluralsight.com/library/courses/linq-fundamentals/table-of-contents