CSS not updating on .NET core website deployed using Visual Studio Online and Azure

UPDATE!

Very stupid of me to setup multiple steps for each dependencies, after reading this on stackoverflow.com, I actually had to only setup 1 npm command which would be npm install and it would automatically pickup all dependencies from the package.json folder. :)

AZURE & Visual Studio Online

I always wanted to try out Azure, I was always fascinated by how Scott Hanselman always demo’d how easy and simple it is to build and deploy using Azure. So I decided to give it a try. I made a .NET Core Web app, a Visual Studio Online account and deploying to Azure from there.

Everything is very straight forward and I am sure that anyone would be able to setup that. Next I configured gulp by creating gulpfile.js – Can read more here. But once the site got deployed, any css changes I make, had no effect on the website even after re-deploying. Also note I did not commit the .min.css and .min.js files.

FIX

To fix this, I found that in the build steps you can configure gulp to run. I set it up to run post-build, few additional things I had to do was configure multiple npm installs steps for gulp and rimraf which I was using.

steps for setting up website deployment on visual studio online

With these changes, now everytime I see gulp running after a successful build and I have setup a default task which cleans and builds both css and js, below is the gulpfile.js I am using.

/// <binding Clean='clean' AfterBuild='postbuild' />
"use strict";

var gulp = require("gulp"),
    rimraf = require("rimraf"),
    concat = require("gulp-concat"),
    cssmin = require("gulp-cssmin"),
    uglify = require("gulp-uglify");

var paths = {
    webroot: "./wwwroot/"
};

paths.js = paths.webroot + "js/**/*.js";
paths.minJs = paths.webroot + "js/**/*.min.js";
paths.css = paths.webroot + "css/**/*.css";
paths.minCss = paths.webroot + "css/**/*.min.css";
paths.concatJsDest = paths.webroot + "js/site.min.js";
paths.concatCssDest = paths.webroot + "css/site.min.css";

gulp.task("clean:js", function (cb) {
    rimraf(paths.concatJsDest, cb);
});

gulp.task("clean:css", function (cb) {
    rimraf(paths.concatCssDest, cb);
});

gulp.task("clean", ["clean:js", "clean:css"]);

gulp.task("min:js", function () {
    return gulp.src([paths.js, "!" + paths.minJs], { base: "." })
        .pipe(concat(paths.concatJsDest))
        .pipe(uglify())
        .pipe(gulp.dest("."));
});

gulp.task("min:css", function () {
    return gulp.src([paths.css, "!" + paths.minCss])
        .pipe(concat(paths.concatCssDest))
        .pipe(cssmin())
        .pipe(gulp.dest("."));
});

gulp.task("min", ["min:js", "min:css"]);

gulp.task("default", ["clean:js", "clean:css", "min:js", "min:css"]);

Hope this helps.

Multiple tab issue with Signal R

So, in the last project I worked in my previous company, We had developed an internal web portal using ASP.NET MVC and SQL, Signal R for realtime notifications. We leveraged Signal R to send realtime messages and notifications to the users. However there was this one unusual issue which people begun to notice — After opening X number of tabs, the newest tab does not load. It wont load until you close one of the already opened tabs. This over the time became very embarrassing and we decided to look for a fix.

After reading a little bit about this issue on the internet, found some interesting concepts. Sharing them below

Browsers have a maximum number of concurrent connections, usually around 6. After opening 6 or more tabs in the browser, all pointing to the same site, subsequent tabs would simply refuse to load.Source

So, all in all we found there are 2 ways in which this issue should be addressed. One of them is more like a quick fix, while the other one is the correct but time-consuming approach.

1. QUICK FIX – Close the connections from the client whenever the tab is not in use, and re-connect when tab is active

There are plenty of ways one can find when a tab is active or inactive. Using these events one can start/stop a connection. When the tab is not in focus, we killed off the connection of that tab, and when the user is back on that tab, we again reconnect to the hub.

window.addEventListener('focus', function() {
    signalRHub.connect();
});

window.addEventListener('blur', function () {
    signalRHub.disconnect();
});

2. Using localstorage as a message bus between the tabs

In this approach you will need only a single Signal R connection open, thereby preventing the multiple connection problem. Here localstorage can act like a message bus between the tabs, the storage event helps in broadcasting data between the tabs.

The concept is fairly simple. Only one tab keeps a push connection; we call this the master tab. When it receives a push event, it broadcasts it by setting the event as a property on local storage called “broadcast”. When a tab receives the storage event for this key, it reads the JSON-encoded event object from local storage and processes it as though it had been received via an EventSource object.Source

Further reading?
1. https://github.com/SignalR/SignalR/issues/2744
2. https://blog.fastmail.com/2012/11/26/inter-tab-communication-using-local-storage/

Hope this helps :)

Enabling and configuring Http-Redirection on IIS 7

There is always a use case or a scenario where one might want to redirect all request from your website to some other website. The element configures settings for Internet Information Services (IIS) 7 that redirect client requests to a new location.

To begin with, make sure you have HttpRedirect feature enabled, if not it can be easily be enabled by going to the “Programs & Features” >> “Turn Windows features on or off” and enabling “HTTP Redirection” module.

enter image description here

Once you have made sure you have the necessary module installed. Let’s quickly see how to setup the redirection.

enter image description here

enter image description here

Simply put in the url where you want the redirection to happen. You can also redirect to the exact destination instead of relative using the options provided.

Hope this helps. Cheers!

Prevent Elmah to send mail on specific type of errors but log them to db.

Approach 1 :

The below filter when added, will stop both – sending out error email and logging to the db.

<errorFilter>
    <test>
        <!--<equal binding="HttpStatusCode" value="404" type="Int32" />-->
        <regex binding="BaseException.Message" pattern="404 request received" />
    </test>
</errorFilter>

Approach 2 :

The below filter will only stop sending out mail, but will continue to log to the db.

<errorFilter>
    <test>
        <or>
            <and>
                <regex binding="BaseException.Message" pattern="404 request received" />
                <regex binding="FilterSourceType.Name" pattern="mail" />
            </and>
            <and>
                <regex binding="BaseException.Message" pattern="Any xyz pattern can go in here..." />
                <regex binding="FilterSourceType.Name" pattern="mail" />
            </and>
        </or>
    </test>
</errorFilter>

Prevent elmah to be cached when using CDN.

It has been a common practice to use ELMAH for pretty much all of my web projects built using the ASP.NET stack.

One problem I kept running into was when using CDN with a website, there was no simple/direct way to tell the CDN to not cache the elmah urls. Here’s a solution which worked for me.

Step 1: Select website and add a url rewrite rule

Step 2: Make sure to select the “Outbound” rule when selecting the rule template

Step 3: Add a precondition, in this case add the elmah url

Step 4: Add a rule to update your response header’s Cache-Control with no-cache

Step 5: Done, now check the http response on your browser

References:

Using key press event in Angular JS

It is a very common use case to catch event of certain key press, like the enter key for example. In this post, I am gonna write about how to handle key press event in Angular JS – using the so called “angular way” approach.

Problem statement:
Let’s define a problem statement to begin with. I have a form with one text field and a button next to it.

enter image description here

And then there was a directive…
This directive checks for keydown & keypress and checks the keycode, 13 in case of the enter key.

app.directive('EnterPressed', function() {
    return function(scope, element, attrs) {
        element.bind("keydown keypress", function(event) {
            if (event.which === 13) { // 13 is the code for enter
                scope.$apply(function() {
                    scope.$eval(attrs.myEnter);
                });
                event.preventDefault();
            }
        });
    };
});

and that’s about it. We are done.

Usage:

<div ng-app="" ng-controller="WierdController">
    <input type="text" enter-pressed="doSomething()">
    <button ng-click="doSomething()">Let's go!</button>
</div>

When to use ng-if vs ng-show/ng-hide in Angular JS

Both ng-if and ng-show/ng-hide directives, shows/hides/removes/add HTML to the DOM based on expression provided to the attribute. The approach they use to do this is different though.

ng-show – The element is shown or hidden by removing or adding the .ng-hide CSS class onto the element.

ng-if, on other hand differs from ng-show and ng-hide in that ng-if completely removes and recreates the element in the DOM rather than changing its visibility via the display CSS property.

You might notice a significant improvement in the responsiveness of your app if you repalce all your ng-show/ng-hide with ng-if. Because ng-show leaves the element on the DOM and all of its watch expressions and performance costs would still exists even though these elements are not viewable to the user.

References :

How to add an exclusion list to an HTTP Module in ASP.NET MVC

When writing your own HTTP Module you will need to have an exclusion list, so that not all HTTP request are intercepted by this module. Like for example: HTTP requests for CSS, JS, Images and even Html templates.

Here is what I used in one of our recent projects

private bool ShouldProcessRequestForSignUp(HttpRequest request)
{
    bool isAnAjaxRequest = request.RequestContext.HttpContext.Request.IsAjaxRequest();
    bool isRequestIsForLogoff = request.Url.AbsolutePath.ToLower().Contains("/account/logoff");
    bool isRequestIsForLogin = request.Url.AbsolutePath.ToLower().Contains("/account/login");
    bool isRequestForResources = (request.Url.AbsolutePath.ToLower().Contains("content") || request.Url.AbsolutePath.ToLower().Contains("scripts"));
    if (isAnAjaxRequest)
        return false;
    if (isRequestFortheSignupPage || isRequestIsForLogoff || isRequestIsForLogin)
        return false;
    if (isRequestForResources)
        return false;
    return true;
}

Updating one to many relationship tables using Entity Framework 6

Problem Statement

Consider the following diagram, where there is one to many relationship between the Employee and Assest table. Here 1 Employee can have M Assests.

enter image description here

Lets say an Employee has 2 assests namely –

OldList NewList
Home Home
Bike Car

So there are 3 things to be done when updating this data using the Entity Framework

  1. Look for items present in the newlist and missing in the oldlist, these items are to be added. The item “Car” in this example.
  2. Look for items present in the oldlist and missing in the newlist, these items are to be removed. The item “Bike” in this example.
  3. And finally the items that are present in both the list. The item “Home” in this example, is to be untouched.

Code

The following code uses ExceptBy extension method to compare two lists and return based on the key passed to it.

public void UpdateEmployeeAssests(int employeeId, List<EmpAssets> updatedAssests)
{
    using (var context = new SampleDbEntities())
    {
        List<EmpAssets> oldAssests = context.EmpAssets.Where(x => x.EmployeeId == employeeId).ToList();

        List<EmpAssets> addedAssests = updatedAssests.ExceptBy(oldAssests, x => x.CityId).ToList();
        List<EmpAssets> deletedAssests = oldAssests.ExceptBy(updatedAssests, x => x.CityId).ToList();

        deletedAssests.ForEach( x => context.Entry(x).State = EntityState.Deleted);
        addedAssests.ForEach(x => context.Entry(x).State = EntityState.Added);

        context.SaveChanges();
    }
}

References: