Pages

Thursday, September 29, 2016

MVC Setup from Empty ASP.NET template

ASP.Net Empty template doesn't have any nuget packages included, so no packages.json will exist.

1. Installing MVC

Packages Icluded

Microsoft.AspNet.Mvc

Microsoft.AspNet.WebPages

Microsoft.AspNet.Razor

Microsoft.Web.Infrastructure   

References Installed

System.Web.WebPages.Razor

System.Web.WebPages.Deployment

System.Web.WebPages

System.Web.Razor

System.Web.Mvc

System.Web.Helpers

Microsoft.Web.Infrastruture

2. Uninstall-package - References Removed

Microsoft.AspNet.Mvc

System.Web.Mvc

Microsoft.AspNet.WebPages

System.Web.WebPages.Deployment

System.Web.WebPages

System.Web.Helpers

Microsoft.AspNet.Razor

System.Web.Razor

Microsoft.Web.Infrastructure

Microsoft.Web.Infrastruture

Finial complete MVC directory structure:

3. Add Global Application Class File to application

Global.asax.cs

Project right click > Add > New Item… > Select Global Application Class

4. Create folders

·         App_Start (can named anything)

·         Controllers

·         Views

5. Under App_Start create a class file and name it whatever you want - RouteConfiguration.

.axd file types are HTTP Handlers, which should be ignored.

Add code to file:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using System.Web.Routing;

 

namespace myWebsite.App_Start

{

    public static class RouteConfiguration

    {

        public static void Register(RouteCollection routes)

        {

            routes.IgnoreRoute("{resource}.axd/{*pathinfo}");

 

            routes.MapRoute(

                "Default",

                "{controller}/{action}/{id}",

                new { controller = "Home", action = "Index"}

                );

        }

 

    }

}

 

6. Add code to Global.asax class file passing all routes.

using com.waggintails.App_Start;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Routing;

using System.Web.Security;

using System.Web.SessionState;

 

namespace com.waggintails

{

    public class Global : System.Web.HttpApplication

    {

 

        protected void Application_Start(object sender, EventArgs e)

        {

            RouteConfiguration.Register(RouteTable.Routes);

        }

    }

}

7. Within controllers folder, add a MVC5 Controller - Empty

Rename to whatever you like – Home

Add code to file:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

 

namespace com.waggintails.Controllers

{

    public class HomeController : Controller

    {

        // GET: Default

        public ActionResult Index()

        {

            return View();

        }

    }

}

 

8. Within views folder, add an empty view and name the view as the same name that you had for the controller.

Add code to file:

@{

    ViewBag.Title = "Home";

}

 

<h2>Home</h2>

 

And within Views folder, add a web.config file.

Add code to file:

<?xml version="1.0"?>

 

<configuration>

    <configSections>

        <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">

            <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />

            <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />

        </sectionGroup>

    </configSections>

 

    <system.web.webPages.razor>

        <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.3.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="com.waggintails" />

            </namespaces>

        </pages>

    </system.web.webPages.razor>

 

    <appSettings>

        <add key="webpages:Enabled" value="false" />

    </appSettings>

 

    <system.webServer>

        <handlers>

            <remove name="BlockViewHandler"/>

            <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />

        </handlers>

    </system.webServer>

 

    <system.web>

        <compilation>

            <assemblies>

                <add assembly="System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />

            </assemblies>

        </compilation>

    </system.web>

</configuration>

Press F5 and Home view should show correctly

9. <Optional> Include a layout view

Within the Views directory add a view called

_ViewStart.cshtml

This view allow you to specify the path for the layout view.

Add code:

@{

    Layout = "~/Views/Shared/_Layout.cshtml";

}

Within the directory you had specified in _ViewStart, add the specified view -  _Layout.cshtml

Add code – when using layouts, must include @RenderBody.

<!DOCTYPE html>

 

<html>

<head>

    <meta name="viewport" content="width=device-width" />

    <title>_Layout</title>

</head>

<body>

    <div>

        @RenderBody()

    </div>

</body>

</html>

With layout, finial complete MVC directory structure:




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

Thursday, September 1, 2016

Razor Views Predefined Path View

Setting predefined paths where the Razor View Engine locates partial views.

A Look at the Razor View Engine in ASP.NET MVC

Create a class:

public class PredefinedPathViewEngine : RazorViewEngine
{
    public PredefinedPathViewEngine()
    {
        var locationFormat = new[]
                                    {
                                        "~/Views/{1}/{0}.cshtml",
                                        "~/Views/{1}/Partials/{0}.cshtml",
                                        "~/Views/Shared/{0}.cshtml",
                                        "~/Views/Shared/Partials/{0}.cshtml",
                                    };

        PartialViewLocationFormats = locationFormat.ToArray();
    }

}



Register the class within Global.asax.cs Application_Start() method:


protected void Application_Start()
{
    ViewEngines.Engines.Add(new PredefinedPathViewEngine());

}




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, January 23, 2015

Handling JavaScript Dependencies and ASP.Net MVC Framework

In functional or component base programming, tracking dependencies is important.

Methods handling dependency tracking can be handled client side, however, I was using ASP.Net MVC bundling and I wanted server side to handle the JavaScript dependency tracking.

ASP.Net MVC bundling allows extensible points, where I wrote a class with a method that traced a specified directory and included the dependent files into a bundle.

I was using JScript IntelliSense the “Reference” Tag at the top of the JavaScript files, which “if the “path” attribute points to another JS file, any objects or functions defined inside that file-or in a file referenced by that file-will show up in IntelliSense.”

Code below, using the reference tags, I was able to trace dependencies.

I created a class called BundleDependencies and created a reference to this class when registering bundles.

var bundleDependencies = new BundleDependencies();

and calling referencePath method, which returns an array of dependent file names.

This method accepts a relative path off the root to the directory. The files located in the specified directory will be root parent files. The root parent files will not be included in the bundle.

The root parent file is the file that contains the reference. Only reference files will be included in the bundle and not the root parent file. Referenced files that have reference to another file isn't considered a parent file. There can only be one parent file, so all files with a reference will be traversed.

JavaScript file can contain more than one reference:
/// <reference path="Components/DropBox.js" />

/// <reference path="Components/PageTitle.js" />

/// <reference path="Components/RosterList.js" />
and reference a file located in another directory. Must be relative and strictly follow ../ notation:
/// <reference path="../../Application/Model.js" />
Since Visual Studio supports Reference tags, all is need is drag JavaScript file from Solution Explorer and drop on the working JavaScript file.


Bundle Configuration Class

namespace com.hillHigh1980
{
    public class BundleConfig
    {
        public static void RegisterBundles(BundleCollection bundles)
        {
            var bundleDependencies = new BundleDependencies();

            // Script Bundles ================================
            var scriptBundle = new ScriptBundle("~/bundles/Views/Home");
            scriptBundle.Include(bundleDependencies.referencePath("Scripts/Views/Home/Components"));
            scriptBundle.IncludeDirectory("~/Scripts/Views/Home", "*.js", true);
            scriptBundle.Orderer = new NonOrderingBundleOrderer();
            bundles.Add(scriptBundle);

        }
    }
}



BundleDependencies Class

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;

namespace com.hillHigh1980.Models
{
    public class BundleDependencies
    {

        List<string> fileDependencies(string directory, string file, string scriptPath)
        {
            var regularExpression = new Regex(@"^///\s?$", RegexOptions.IgnoreCase);
            Match match;

            List<string> reference;
            string relativePath;
            List<string> directoryParts;
            int countRelativePaths;
            int countFolders;
            var references = new List();
            Func<string,bool> parents = delegate(string parent) { return parent == ".."; };

            var rows = File.ReadAllLines(file);
            foreach (var row in rows)
            {
                match = regularExpression.Match(row);

                if (match.Success)
                {
                    //Parse reference row
                    reference = new List(match.Groups[1].Value.Split('"')[1].Split('/'));
                    countRelativePaths = reference.Count(parents);
                    reference.RemoveRange(0, countRelativePaths);

                    //Parse directory
                    directoryParts = directory.Split('\\').ToList();
                    countFolders = directoryParts.Count() - 1;

                    //Create path where reference is located.
                    directoryParts.RemoveRange(countFolders - countRelativePaths + 1, countRelativePaths);
                    directoryParts.AddRange(reference);

                    //Complete path to reference file.
                    file = string.Join(@"\", directoryParts.ToArray());

                    //Create relative path, which will be added to bundle.
                    relativePath = "~/" + file.Substring(file.IndexOf(scriptPath)).Replace(@"\", "/");

                    //Creating directory path, don't need file.
                    directoryParts.RemoveAt(directoryParts.Count() - 1);
                    directory = string.Join(@"\", directoryParts.ToArray());

                    //Specified refernce may contain additional references.
                    references.AddRange(fileDependencies(directory, file, scriptPath));

                    references.Add(relativePath);
                }
                else
                {
                    //Limit to the first line. All done if not found.
                    break;
                }
            }

            return references;
        }

        //Locates all files within a specified directory.
        //All sub-directories are searched if includeSubDirectories is set true.

        public string[] referencePath(string viewPath, bool includeSubDirectories = false, string scriptPath = "Scripts")
        {
            var references = new List();
            List<string> result;
            string[] directories;

            if (includeSubDirectories)
            {
                directories = Directory.GetDirectories(HttpContext.Current.Server.MapPath(viewPath));
            }
            else
            {
                directories = new[] {HttpContext.Current.Server.MapPath(viewPath)};
            }


            foreach (var directory in directories)
            {
                foreach (var file in Directory.GetFiles(directory))
                {
                    result = fileDependencies(directory, file, scriptPath);
                    references.AddRange(result);
                }
            }

            var responses = references.ToArray();

            return responses;
        }

    }
}
}


NonOrderingBundleOrderer Class


using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Optimization;

namespace com.hillHigh1980.Models
{
    class JSFileTransformer : IBundleTransform
    {
        public void Process(BundleContext context, BundleResponse response)
        {

        }
    }

    class NonOrderingBundleOrderer : IBundleOrderer
    {
        public IEnumerable OrderFiles(BundleContext context, IEnumerable files)
        {
            var count = files.Count();
            var arry = files.ToArray();
            var j = 1;
            BundleFile hold = arry[0];
            BundleFile temp;

            for (int i = 0; i < count; i++)
            {
                if (hold.VirtualFile.Name.IndexOf("_View") == -1)
                {
                    if (j < count)
                    {
                        temp = arry[j];
                        arry[j] = hold;
                        hold = temp;
                        j += 1;
                    }
                }
                else
                {
                    arry[0] = hold;
                    break;
                }
            }

            return arry;
        }
    }
}

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