WHAT'S NEW?
Loading...

Your first MEAN.JS site running on the cloud

Index


  • Intro
  • Ingredients
  • Receipt
  • Mongo
  • Heroku
  • Extra
  • References

Intro


In this tutorial I want to change a little bit the subject we've been following during these last months. Today, you will discover how easy can be build an entire site, frontend, backend and finally publish everything on the cloud for FREE and only in a few hours.

By using the MEAN stack and Yeoman we can achieve that in a relatively easy way and once our machine is completely setup repeat this process every time we want. See here below how the full environment looks:


Ingredients

Please, serve yourself with these awesome ingredients so you can cook a very special receipt and impress all your guests:

  • https://toolbelt.heroku.com/: register in the Heroku site, as this will be our hosting service provider and install its toolbelt application.
  • https://nodejs.org/en/: download and install last version.
  • https://www.python.org/download/releases/2.7.3/#download: install python v2.7.3 as it's needed to compile native NodeJs addons and it's the current supported version. Make sure that you have a PYTHON environment variable, and it is set to drive:\path\to\python.exe not to a folder.
  • https://www.mongodb.org/downloads: this will be our NoSQL database provider. Install it and run the Mongo daemon: mongod.exe, within a console (remember to create c:\data\db folder structure using the default mongo settings).
  • Microsoft Build Tools 2013 / 2015
  • Finally, within the "Extra" section at the bottom of this post, a stunning windows console called cmder running on your machine. Completely recommended console with some steroids.

Receipt

Once all the ingredients are installed on your computer, now is the time to start cooking our new application.

First of all we need to install globally a few packages in our NodeJS instance by running the following command:




  • Yo: Yeoman helps you to kickstart new projects, prescribing best practices and tools to help you stay productive. To do so, they provide a generator ecosystem. A generator is basically a plugin that can be run with the `yo` command to scaffold complete projects or useful parts.
  • grunt-cli: this is the build system helping you out to build, preview and test your applications. Gulp is also another popular option for building project.
  • bower: this is a package manager used to solve project dependencies. Npm is a common alternative used in the previous command.
  • generator-angular-fullstack: this is the template for our angular site we'll use with Yo. This particular package comes with Heroku compatibility which will be helpful during the deployment process, you can find more info in its site here.


Finally, everything is ready and we can start cooking by running the following commands:




Replace my-new-project with the name of the folder you want, [app-name] with the name of the application you want and have MongoDB running on background. With these three simple commands you end up with a new folder called "my-new-project" and within that folder a complete website created with just one command. Finally compile and run the project locally:




Mongo


For the database hosting I chose mongolab as my provider because is free until 500Mb and really easy to setup. Take a look at their web site and after creating a new account you just need to generate a new Mongo database and copy the URL connection string into your project replacing your localhost Mongo database. Once this is done the last step will be deploy our site on Heroku so it will be open to everybody.

Heroku


For the deployment to Heroku we just need to write some commands within our console and the deployment will be done:




Extra


There is a big component of console commands on this tutorial. For this reason I've tried cmder console for Windows and I think you should also give it a go. It's a really powerful console app which a lot of functionality from Linux systems, besides, it is highly customizable. Follow this tutorial from Andrew Moore to set it up.

References


https://nodejs.org/en
https://toolbelt.heroku.com
http://meanjs.org/generator.html
http://www.awmoore.com/2015/01/14/coding-in-windows-part-1/
https://github.com/yeoman/yeoman

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)