Search This Blog

2015-10-16

NODE JS and MEAN Stack

What is Mean :
MEAN is an opinionated fullstack javascript framework - which simplifies and accelerates web application development.Mean Stands for MongoDB,Express,NojeJS and AngularJS.

What is MongoDB :
MongoDB is the leading NoSQL database, empowering businesses to be more agile and scalable.

What is Express :
Express is a minimal and flexible node.js web application framework, providing a robust set of features for building single and multi-page, and hybrid web applications.

What is Node JS :
Node.js is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications.It is an application development platform that allows us to create standalone applications developed using JavaScript.

What is AngularJS :
AngularJS lets you extend HTML vocabulary for your application. The resulting environment is extraordinarily expressive, readable, and quick to develop.

Install NodeJS in windows:
Go to the https://nodejs.org/en/ and Click 'Download for Windows'. Once download completed, install it.

In odder to check the installation, Open the command prompt and type node -v , it will show you the current version of node js installed at your PC.

C:\>node -v

REPL :
In order to start the Read-Eval-Print-Loop or REPL for short, I am going to just type the node command and I'm not going to use any of the flags. And you can see now my cursor has changed here to the > sign, and now I am actually in the REPL. And at this point, I'm just basically free to start entering lines of JavaScript that are going to be evaluated right away.

I can say something like console.log("Hello World") and press Enter.

Also , the multiline REPL command executed be as below in while loop

When you have done, press Ctrl+c twice or type process.exit(1) , in oder to exit the REPL.


  • Read - Reads user's input, parse the input into JavaScript data-structure and stores in memory.
  • Eval - Takes and evaluates the data structure
  • Print - Prints the result
  • Loop - Loops the above command until user press ctrl-c twice

  • 2014-01-06

    MVC-Basic to Advanced:Part 1-Create a New Project in MVC & Introduction to HTML Helper

    Hello Guys, Its a long time I was not in touch with my blog due to some personal constraint.Lets start it once again.... In this MVC series, I have a plan to contribute from a basic to advanced modules on MVC. Lets start with a simple MVC solution..... Step 1: Open the VS2012, Create a New Project 'MyMvcApplication' as below

    Step 2:Select 'InternetApplication' From the template and 'Razor' as a view engine.Click OK.

    Step 3.Modify the Index.cshtml as below so that it looks like simple and run it.

    Step 4. Once Run, It should looks like below...


    HTML Helper : HTML helpers are an easy way to render the appropriate HTML markup in a view and returns an HTML-encoded string of the type MvcHtmlString(i.e already HTML-encoded) and and therefore should not be encoded again. Example : In the Index.cshtml, you can add HTML Helpers @Html.TextBox and @Html.CheckBox like below .
    @{
    ViewBag.Title = "Home Page";
    }
    @section featured {
    <section class="featured">
    <div class="content-wrapper">
    <hgroup class="title">
    <h1>@ViewBag.Title.</h1>
    <h2>@ViewBag.Message</h2>
    @Html.TextBox("myTextbox")
    @Html.CheckBox("myCheckbox")
    </hgroup>
    </div>
    </section>
    }

    Standard HTML Helpers :

    Form Extensions —
    • Html.BeginForm()
    • Html.BeginRouteForm()
    • Html.EndForm()

    Input Extensions —
    • Html.CheckBox()
    • Html.Hidden()
    • Html.Password()
    • Html.RadioButton()
    • Html.TextBox()
    TextArea Extensions —
    • Html.TextArea()
    Label Extensions —
    • Html.Label()
    Link Extensions —
    • Html.ActionLink()
    • Html.RouteLink()
    Select Extensions —
    • Html.DropDownList()
    • Html.ListBox() 
    Validation Extensions —
    • Html.Validate()
    • Html.ValidationMessage()
    • Html.ValidationSummary()
    The above HTML Helper can be made as a strongly typed(except the Form Extension) by addling a 'for' as a suffix(like Html.TextBoxFor(model => model.FirstName)) and use use lambda expressions when referring to the model that has been passed to the view.

    2014-01-05

    Introduction to Entity Framework-Part I

    LINQ to Entities is considered to be one of Microsoft's new ORM products.ORM stands for Object-Relational Mapping.It is a programming technique that contains a set of classes that map relational database entities to objects in a specific programming language.Entity Framework (EF)enables developers to create data access applications by programming against a conceptual application model instead of programming directly against a relational storage schema.With Entity Framework, developers work with a conceptual data model, an Entity Data Model, or EDM, instead of the underlying databases.
    The conceptual data model schema is expressed in the Conceptual Schema Definition Language (CSDL) ,the actual storage model is expressed in the Storage Schema Definition Language (SSDL), and the mapping in between is expressed in the Mapping Schema Language (MSL).

    Lets see how to create a simple LINQ to entity application.

    Step 1:Create a console application as follows-


    Step 2:Add a new Item "ADO.NET entity data model"


    Step 3:Click Next and choose "Generate from database"


    Step 4:Choose a existing connection or click new connection-


    Step 5:Choose the dabase object as follows-




    Step 6:After you click on the Finish button the following two files will be added to the project: Northwind.edmx and Northwind.designer.cs. The first file holds the model of the entities including the entity sets, entity types, conceptual models, and the mappings. The second one is the code for the model which defines the ObjectContext of the model.



    Step 7:If you open the file, Northwind.Designer.cs (you need to switch from the Model Browser to Solution Explorer to open this file), you will find that the
    following classes have been generated for the project:
    public partial class NorthwindEntities : ObjectContext
    public partial class Product : EntityObject
    public partial class Category : EntityObject
    public partial class Current_Product_List : EntityObject

    In the above four classes, the NorthwindEntities class is the main conduit through which we'll query entities from the database as well as apply changes back to it. It contains various flavors of types and constructors, partial validation methods, and property members for all of the included tables. It inherits from the ObjectContext class which represents the main entry point for the LINQ to Entities framework.

    The next two classes are for the two tables that we are interested in. They implement the EntityObject interface. This interface defines all of the related property changing and property changed event methods which we can extend to validate properties before and after the change.

    The last class is for the view. This is a simple class with only two property members. Because we are not going to update the database through this view it doesn't define any property change or changed event method.

    Querying records:

    To query your records you can do any one of three(Lambda Expression,Query expression with var keyword,query expression with proper datatype) in following approach.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace LINQConsoleApp
    {
    class Program
    {
    static void Main(string[] args)
    {
    NORTHWINDEntities objNORTHWINDEntities = new NORTHWINDEntities();


    var LambdaExpOutput = objNORTHWINDEntities.Products.Where(p => p.Category.CategoryName.Equals("Beverages")
    p.Category.CategoryName.Equals("Condiments"))
    .OrderByDescending(p => p.ProductName).ThenBy(p=>p.QuantityPerUnit)
    .Select(p=> new {p.ProductName,p.QuantityPerUnit,p.Category.CategoryName});

    var LinqVarOutput = from p in objNORTHWINDEntities.Products
    where p.Category.CategoryName == "Beverages"
    p.Category.CategoryName == "Condiments"
    orderby p.ProductName, p.QuantityPerUnit descending
    select new { p.ProductName, p.QuantityPerUnit, p.Category.CategoryName };

    IEnumerable<Product> LinqOutput = from p in objNORTHWINDEntities.Products
    where p.Category.CategoryName == "Beverages"
    p.Category.CategoryName == "Condiments"
    orderby p.ProductName descending, p.QuantityPerUnit
    select p;

    Console.WriteLine("There are {0} LambdaExpOutput Items", LambdaExpOutput.Count());
    Console.WriteLine("There are {0} LinqVarOutput Items", LinqVarOutput.Count());
    Console.WriteLine("There are {0} LinqOutput Items", LinqOutput.Count());
    Console.WriteLine("--------------------------------------------------------------------------");
    int maxLimit = 0;
    foreach (var p in LambdaExpOutput)
    {
    if (maxLimit == 3)
    {
    break;
    }
    Console.WriteLine("Product Name :{0} QuantityPerUnit:{1} CategoryName:{2}", p.ProductName, p.QuantityPerUnit, p.CategoryName);
    maxLimit++;
    }
    Console.WriteLine("--------------------------------------------------------------------------");
    maxLimit = 0;
    foreach (Product p in LinqOutput)
    {
    if (maxLimit == 3)
    {
    break;
    }
    Console.WriteLine("Product Name :{0} QuantityPerUnit:{1} CategoryName:{2}", p.ProductName, p.QuantityPerUnit, p.Category.CategoryName);
    maxLimit++;
    }

    Console.ReadLine();

    }
    }
    }


    The output will be as follows-




    Updating records

    To change the product name of 3rd element you can do as follows-

    NORTHWINDEntities objNORTHWINDEntities = new NORTHWINDEntities();
    Product objProduct = LinqOutput.ElementAtOrDefault(2);
    if (objProduct != null)
    {

    objProduct.ProductName = objProduct.ProductName + "_A";
    objNORTHWINDEntities.SaveChanges();
    }


    Inserting records
    To add a new record you can do as follows-
    NORTHWINDEntities objNORTHWINDEntities = new NORTHWINDEntities();
    Product objNewProduct = new Product { ProductName = "My Product" };
    objNORTHWINDEntities.Products.AddObject(objNewProduct);
    objNORTHWINDEntities.SaveChanges();

    Deleting records
    To delete the record you can do as follows-

    NORTHWINDEntities objNORTHWINDEntities = new NORTHWINDEntities();
    IQueryable<Product> productsToDelete =from p in objNORTHWINDEntities.Products
    where p.ProductName == "My Product"
    select p;

    if (productsToDelete.Count() > 0)
    {
    foreach (var p in productsToDelete)
    {
    objNORTHWINDEntities.DeleteObject(p);
    Console.WriteLine("Deleted product {0}", p.ProductID);
    }
    objNORTHWINDEntities.SaveChanges();
    }

    View SQL statements
    To view the generated SQL statements used by LINQ to Entities queries.
    NORTHWINDEntities objNORTHWINDEntities = new NORTHWINDEntities();
    IQueryable<product> productsToDelete = from p in objNORTHWINDEntities.Products
    where p.ProductName == "My Product"
    select p;

    Console.WriteLine(productsToDelete.ToTraceString());
    Console.ReadLine();



    Join n Query
    When you don't have any foreign key relationship between tables it is very useful to use join query as follows
    var categoryProducts = from c in objNORTHWINDEntities.Categories
    join p in objNORTHWINDEntities.Products
    on c.CategoryID equals p.CategoryID
    into productsByCategory
    select new
    {
    c.CategoryName,
    productCount = productsByCategory.Count()
    };
    foreach (var cp in categoryProducts)
    {
    Console.WriteLine("There are {0} products in category {1}",
    cp.productCount, cp.CategoryName);
    }
    Console.ReadLine();




    Querying a view is the same as querying a table.

    2011-09-03

    Introduction to Entity Framework-Part II





    Add a Stored Procedure

    Open the Northwind.edmx designer.Right-click on an empty space of the designer surface and select Update Model from Database.expand the Stored Procedures node, check Ten Most Expensive Products (dbo), and then click on the Finish button.

    On the designer surface, right-click on an empty space, and select Add from the context menu, then select Function Import.On the Add Function Import window, select Ten_Most_Expensive_Products as the stored procedure name them retype this name as the Function Import Name.Click on the Create New Complex Type button to create a new entity type.Type the function import name as "Ten_Most_Expensive_Products_Function".

    Click OK.







    we can call this stored procedure as follows



    var myProduct = from p in objNORTHWINDEntities.Ten_Most_Expensive_Products_Function()

    select p;

    foreach (var p in myProduct)

    {

    Console.WriteLine("Product Name: {0}, Price: {1}",

    p.TenMostExpensiveProducts, p.UnitPrice);

    }

    Console.ReadLine();





    Similarly you can call create a stored proc with param and call from your application-

    Create PROCEDURE [dbo].[GetProductFrmProductID]

    (

    @ProductID int

    )

    AS

    SET NOCOUNT ON

    Select * from Products where ProductID = @ProductID



    Add a stored proc as the same way ,choose Entities instead of complex type as the stored proc returns the data as product entity type-







    use the LINQ as follows-

    NORTHWINDEntities objNORTHWINDEntities = new NORTHWINDEntities();



    var myProductFromSP = from p in objNORTHWINDEntities.Product_Function(2)

    select p;

    foreach (var p in myProductFromSP)

    {

    Console.WriteLine("Product ID: {0}, Name: {1}",

    p.ProductID, p.ProductName);

    }

    Console.ReadLine();



    when you run it,the output will be as follows-





    Entity Framework version 1.0 only has limited support for stored procedures.It can't handle multiple result sets from the same stored procedure, not to mention dynamic result sets (the stored procedure returns different result sets according to different input parameters).



    Compiled Query

    A compiled query is actually a function. The function contains a compiled LINQ query expression and can be called just like a regular function.It increase performance by compiling the query once and executing it several times in the application with different parameters.



    The following code shows how to define a compiled query:



    NORTHWINDEntities objNORTHWINDEntities = new NORTHWINDEntities();

    Func<NORTHWINDEntities, strin>, IQueryable<Product>> fn

    = CompiledQuery.Compile((NORTHWINDEntities NW, strin> cate>ory) =>

    from p in NW.Products

    where p.Cate>ory.Cate>oryName == cate>ory

    select p);

    var objCompiledQueryOutput = fn(objNORTHWINDEntities, "Bevera>es");

    Console.WriteLine("Total products in Bevera>es cate>ory : {0}",

    objCompiledQueryOutput.Count());

    Console.ReadLine();





    Direct SQL

    LINQ to entity supports direct SQL with the following methods-

    The ExecuteStoreQuery() method lets you execute a raw SQL query and converts the result of your query directly into objects.

    The ExecuteStoreCommand() method lets you directly execute SQL commands against the database.



    Example-



    NORTHWINDEntities objNORTHWINDEntities = new NORTHWINDEntities();

    var directSQL = objNORTHWINDEntities.ExecuteStoreQuery<Product>(

    "SELECT * " +

    "FROM Products " +

    "WHERE UnitPrice >28" +

    "ORDER BY ProductName;"

    );



    Console.WriteLine("Total products :{0}",

    directSQL.Count());



    int rowCount = objNORTHWINDEntities.ExecuteStoreCommand(

    " update products "

    + "set UnitPrice=UnitPrice+1 "

    + "where productID=35");



    if (rowCount < 1)

    Console.WriteLine("No product is updated");

    else

    Console.WriteLine("Product price is updated");





    Dynamic query with parameters

    We can also build a dynamic query string with parameters and then pass different parameters to query the database at runtime.



    string queryString =

    @"SELECT VALUE Product

    FROM NorthwindEntities.Products

    AS Product

    WHERE Product.ProductID = @id";



    ObjectQuery<product> productQuery =

    new ObjectQuery<Product>(queryString, objNORTHWINDEntities);

    productQuery.Parameters.Add(new ObjectParameter("id", 1));

    foreach (var p in productQuery)

    {

    Console.WriteLine("Product name: {0}", p.ProductName);

    }



    Console.ReadLine();





    Inheritance

    LINQ to Entities supports three types of inheritance: Table Per Hierarchy (TPH) inheritance, Table Per Type (TPT) inheritance, and Table Per Concrete (TPC) inheritance.

    In Table per Hierarchy inheritance there is a single database table that contains fields for both parent information and child information. With relational data a discriminator column contains the value that determines which class any given record belongs to.

    Suppose we have a person table as follows



    CREATE TABLE [dbo].[person](

    [PersonID] [int] IDENTITY(1,1) NOT NULL,

    [LastName] [nvarchar](20) NOT NULL,

    [FirstName] [nvarchar](10) NOT NULL,

    [EnrollmentDate] [datetime] NULL,

    [HireDate] [datetime] NULL,

    [PersonType] [varchar](1) NULL,

    CONSTRAINT [PK_person] PRIMARY KEY CLUSTERED

    (

    [PersonID] ASC

    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

    ) ON [PRIMARY]







    As you can see, the table holds two different fields from two different types: HireDate (which belong to a professor type) and EnrollmentDate (which belongs to student type). The table also includes an Text discriminator field which is called PersonType. When PersonType equals P, the person type is a professor and when it is S, the type is student.



    The following steps will help you to understand how you can create a TPH inheritance mapping.



    Update your model from database so that you can add the new entity person





    Change the entity class name from person to BasePerson.

    Right-click on an empty space on the designer surface, then choose

    Add | Entity… from the context menu.





    Create two Entity "Professor" and "Student" and make "BasePerson" as their base type.



    Cut HireDate from BasePerson and paste it to Professor class and Cut Enrollment date from BasePerson to Student Class.

    Right-click on the PersonType property of the BaseCustomer entity, and select Delete from the context menu. We need to delete this property because we will use this property as our discriminator.







    Now select the Professor entity on the model designer, and go to the Mapping Details window (it should be next to your Output window or you can open it from menu View | Other Windows | Entity Data Model Mapping Details).

    On the Mapping Details window, click on , and select Person from the drop-down list. Make sure HireDate is mapped to HireDate and Enrollment and PersonType is not mapped.

    Again on the Mapping Details window, click on , and select Person from the drop-down list. Select = as the operator, and enter P as the Value / Property.



    Repeat the above process for Student type so that it looks as follows-