Pages

Saturday, September 20, 2014

With a new thought, revisited previous post: JavaScript Chained Inheritance
Included ability to inherit from either an Object or a Constructor function

New Idea


hillHigh.inherit = function (subClass) {
    return new function () {
        var superClasses = [subClass],
            result,
            convertToContructorFunctions = function () {
                for (var i = 0, length = superClasses.length; i < length; i++) {
                    if (Object.prototype.toString.call(superClasses[i]) === "[object Object]") {
                        console.log(i);
                        superClasses[i] = superClasses[i].constructor;
                    }
                }
            };

        this.from = function (superClass) {
            superClasses.push(superClass);
            return this;
        };

        this.provide = function () {
            convertToContructorFunctions();

            for (var i = superClasses.length - 1; i > 0; i -= 1) {
                superClasses[i - 1].prototype = new superClasses[i]();
                superClasses[i - 1].prototype.constructor = superClasses[i - 1];
            }
            return superClasses[0];
        };

        return this;
    };
};


Results



var Fn1 = function () {
    this.a = "a";
};
var Fn2 = function () {
    this.b = "b";
};
var Fn3 = function () {
    this.c = "c";
};
var fn1 = new Fn1();
var fn2 = new Fn2();
var fn3 = new Fn3();

//All Constructor functions
var result0 = hillHigh.inherit(fn3).from(fn2).from(fn1).provide();
//All Objects
var result1 = hillHigh.inherit(Fn3).from(Fn2).from(Fn1).provide();
//Mix Objects and constructor functions
var result2 = hillHigh.inherit(fn3).from(Fn2).from(fn1).provide();

console.log("result0: " + result0.a);
console.log("result0: " + result0.b);
console.log("result0: " + result0.c);

console.log("result1: " + result1.a);
console.log("result1: " + result1.b);
console.log("result1: " + result1.c);

console.log("result2: " + result2.a);
console.log("result2: " + result2.b);
console.log("result2: " + result2.c);


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

Saturday, June 7, 2014

Chained JavaScript Inheritance.

Chained JavaScript Inheritance. Thought this may be useful.

Define Objects:

var Fn1 = function () {
    this.a = "a";
};
var Fn2 = function () {
    this.b = "b";
}
var Fn3 = function () {
    this.c = "c";
}

Inheritance

inherit(Fn3).from(Fn2).from(Fn1).provide();

Extend

Fn1.prototype.aa = function () {
    return "AA";
};
Fn2.prototype.bb = function () {
    return "BB";
};
Fn3.prototype.cc = function () {
    return "CC";
};

Instantiate

var ff = new Fn3();

Inherit Object

var inherit = function (subClass) {
    return new function () {
        var superClasses = [subClass],
            result;

        this.from = function (superClass) {
            superClasses.push(superClass);
            return this;
        };

        this.provide = function () {
            for (var i = superClasses.length - 1; i > 0; i -= 1) {
                superClasses[i-1].prototype = new superClasses[i]();
                superClasses[i-1].prototype.constructor = superClasses[i-1];
            }
            return subClass;
        };

        return this;
    };
};

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

Monday, June 2, 2014

AngularJS and MVC 4 Bundling Optimization

When bundling AngularJS controllers, MVC 4 optimization best optimizes by renaming variables. Shrinking of variables reduces file size, however, when incorporating AngularJS and creating a controller, the $scope variable can NOT be renamed.

Not a big fan of third party scripts, yet the company that I was employed with, I had to find a work around.

This is why I enjoy .Net MVC, because I’m not stuck with a deterministic framework. MS MVC offers many tools. Below is how I got Angular to be minified.
Create a new C# class (NoRenameTransform.cs) and extended the IBundleTransform interface.

Include these namespaces:
System.Web.Optimization
Microsoft.Ajax.Utilities


using System;
using Microsoft.Ajax.Utilities;
using System.Web;
using System.Web.Optimization;

And implement the IBundleTransform interface

public class NoRenameTransform : IBundleTransform
{
    protected static Minifier compiler = new Minifier();

    public void Process(BundleContext context, BundleResponse response)
    {
        var codeSettings = new CodeSettings
        {
            NoAutoRenameList = "$scope"
        };
        response.Content = compiler.MinifyJavaScript(response.Content, codeSettings);
    }
}

The Micorsoft.Ajax.Utilities exposes the Minifier / Minifer ASP.NET object, which has a MinifyJavascript method. MinifyJavaScript method optimizes the file’s contents.

Micorsoft.Ajax.Utilities also exposes the CodeSettings object.

Create a field instantiating Minifier object.

Within the Process method, create a variable instantiating CodeSettings object. Set the NoAutoRenameList property to an array of strings of the item(s) that shouldn’t be changed. The $scope variable will not be minified.

var codeSettings = new CodeSettings
{
    NoAutoRenameList = "$scope"
};

IBundleTransform contract expects a Process method, and the Process method arguments expose BundleContext and BundleResponse.

Within the registered bundle configuration file, instantiate a new ScriptBundle class. ScriptBundle inherits from the Bundle class.

ScriptBundle exposes a Generic IList Transforms property.

Clear Transform

Add a new reference to the NoRenameTransform class.

var scriptBundleCore = new ScriptBundle"~/bundles/Modules/EventsApp");
scriptBundleCore.Include("~/Scripts/Modules/EventsApp/app.js");
scriptBundleCore.IncludeDirectory("~/Scripts/Modules/EventsApp/controllers", "*.js", true);
scriptBundleCore.Transforms.Clear();
scriptBundleCore.Transforms.Add(new NoRenameTransform());
bundles.Add(scriptBundleCore);


Bundle lifecycle:
Global.asax, Application_Start, Bundles are registered

BundlesConfig.RegisterBundles(BundleTable.Bundles);

BundlesConfig.RegisterBundles is called and ScriptBundle objects are added to the BundleTable.
ScriptBundles exposes a default transform property, which can be cleared.

scriptBundleCore.Transforms.Clear();

Add new behavior with how the bundle should be minified.

scriptBundleCore.Transforms.Add(new NoRenameTransform());
The transform Process method is called from when the razor view is rendered.

@Scripts.Render("~/bundles/Modules/EventsApp")

Complete Code

Razor View

@{
    ViewBag.Title = "Index";
}

<div ng-app class="container">
    <div ng-controller="EventController">
        {{name}}
    </div>
</div>

@section scripts {
    @Scripts.Render("~/bundles/Modules/EventsApp")
}

Config.asax

using FileUpload_MVC.App_Start;
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

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

        }
    }
}

BundleConfig.cs

using FileUpload_MVC.Models;
using System.Web.Optimization;

namespace FileUpload_MVC.App_Start
{
    public class BundlesConfig
    {
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Clear();
            BundleTable.EnableOptimizations = true;

            var scriptBundleCore = new ScriptBundle("~/bundles/Modules/EventsApp");
            scriptBundleCore.Include("~/Scripts/Modules/EventsApp/app.js");
            scriptBundleCore.IncludeDirectory("~/Scripts/Modules/EventsApp/controllers", "*.js", true);


            scriptBundleCore.Transforms.Clear();
            scriptBundleCore.Transforms.Add(new NoRenameTransform());
            
            
            bundles.Add(scriptBundleCore);
            
        }
    }
}

NoRenameTransform.cs

using System;
using Microsoft.Ajax.Utilities;
using System.Web;
using System.Web.Optimization;

namespace FileUpload_MVC.Models
{
    public class NoRenameTransform : IBundleTransform
    {
        protected static Minifier compiler =  new Minifier();

        public void Process(BundleContext context, BundleResponse response)
        {
            context.UseServerCache = false;
            response.Cacheability = HttpCacheability.NoCache;

            var codeSettings = new CodeSettings
            {
                NoAutoRenameList = "$scope"
            };
            response.Content = compiler.MinifyJavaScript(response.Content, codeSettings);
        }
    }
}

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

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