Pages

Saturday, May 17, 2014

Native JavaScript + JQuery vs AngularJS


Both JavaScript and JQuery have been around and are performing better.

Except JQuery, I haven’t accepted any other third party JavaScript frameworks or libraries. However recently, I have been drilling into AngularJS. I’m questioning, is Angular worth adding to projects?

After reading, AngularJS recursive templates, post, it appears Angular is bloated and expensive compared to native JavaScript.

I rewrote the post’s conclusion in Native JavaScript + JQuery. What I wrote isn’t the best and can be improved on, however I believe it to be sleeker and trimmer.

Conclusion, presently I wouldn’t include any Angular into projects. I would continue learning JavaScript and apply all the great JavaScript patterns.

Please compare what I offered and mention why Angular? Please I know about reinventing the wheel, but I’m not convinced.

View what they offered JSFiddle.


Below is what I thought would accomplish similar results.

DOM

<div id="ahhBetter">&nbsp;</div>

JavaScript + JQuery

function doAgain(arry) {
    var s = "<ul>";

    for (var i = 0; i < arry.length; i++) {
        s += "<li>" + arry[i].title + "</li>";
        if (arry[i].categories) {
            s += doAgain(arry[i].categories);
        }
    }
    s += "</ul>"

    return s;
}

$("#ahhBetter").append(doAgain(items));

Data

var items = [{
    title: 'Computers',
    categories: [{
        title: 'Laptops',
        categories: [{
            title: 'Ultrabooks'
        }, {
            title: 'Macbooks'
        }]
    },

      {
          title: 'Desktops'
      },

      {
          title: 'Tablets',
          categories: [{
              title: 'Apple'
          }, {
              title: 'Android'
          }]
      }
    ]
},

    {
        title: 'Printers'
    }

];


This post is for the purpose of my notes only and sometimes a rant.
“I invented nothing new. I simply assembled the discoveries of other men behind whom were centuries of work. Had I worked fifty or ten or even five years before, I would have failed. So it is with every new thing. Progress happens when all the factors that make for it are ready and then it is inevitable. To teach that a comparatively few men are responsible for the greatest forward steps of mankind is the worst sort of nonsense.” 
Henry Ford

Friday, May 9, 2014

Azure: Transferring Local SQL Database to Azure SQL Database

 

Setup a SQL Server at Azure.

image

Click Create A SQL Database Server, and fill in server settings:

image

Clicking on the check mark, SQL server is created and display. The server name is 123456785.


Locally, I have SQL Server 2012, which has two databases. I will be transferring these databases to Azure.

  • FileUploadSQLDB
  • GoonSeedsSQL

image

Right click on database >Tasks > Deploy Database to SQL Azure

image

Click next >

image

Click Connect >

image

Enter the Server name (123456785), Login and Password (Should receive an error):

image

Should receive an error, this occurs because Azure’s firewall. Correct the problem, go back to Azure.

image

 

Click on Manage:

image

Will receive two messages, Clicking yes will include the Server address to the firewall rules:

image

When click yes, will be prompted with another message, and click yes. This should correct the local database error.

image

Return to SQL Server Management Studio. Click Connect >

image

Click Next >

image

The Summary page is displayed. Click Finish >

The progress page will begin importing the database, and on completion Close.

The database will now display within Azure.

 

image

Moving the second database, follow similar steps. The second database can be added to the same server. For one Server, I am allowed to add up to 150 databases.

The error can be handled another way:

The following code creates a server-level firewall setting called Allow Azure that enables access from Azure.

sp_set_firewall_rule (Azure SQL Database)

-- Enable Azure connections.
exec sp_set_firewall_rule N'Allow Azure','0.0.0.0','0.0.0.0'





This post is for the purpose of my notes only.
“I invented nothing new. I simply assembled the discoveries of other men behind whom were centuries of work. Had I worked fifty or ten or even five years before, I would have failed. So it is with every new thing. Progress happens when all the factors that make for it are ready and then it is inevitable. To teach that a comparatively few men are responsible for the greatest forward steps of mankind is the worst sort of nonsense.”



Henry Ford

MVC 4.5 Adding Bundling to Empty Project

Steps needed to add bundling to a new MVC 4.51 empty project.
Add reference: Microsoft.AspNet.Web.Optimization
from the Package Manager Console enter:
  • PM> Install-Package Microsoft.AspNet.Web.Optimization
image
Adding Microsoft.AspNet.Web.Optimization, added a reference to the System.Web.Optimization namespace.
System.Web.Optimization exposes:
  • BundleCollection: Contains and manages the set of registered Bundle objects in an ASP.NET application.
  • ScriptBundle: Represents a bundle object that does Js Minification.
  • StyleBundle: Represents a bundle object that does CSS minification.
  • BundleTable: Static holder class for the default bundle collection.
Additional : MSDN

Within Views folder , add reference to web.config. Adding reference to web.config will support bundling Razor Html helpers: @Scripts on pages.
<system.web.webPages.razor>
  <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
  <pages pageBaseType="System.Web.Mvc.WebViewPage">
    <namespaces>
      <add namespace="System.Web.Mvc" />
      <add namespace="System.Web.Mvc.Ajax" />
      <add namespace="System.Web.Mvc.Html" />
      <add namespace="System.Web.Routing" />
      <add namespace="FileUpload_MVC" />
      <add namespace="System.Web.Optimization" />
    </namespaces>
  </pages>
</system.web.webPages.razor>

 

Within Views folder, add reference to web.config file. This will support bundling Razor Html helpers @Styles on pages.

 

<system.web>
   <pages>
     <namespaces>
       <add namespace="System.Web.Optimization" />
     </namespaces>
   </pages>
    
   '''

 </system.web>






Within App_Start folder, create a class named whatever you prefer; I will keep to convention and create a class called: BundlesConfig, which it’s signature expects a Bundlecollection.

I could call the class MyBundlesConfig, which it’s signature expects a Bundlecollection.

imageimage











Bundling JavaScript and CSS files.

Add a static method to BundlesConfig which its signature accepts a BundleCollection type.

Create respective bundle objects, expecting a string argument. String argument represents a virtual path where bundling files are located.

Fictitious application relative URLs (“~/url”) are allowed as parameters. Could be thought as a namespace, so (~/MyFictitiousUrl) could be used, and doesn’t necessarily exist as a path within the file structure.

var scriptBundle = new ScriptBundle(“~/bundles/Scripts”);;
var styleBundle = new StyleBundel(“~/bundles/Styles”);


Possible taking advantage of CDN by passing the path of a Content Delivery Network as the second parameter:

var scriptBundle = new ScriptBundle(“~/bundles/Scripts”,”http://MyCDN”);





Include a set of files to be included in the bundle object.

var scriptFiles = new string[]  { “~/Scripts/*.js” };
var styleFiles = new string[] { “~/Content/*.css” };
scriptBundle.Include(scriptFiles );
styleBundle .Include(styleFiles );

Possible passing only a string argument:

scriptBundle.Include(“~/Scripts/*.js”);
styleBundle .Include(“~/Content/*.css”);


Above, the scriptBundle object will collect all JavaScript files located within the Scripts folder. styleBundle object will collect all CSS files located within the Content folder.

Add bundle objects to BundleCollection.

bundles.Add(scriptBundle);
bundles.Add(styleBundle);




BundleConfig.cs


namespace FileUpload_MVC.App_Start
{
    public class BundlesConfig
    {
        public static void RegisterBundles(BundleCollection bundles)
        {
            var scriptBundle = new ScriptBundle("~/bundles/Scripts");

            var scriptFiles = new string[] { "~/Scripts/*.js" };

            scriptBundle.Include(scriptFiles);

            var styleBundle = new StyleBundle("~/bundles/Styles");
            styleBundle.Include("~/Content/*.css");

            bundles.Add(scriptBundle);
            bundles.Add(styleBundle);
        }
    }
}

Or… Using IncludeDirectory()

namespace FileUpload_MVC.App_Start
{
    public class BundlesConfig
    {
        public static void RegisterBundles(BundleCollection bundles)
        {
            var scriptBundle = new ScriptBundle("~/bundles/Scripts");

            scriptBundle.IncludeDirectory("~/Scripts", "*.js", true);

            var styleBundle = new StyleBundle("~/bundles/Styles");
            styleBundle.IncludeDirectory("~/Content", "*.css", true);

            bundles.Add(scriptBundle);
            bundles.Add(styleBundle);
        }
    }
}






With help of Razor Html Bundling helpers, add Bundling to Razor View:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>deDogs - File Upload Appication</title>

    @Styles.Render("~/bundles/Styles")

    <script src="~/Scripts/modernizr-2.6.2.js"></script>
</head>
<body>

    <div>
        @RenderBody()
        <hr />
        <footer></footer>
    </div>

    @Scripts.Render("~/bundles/Scripts")
</body>
</html>






Within the Global.asax.cs file, register calling RegisterBundles(BundleCollection bundles).

 

Reference System.Web.Optimization and passing a Bundles collection. BundleTable is a static holder class for the default bundle collection.

 

namespace FileUpload_MVC
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundlesConfig.RegisterBundles(BundleTable.Bundles);

        }
    }
}


Possible to set BundleTable.EnableOptimizations: return true if bundling and minification of bundle references is enabled; otherwise, false.


Bundling and Minification


This post is for the purpose of my notes only.
“I invented nothing new. I simply assembled the discoveries of other men behind whom were centuries of work. Had I worked fifty or ten or even five years before, I would have failed. So it is with every new thing. Progress happens when all the factors that make for it are ready and then it is inevitable. To teach that a comparatively few men are responsible for the greatest forward steps of mankind is the worst sort of nonsense.”


Henry Ford

Tuesday, May 6, 2014

Migration: Helpful When Seeding Database and Error is Thrown

Using Entity Framework Migration, I was seeding a database.

From the Package Manager Console window and after entering Update-Database, an error was displayed.

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

This was the only information about error, and the error message didn’t indicate any good advise what caused the error.

Shown below is a work-around found at StackOverflow, which helped pin point the error.

Stackoverflow Overridding SaveChanges

public partial class Database : DbContext
{
public override int SaveChanges()
{
try
{
return base.SaveChanges();
}
catch (DbEntityValidationException ex)
{
var sb = new StringBuilder();

foreach (var failure in ex.EntityValidationErrors)
{
sb.AppendFormat("{0} failed validation\n", failure.Entry.Entity.GetType());
foreach (var error in failure.ValidationErrors)
{
sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage);
sb.AppendLine();
}
}

throw new DbEntityValidationException(
"Entity Validation Failed - errors follow:\n" +
sb.ToString(), ex
); // Add the original exception as the innerException
}
}
}



This post is for the purpose of my notes only.
“I invented nothing new. I simply assembled the discoveries of other men behind whom were centuries of work. Had I worked fifty or ten or even five years before, I would have failed. So it is with every new thing. Progress happens when all the factors that make for it are ready and then it is inevitable. To teach that a comparatively few men are responsible for the greatest forward steps of mankind is the worst sort of nonsense.”



Henry Ford

Sunday, May 4, 2014

Entity First - Code First - Migrations Setup

1. Created two window class project:
  • exposing the domain classes:
  • exposing the DB context classes
2. Created a MVC  4.5.1 project

1. Created two window class projects:
Domain Classes
using System;

namespace FileUpload.DomainClasses
{
    public class Media
    {
        public int Id { get; set; }
        public int MediaTypeId { get; set; }
        public string Name { get; set; }
        public string Title { get; set; }
        public string Caption { get; set; }
        public string Description { get; set; }
        public string Path { get; set; }
        public int Width { get; set; }
        public int Height { get; set; }
        public DateTime IDate { get; set; }
        public DateTime UDate { get; set; }

        public virtual MediaType MediaType { get; set; }

    }
}


namespace FileUpload.DomainClasses
{
    public class MediaType
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Extension { get; set; }
    }
}


DB Context Class

Reaching the domain class add reference to FileUpload.DominClasses.

Within the constructor, explicitly set connection string name, which will be found within web.config.

using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;

namespace FileUpload.DataLayer
{
    public class FileUploadContext : DbContext
    {
        public FileUploadContext()
            : base("name=FileUploadContextDB")
        {

        }
        public DbSet<Media> Medias { get; set; }
        public DbSet<MediaType> MediaTypes { get; set; }
    }
}


Connection String

Within web.config, added two connection strings.


  • FileUploadContext
  • FileUploadContextDB

FileUploadContext is name of the DB context class. If a connection string wasn’t explicitly set within the DB context class constructor, then a connection string with the context class name will be used.

However, the context class above has explicitly set the connection string within the constructor, so the  FileUploadContextDB connection string  is used.

web.config connectionStrings

<?xml version="1.0"?>
<configuration>
  <connectionStrings>
    <add name="FileUploadContext" connectionString="Data Source=(localdb)\Projects;Initial Catalog=FileUploadContextDB;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False" providerName="System.Data.SqlClient" />
    <add name="FileUploadContextDB" connectionString="Data Source=DEDOGS-PC\DEDOGSSQL;Initial Catalog=FileUploadContextDB;Integrated Security=False;User ID=sa;Password=moclay9330;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False" providerName="System.Data.SqlClient" />
  </connectionStrings>
    <system.web>
      <compilation debug="true" targetFramework="4.5.1" />
      <httpRuntime targetFramework="4.5.1" />
    </system.web>

</configuration>





2. Created a MVC  4.5.1 project

Reaching the, add reference :


  • domain class, to FileUpload.DominClasses.
  • DB context, to FileUpload.DataLayer.

Created a Controller with a View.

namespace FileUpload_MVC.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            using (var context = new FileUploadContext())
            {
                var medias = context.Medias.ToList();

            }
            return View();
        }
    }
}


On the first attempt, when a database hasn’t been setup, asking for the Medias list, Entity Framework will create a database. The database scheme reflects the context class’ names and properties.

image

Influence DB Scheme by Enabling Entity Framework Migrations Feature

Migrations track changes with your C# code.

Within the Package Manager:

1. Select FileUploadDataLayer from Default project dropdown.

pc

2. Type

PM> Enable-Migrations –ContextTypeName FileUploadContext

This will run migrations against the default project creating a Migrations folder in the FileUploadDataLayer project.

image

image

3. Within Configuration.cs, AutomaticMigrationsEnabled is set equal to false. Set AutomaticMigrationsEnabled equal to true. This will allow automatic changes to occur in the database. AutomaticMigrationsEnabled  should only be set true in production or whenever working with beginning stages.

namespace FileUpload.DataLayer.Migrations
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;

    internal sealed class Configuration : DbMigrationsConfiguration<FileUpload.DataLayer.FileUploadContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
            ContextKey = "FileUpload.DataLayer.FileUploadContext";
        }

        protected override void Seed(FileUpload.DataLayer.FileUploadContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
            //  to avoid creating duplicate seed data. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );
            //
        }
    }
}

 

4. Seed method allow automatically populating the database with data. Every time the database is updated it will run the seed method.

protected override void Seed(FileUpload.DataLayer.FileUploadContext context)
{
    context.MediaTypes.AddOrUpdate(mt => mt.Name,
        new MediaType { Name = "JPEG", Extension = "jpg" },
        new MediaType { Name = "GIF", Extension = "gif" },
        new MediaType { Name = "PNG", Extension = "png" }
        );
    context.Medias.AddOrUpdate(r => r.Name,
        new Media { Name = "Kirk", UDate = DateTime.Now, IDate = DateTime.Now, MediaTypeId = 1 },
        new Media { Name = "Kirk", UDate = DateTime.Now, IDate = DateTime.Now, MediaTypeId = 1 },
        new Media { Name = "Kirk", UDate = DateTime.Now, IDate = DateTime.Now, MediaTypeId = 1 }
        );
}

5. Within the Package Manager Console and FileUpload.Datalayer selected as default project, update database with this seed data.

 

PM> Update-Database –Verbose

 

image

 

Migration SQL Script or Update Database are two ways when handling changes when class properties are added or removed.

If AutomaticMigrationsEnabled  is set true, then by just running Update-Database from package manager will handle any scheme changes.

if AutomaticMigrationsEnabled  is set false, then must use a Migration SQL Script. A migration script was created and is located in the Migration folder.

namespace FileUpload.DataLayer.Migrations
{
    using System;
    using System.Data.Entity.Migrations;
    
    public partial class InitialCreate : DbMigration
    {
        public override void Up()
        {
            CreateTable(
                "dbo.Media",
                c => new
                    {
                        Id = c.Int(nullable: false, identity: true),
                        MediaTypeId = c.Int(nullable: false),
                        Name = c.String(),
                        Title = c.String(),
                        Caption = c.String(),
                        Description = c.String(),
                        Path = c.String(),
                        Width = c.Int(nullable: false),
                        Height = c.Int(nullable: false),
                        IDate = c.DateTime(nullable: false),
                        UDate = c.DateTime(nullable: false),
                    })
                .PrimaryKey(t => t.Id)
                .ForeignKey("dbo.MediaTypes", t => t.MediaTypeId, cascadeDelete: true)
                .Index(t => t.MediaTypeId);
            
            CreateTable(
                "dbo.MediaTypes",
                c => new
                    {
                        Id = c.Int(nullable: false, identity: true),
                        Name = c.String(),
                        Extension = c.String(),
                    })
                .PrimaryKey(t => t.Id);
            
        }
        
        public override void Down()
        {
            DropForeignKey("dbo.Media", "MediaTypeId", "dbo.MediaTypes");
            DropIndex("dbo.Media", new[] { "MediaTypeId" });
            DropTable("dbo.MediaTypes");
            DropTable("dbo.Media");
        }
    }
}



This post is for the purpose of my notes only.


“I invented nothing new. I simply assembled the discoveries of other men behind whom were centuries of work. Had I worked fifty or ten or even five years before, I would have failed. So it is with every new thing. Progress happens when all the factors that make for it are ready and then it is inevitable. To teach that a comparatively few men are responsible for the greatest forward steps of mankind is the worst sort of nonsense.”


Henry Ford