Wednesday, August 31, 2022

 

Revealing Module Pattern for JavaScript








var SiteJavascript = function () {
 
    function test() {
        alert('SiteJavascript test');
    }

    return {
        test:test
    }
};

Usage:
01 reference the script.
In an MVC page all script would be in the @section Scripts section.
<script src="~/js/siteJavascript.js" asp-append-version="true"></script>

02 initialize and call the test function
var site = SiteJavascript();
site.test();

Thursday, October 4, 2012

Using a recursive common table expression to generate a date range

At one company that I worked for, I inherited a bunch of reporting code written in T-SQL. A lot of it was for reporting on monthly information. Sometimes where were inserts into temp tables for month data and the performance was terrible.

One consultant I hired saw some of the T-SQL code and suggested using a recursive common table expression (CTE) to generate dates. This was much faster than inserting into a temp table.

Here is an example of a CTE to generate the range of days for the current month. Obviously using a recursive algorithm can be dangerous. There is a limit on the number of recursive calls that can be made. You can add OPTION (MAXRECURSION N); to the select from a recursive CTE to limit the number of interations where N is a number between 0 and 32,767.

 
DECLARE @StartDate datetime
DECLARE @EndDate datetime
SET @StartDate = DATEADD(month, DATEDIFF(month,'20120101', CURRENT_TIMESTAMP), '20120101')
SET @EndDate = DATEADD(month, DATEDIFF(month,'20120131', CURRENT_TIMESTAMP), '20120131')

;WITH DateRange(Date) AS
    (
        SELECT
            @StartDate Date
        UNION ALL
        SELECT
            DATEADD(day, 1, Date) Date
        FROM
            DateRange
        WHERE
            Date < @EndDate
    )
SELECT * FROM DateRange

First and last day of the current month T-SQL

In programming there are usually many ways to accomplish a given task. A good developer is always on the search for a cleaner algorithm. The caveat being that less code is great as long as it does not come at the expense of code readability/maintainability.

One algorithm question I used to ask in interviews went as follows:

Give me an algorithm to calculate the last day of the current month assuming that your language has functions to both create dates and perform date arithmetic.

A simple way to do this is to find the first day of the next month, and subtract a day. T-SQL does not have a last day of the month function so I found that I was having to write code like this a lot:

 
declare @startDate dateTime
declare @endDate dateTime
set @startDate = getDate()
set @startDate = CAST(CAST(YEAR(@startDate) AS VARCHAR(4)) + '/' + CAST(MONTH(@startDate) AS VARCHAR(2)) + '/01' AS DATETIME)
set @endDate = DATEADD(month, +1, @startDate)
set @endDate = DATEADD(day, -1, @endDate)

print @startDate
print @endDate

But in reading Itzik Ben-Gan's book T-SQL Fundamentals, he illustrated a simpler way to to this:
DECLARE @StartDate datetime
DECLARE @EndDate datetime
SET @StartDate = DATEADD(month, DATEDIFF(month,'20120101', CURRENT_TIMESTAMP), '20120101')
SET @EndDate = DATEADD(month, DATEDIFF(month,'20120131', CURRENT_TIMESTAMP), '20120131')
print @startDate
print @EndDate 

This way simply calculates the month offset between an anchor date and the current date and then adds that many months back to the anchor date. If the anchor date is the first date of its month, this yields the first date of the current month. However if the anchor date is the last day of its month, you get the last day of the current month.

For me a much more elegant algorithm that is readable and maintainable.

Practical example of the Revealing Module Pattern in JavaScript

One of my friends, Russell Durham, created an excellent blog post on the revealing module pattern in javascript. I asked him if I could replicate this on my blog. The original post is JavaScript Revealing Module Pattern

The revealing module pattern is one of several patterns that allow you to create namespaces within your javascript while also providing a method of creating public and private functions. In general, anything you write in a script block is considered to be in the global namespace so any other javascript on the page will have access to it.
 
function globalOne() {
 //random code here
};

function globalTwo() {
 globalOne();
}; 
I’ve seen a lot of developers that actually write javascript this way and while it may still work it is not a good practice. When writing your class libraries or other server side code you wouldn’t (at least I hope you wouldn’t) expose every function within the library. Some functions exist only to help the public functions complete their task and have no business being called outside of the library. The same can apply to javascript functions. Let’s say you have an online shopping site and while in the checkout process the user can update the quantity of what’s in the cart as well as the shipping method and this in turn updates the total. Using the method above of keeping everything in the global namespace our javascript would look something like this:
function updateQuantity(newQuantity) {
 //code to update the quantity
 updatePrice(newPrice);
};

function updateShipping(newShippingMethod) {
 //code to update the shipping method
 updatePrice(newPrice);
};

function updatePrice(newPrice) {
 //code to update the price
}; 
Functionally, this code is correct. It meets the requirements and everything is good. However, now everyone has access the the updatePrice function. I’m not sure about everyone else but I sure don’t want my users to be able to update the price whenever they feel like it. I want a little more control over how and when that function is called. This is where the revealing module pattern comes in. The pattern is pretty simple:
var myObject = (function() {

 var publicFunction = function() {
  //do something public
 };

 var privateFunction = function() {
  //do something private
 }

 return {
  doSomething: publicFunction
 }

})();
The first thing you’ll notice is that we create an object to place the functions inside of. Doing this removes the functions from the global namespace and makes the only visible within the scope of the object (making them all private). To make a function public you need to return the function from within the object which is done on line 11. Notice how left of the “:’” is “doSomething” while to the right is the name of our function. Changing the value on the left side allows us to change the name of the public facing function. So now, instead of calling:
myObject.publicFunction();  
We can call it like this:
myObject.doSomething();  
In this case doSomething is mapped to publicFunction. Now that we’ve seen the pattern, let’s apply it to our earlier example with the shopping cart.
var cart = (function() {

 function updateQuantity(newQuantity) {
  //code to update the quantity
  updatePrice(newPrice);
 };

 function updateShipping(newShippingMethod) {
  //code to update the shipping method
  updatePrice(newPrice);
 };

 function updatePrice(newPrice) {
  //code to update the price
 };

 return {
  updateQuantity: updateQuantity,
  updateShipping: updateShipping
 }

})();
That’s much better. Now all the functions are removed from the global scope and placed inside of our new cart object. Only updateQuantity and updateShipping are returned which means that updatePrice is now a private method that can not be accessed outside of the cart object. To call our new functions is a simple as:
cart.updateQuantity(5);
cart.updateShipping('overnight');  
However, if we try and call cart.updatePrice(5.00) we’ll have an exception thrown since cart.updatePrice does not exist. As I mentioned before there are other patterns that can be used to accomplish the same thing but the revealing module pattern is the one I find myself using the most often. It is easy to read, easy to use and makes exposing public members simple.

Monday, September 17, 2012

Conversion between HTTPContext and HTTPContextBase

 
// Getting HttpContext from HttpContextBase:
HttpContext httpContext = httpContextBase.ApplicationInstance.Context;


 
// Getting HttpContextBase from HttpContext:
HttpContextBase httpContextBase = new System.Web.HttpContextWrapper(context);




Wednesday, September 5, 2012

Returning null when implementing IDependencyResolver

We have an MVC4 application that uses the Unity IoC container. Upon startup there were numerous errors like

Activation error occured while trying to get instance of type IControllerFactory, key ""

I found a fix for this in a stackoverflow article: Activation error occured while trying to get instance of type. The article included an implementation of IDependencyResolver that returned null when an object could not be resolved.

I then remembered that that I had used this solution before without really thinking about it.

I found a better explanation in this article ASP.NET MVC 3 Hosting :: Problem in implementing IControllerActivator in ASP.NET MVC 3.

Wednesday, March 28, 2012

SelectListItems from a LINQ query using anonymous types

 
                var searchList = from products in productdbConnection.Products
                                 group products by products.Discontinued  into g
                                 select new SelectListItem
                                 {
                                     Text = g.Key.ToString(),
                                     Value = g.Key.ToString()
                                 };
I wanted to show an example of creating SelectListItems from a LINQ query using anonymous types and grouping to grab distinct elements.