Posts

Showing posts from June, 2017

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 .

AJAX Partial Views via a JQuery Plugin

Image
The first time we implemented code to AJAX in a Partial View we were quite happy with the results. The app we were working on was built using the traditional style of server-side rendered views but we wanted to add in some simple AJAX functionality to spruce up the User Experience.  After implementing this code a few times one thing jumped out at us. The potential for “Spaghetti Code”.  Since each action had a unique URL and DOM element to update in the view, we had to write a snippet of JavaScript code for each action, which lead to a lot of code redundancy. So eventually, we attempted to write a reusable plugin that would take care of all of our AJAX calls so we could focus on Strongly Typed Razor partial views and controller code.  A good example of this plugin could be to AJAX in a success or error message upon submitting a Feedback form. To see this in action, you can view the feedback form at SFTool . We will demonstrate how to use this plugin with ASP.Net MVC. Step 1 -

Web applications for a Government Audience: Think twice before using Font Icons

Image
Modern web applications make heavy use of icons and beautiful custom text fonts, and for good reason. Icons and custom fonts are awesome when used properly. But what happens when icons and custom text do not appear for a significant portion of users? Icons Take the following example from Data.gov. They have a very nice looking navigation on their homepage that makes great use of font icons.  However, this is how the site looks using Internet Explorer 11 on a government domain such as DOD. On one hand, the icons are only used as supplements and so even though there is a gaping vertical space between each navigation item, usability is still the same. If you follow this principal and always provide text next every icon, worrying about IE users on government domains is not a high priority. There is also a very minor difference in the text fonts although, it's very subtle. Here is another example where the lack of icons causes a greater impact. You can see