Posts

Showing posts from 2017

Clean up your LINQ with Load Expressions

Often times in an application, you will need data from across several tables. One approach to get all this data at once is to use the LINQ .Include() function, which will pull in all the data of the specified parent or child table. However, this can often be too heavy, as you may not need every column so you end up pulling more data from the database than is required. When this is the case, the best practice is to use a Data Transfer Object or DTO which is one flat object that combines properties from parents and children. Below, I demonstrate a simple use of a DTO, using . Include() var products = Uow.Context.Products.Include(x => x.ParentTable).Include(x => x.ChildTable).ToList(); var dtoList = new List<ProductDto>(); foreach ( var product in products) { var dto = new ProductDto{ // Copy over properties ... // Copy over parent properties ... // Copy over child properties ... }; dtoList.Add(dto); } As I mentioned before, this i

Scheduling Tasks With Azure Scheduler

Image
In many applications it is necessary to send email notifications on a schedule. There are many ways to achieve this functionality: using a Windows service,  Windows Task Scheduler, or a number of other third party solutions. In our case, we don't have much control over our web server and so we decided against a Windows service. We ended up going with Azure Scheduler which provides a reliable way to hit a network endpoint on a user defined schedule. While not a free solution in most cases, the cost is low for the majority of small applications. Here's how to set up Azure Scheduler: Open the Azure portal and open the Scheduler Job Collections blade. This can be accessed by searching for scheduler in the top search bar in the Azure portal. Click Add in the top left corner. Name the job. The name can only have alphanumeric characters, hyphens, and underscores. Select or create a new job collection.  If creating a new job collection, select your prici

Git good with Git

There will come a time in every developers life where they will have to learn how to use more than one version control software. Here are some steps to set up a Git repository. STEP 1  - Download the latest version of  Git here . STEP 2  - Open your terminal on your local machine. STEP 3  - You will need to tell Git who you are so that all your commits are labeled properly git config --global user.name "YOUR NAME HERE" And your email address: git config --global user.email "YOUR EMAIL ADDRESS HERE"   STEP 4  - Initiate your local repo: cd <directory you want to use git on> git init Finally you can clone your repo: git clone ssh://milo@example.com/path/to/my-project.git cd my-project STEP 5  - Get to work! The code won't write itself!

Software Versioning and You

It's hard to image that after developing for so long that there was a time that I didn't use any type of software versioning software. Yes, you heard me right, there was a time that I would simply edit some code and upload it to a live environment without a way to track any changes. Versioning software like Subversion allows you to keep track of changes to your code in case. Below you will find steps to set up a svn (Subversion) repository on a host machine and locally. STEP 1  -    Insure your host machine has svn install. Just log into the machine and punch in: which svn Your output should look something like this: :~$ which svn /usr/bin/svn If your some reason you don't have svn installed on your host,  here  is where you can get started. STEP 2  -  Now that you have svn installed on your host you can create a repository. Here is the command for that: svnadmin create (PATH TO YOU REPO HERE eg. /users/svnuser/myrepo) STEP 3  - Next you will need to cre

HighCharts Tech Tip

Image
So you have a website with tons of data but don’t have a visualization solution. HighCharts is a purely JavaScript based chart solution that may be the answer to your searching. It is compatible with all modern browsers. If you need a solution for school or your non-profit organization HighCharts is free to use. It offers line, spline, area, area spline, column, bar, pie, scatter, angular gauges, area range, area spline range, column range and polar chart types. Many of which can also be combined. It allows for multiple axes, tooltip point labels, export and print, and zooming. HighChart can have data supplied statically or dynamically through ajax. The GSA Carbon Footprint tool uses the Highcharts library to visualize carbon emissions data.  The General Services Administration (GSA) developed the GSA Carbon Footprint Tool to help Federal Agencies calculate, report, and reduce their greenhouse gas (GHG) emissions as specified under Executive Order (EO) 13514.  https://www.carbonfootpr

Create your own Short URLs

URLs for deeply nested pages can be difficult to read and even harder to remember, especially for new visitors to a website. When giving a presentation or participating in a technical conference, website owners tend to put shortened URLs on their slides so that the audience can write down the link on a piece of paper or navigate on their phone. Many URL shortening sites have caught on and you can find many examples with a quick search. But, these URLs are most often a string of random characters that do not have much meaning. What if we wanted them to be more memorable? Creating Your own Short URLs Lets say you have the following URL which is for a page that has information about the event at which you are presenting. www.mywebsite.com/events/northamerica/2017/july/exampleconference    As you can see from the structure of the URL, the page for this conference is nested within some hierarchy that is related to the organization of the site. Yet, this URL may be difficult for some

Smart Relative date formatting in C# using extension methods.

The C# DateTime object has some nice .ToString() overloads for formatting dates but sometimes we would like a friendly, relative format like what you see in many Android or iPhone apps. The idea is to only include year, month, and day when they are not the current one. Examples are as follows... Just now         55 seconds ago 1 min ago 15 mins ago 1 hour ago 13 hours ago Sunday, 25th at 12:53 PM              -  different day, same month Tuesday, May 2nd at 12:53 PM     -  difference month, same year May 2nd, 2016 at 12:53 PM          - different year I like this format because it's flexible enough to give you a nice relative format that scales well with dates far in the past. To implement, I used an extension method. Since I am using ordinals for the days, I used another extension that I found in a Stack Overflow post . The Humanizr library accomplishes ordinals very well, but in this case I found it to be overkill. All code below. Now put it into action in your

Copying Azure Blob Storage Containers Between Accounts With PowerShell and AzCopy

A few months ago I wrote about backing up and restoring Azure blobs from a local environment. You can read that post  here . This is not an efficient approach for moving blobs from one Azure storage account to another. In this post I will show you how to copy all containers from one account to another using PowerShell and how to copy individual Azure storage containers using AzCopy. Copying All Containers with PowerShell This script will copy all containers from one Azure storage account to another. This can be useful for populating Azure development accounts. First we will set up our Azure storage accounts and create a storage context for each: $SourceAzureAccountName = "SourceAzureAccount" $SourceAzureKey = "SourceAzureKey" $DestAzureAccountName = "DestAzureAccount" $DestAzureKey = "DestAzureKey" $SourceCtx = New-AzureStorageContext $SourceAzureAccountName -StorageAccountKey $SourceAzureKey $DestCtx = New-AzureStorageContext $DestAzur

Azure Blob Removal and Backup/Restore with PowerShell

Azure Blob Storage is a great service for storing unstructured object data in the cloud. In the development phase of  an application utilizing Azure Blob Storage, it can be necessary to wipe out an Azure test account as they get cluttered with test data. In a production application we need a way to backup valuable blob data and restore as needed. In this blog post, I will show you how to do each of these actions using Azure PowerShell. Removal This script will remove all containers from an Azure instance. This is useful for clearing out Azure development accounts. First we need to connect to our Azure storage account and create a storage context: $AzureAccountName = "TestAzureAccount" $AzureKey = "azurekey" $Ctx = New-AzureStorageContext $AzureAccountName -StorageAccountKey $AzureKey Next we loop through all Azure containers in the account and delete them along with their contents. The -Force parameter is added so we are not prompted when deleting containe

HTML5 Buttons Outside Forms

There have been a few places in our applications where it has been necessary to place our submit buttons outside of a form tag. Rather than use CSS to position the button or adding a JavaScript click handler to fire the submit request I opted to use the HTML5 form attribute to attach my button to the form: <form id="my-form"></form> <button form="my-form" class="btn btn-primary">Submit</button> The form attribute provides a clean way to link our button to the form, but unfortunately this method failed while testing in Internet Explorer. This is a case where Internet Explorer has  failed  to conform to the HTML5 standard. After some searching we decided on the solution presented  here . The label for attribute is supported in Internet Explorer and Microsoft Edge and works when placed outside of a form tag. By placing a hidden submit button inside the form and applying button styling to a label outside of the form we get the des

ASP.NET Identity Account Lockout

Image
ASP.NET Identity 2.1 comes with the infrastructure to support varied authentication from the complex two factor to the simple username and password. It also has the ability to enforce rules on sign in to keep account information secure. One feature that comes with out of the box identity but is not enabled by default is lockout. The behavior of the feature is straightforward: a series of incorrect passwords supplied for a given account will force the user to wait a penalty period before attempting to sign in again. This feature needs to be configured the right way to both prevent phishing for user accounts but to also not inconvenience legitimate users who may have mistyped their password a few times in a row. The first step to enabling this feature is to make some changes to your user manager. Below are 3 properties of the user manager that I am setting in the initialization for the class. The first property is one that is repeated in several of the classes we will look

Elmah Scan Exclusion

ELMAH  (Error Logging Modules and Handlers) is a fantastic logging tool for exception tracking in ASP.NET web applications. It captures almost every type of un-handled exception and it captures an incredibly detailed snapshot of what went wrong, making it an essential tool for diagnosing what went wrong on your website. However, the verbosity and spread of what is logged by ELMAH can be a double edged sword as meaningful, important errors can be lost in a sea of noise. Security Scans and a Clean ELMAH Log: Security scans can flood your ELMAH log in a matter of minutes. It is a good practice to frequently run scans on a production environment to find vulnerabilities, so skipping them is not an option. But, neither is omitting logging as production is the environment in which errors have the biggest negative impacts.  So, we must find a way to allow these two tools to coexist without hindering each other. Security scans work by "crawling" a website and trying every possib

Telerik Kendo Dynamic Dropdown & Grid with Pre-selection

Kendo UI elements are incredibly powerful as they can use AJAX calls to dynamically pull and filter data with little to no effort as it all happens behind the scenes if it is set up properly.  Here  is a great reference for creating a dynamic or remotely bound drop-down (i.e the contents are fetched from the database) and  here  is a great reference for filtering another element based on the drop-down list selection. Now, I will show how we hooked the drop-down list to a grid, and then I'll show how we implemented pre-selection to properly filter the grid on the initial page visit.  Filtering the grid from the drop-down: First, set up the grid the grid with a toolbar.  Here  is a great example for this. Below, I've included a stripped down sample that includes the minimum functionality.  @(Html.Kendo().Grid<Product>() .DataSource(dataSource => dataSource .Ajax() .Model(model => model.Id(m => m.Id)) .ServerOperation(true) .Read(read => read.Ac

Access Web.config from another Project.

Image
Many of our .Net web app solutions have multiple class library projects and in those projects we want to access various app settings in a central web.config housed in the web app project. You will find that simply accessing the Configuration Manager in a class library will not compile. Huh? But it works just fine in my web project. Even ReSharper can't help me here. That's because the assembly required for the Configuration Manager doesn't ship with Class Library projects out of the box. To fix the problem add the System.Configuration assembly to your project. If you have ReSharper, it will now be able to help you by automatically importing the namespace. Otherwise, just add it yourself manually. Hope this helps! Published: 12/15/16

ASP.NET MVC - How to enable/disable CaC/Client Certificate authentication per area or route.

Image
Use Case Typically, when you enable CaC/Client Certificates on a web app you enable it for the entire app. But what if you wanted to disable it for certain sections of the site. For example, an API controller, or a specific Area that hosts pages that can be publicly viewed. Luckily, it's very easy to make this happen. I'll walk through an example that requires CaC authentication for the base app but does not require it to make requests on an API controller, which will use leverage the HTTP Authentication header for auth.  1. Modify the web.config To require client certs for the base app, add this snippet inside the <system.webServer> tag. <!-- Access for the Base App --> <security> <access sslFlags="Ssl, SslNegotiateCert, SslRequireCert" /> </security> Now we can selectively disable client certs for specific sections of the app. In this case, I am disabling it for all routes starting with /api/v1 .