Johnny Code

Fear no code

Filtering Out Linked Documents

By John Bubriski on February 21, 2012

Note: I wanted to add some screenshots to this post, but didn’t have the time. I don’t think it’s super important, but it would definitely help outline the potential issue with Linked Documents.

Linked Documents are a great feature of Kentico.  They allow you to create a page that is essentially a shortcut to another page in the content tree.  To create a linked document you simply create a new document, and you select “Linked Document” instead of selecting a document type. If you’re not familiar with the functionality, check out the well-written docs.

While linked documents provide some great functionality they can also cause a duplication issue.  If you’re using a Repeater to select a path that contains both the original and the linked document, both will appear in the list!

Repeaters

Fixing this with a repeater is easy.  Simply configure the repeater and check the box that says “Filter out duplicate documents”!

Piece of cake!

Other List Controls

But what about menu web parts like the CSS List Menu or Drop Down Menu?  This is a little trickier since they don’t have options to automatically filter out the linked documents.  Instead we can do it using a simple SQL Where clause.  If a document is a Linked Document, the “NodeLinkedNodeID” field in the CMS_Tree table will be the ID of the original Tree Node.  So we can use this as the Where clause for the menu web part:

NodeLinkedNodeId IS NULL"

(Note: you don’t need to put “WHERE” at the beginning of the where clause when configuring Kentico controls)

Another piece of cake!

Posted in Kentico | Tagged Kentico CMS, Linked Documents, Menu Web Parts, Repeater | Leave a response

Introducing Encryptamajig, Symmetric Encryption in C# using AES

By John Bubriski on February 15, 2012

This isn’t my normal type of “full” post. Rather, I wanted to plug my own project which attempts to “standardize” the way people do Symmetric Encryption in .NET using the AES algorithm (the successor to Rijndael).

It’s called Encryptamajig.

To quote the project readme:

“When you look at encryption examples online many are verbose, misleading, outdated, or flat out insecure. By creating this project I hope to provide a single resource that myself and others can use to incoporate encryption into their .NET projects.

My goal is to make sure this project uses an up-to-date encryption algorithm and forces appropriate usage of that algorithm.”

The interface has been simplified so all you need to do is make 2 calls, 1 for encryption and 1 for decryption:

var _key = "Keep me safe";
var _plainText = "Some plaintext you want to encrypt";

var encrypted = AesEncryptamajig.Encrypt(_plainText, _key);
var roundtrip = AesEncryptamajig.Decrypt(encrypted, _key);

For more information about the project, and encryption, take a look at the well written readme on the project page. If you have something to contribute to the project, just send me a pull request on Github!

Posted in Programming | Tagged .NET Framework, AES, C#, Cryptography, Decryption, Encryption, Rijndael, Symmetric Encryption | Leave a response

Ignoring Elmah Exception Spam

By John Bubriski on February 13, 2012

Did you setup Elmah on your website or web application? Yes? Great.

Are you getting 100′s or 1000′s of exception emails every day for bots probing your site for various applications and application frameworks? Yes? Not great.

Did you filter all those emails into a folder in your inbox? Yes? Then you’re doing it wrong.

I’m on IIS 7

Nip it in the bud and implement some filtering to kill those requests so that you never even see them! This question on StackOverflow has a great way of using the Request Filtering Module to accomplish just that in IIS 7.

But what about IIS 6?

We can’t all be on the latest and greatest.  As far as I know, we don’t have Request Filtering in IIS 6, nor can we use the official IIS URL Rewrite Module (Available for free via the Web Platform Installer if you are running IIS 7).

While this is less than ideal, it’s not hard to take those problematic requests and ignore them through and Elmah Error Filter.

First we need to use the Open Source URL Rewriter for .NET to return a 403 Forbidden result for those requests.  In my case, 99% of those requests are looking for various PHP applications that probably have vulnerabilities in older versions.  So I’m going to forbid any PHP files right off the bat by adding this to my Web.Config:

<rewriter>
  <if url="^(.+).php$">
    <forbidden />
  </if>
</rewriter>

Now that you have the PHP requests returning a 403 Forbidden status code we can ignore them with an Elmah Error Filter block in the Web.Config.

<elmah>
  <errorFilter>
    <test>
      <equal binding="HttpStatusCode" value="403" type="Int32" />
    </test>
  </errorFilter>
</elmah>

In my case, I’m dealing with a simple public website that doesn’t incorporate any authentication or authorization, so I never actually use 403 Forbidden status code.  There may be a more elegant way to do this.  But this works.

Posted in Programming | Tagged 403 Forbidden, Elmah, IIS, IIS6, IIS7, Request Filtering, URL Rewriting | 2 Responses

SQL Server Cell-Level Symmetric Encryption: The right way

By John Bubriski on February 9, 2012

So I needed to encrypt some sensitive data being stored in SQL Server. I looked into encrypting the data at the application level via C#, but that would mean I would need to ship encrypted data and keys around, which defeats the purpose (we use a thick client). So I turned to SQL Server to handle the encryption for me, and I was pleasantly surprised!

Types of Encryption

There are 2 general types of encryption in SQL Server that you can employ:

  • TDE (Transparent Data Encryption) – Encrypts your whole database. Available only in SQL Server 2008 Enterprise Edition and SQL Server 2008 Developer Edition (and later).
  • Cell-Level Encryption – Encrypts individual cells. Available in all SQL Server editions (since 2000 I think).

There are other ways to encrypt your data, such as encrypting your entire hard drive, but we’ll focus on the options directly provided by SQL Server. For the purpose of this article, we’ll be focusing on Cell-Level Encryption.

When is SQL Server Encryption Recommended?

You might want to use SQL Server Encryption if you want to minimize the changes to your application code. Injecting encryption code into an existing codebase can be painful, especially if you have to modify all your data access code. Encryption via SQL Server can help limit your attack surface since your sensitive data will spend less time at the client, whether that be your web server or a thick client.

Limitations/Drawbacks.

You have to modify your database to use varbinary fields instead of plain varchar or nvarchar fields. While I don’t think this is a huge deal, it might be a problem for those who don’t have free reign over their DB schema, or when the database table is being accessed directly by multiple applications. If you’re using Stored Procedures or a common Data Access Layer, this isn’t a big deal.

Show me the code!

Let’s say we want to encrypt some credit cards. I’m using the AdventureWorks sample database from Microsoft for my example so the code below should work on your machine too. Plus, the AdventureWorks DB is already storing unencrypted credit cards! Oh noes!

First, we need a Master Key. The Master Key encrypts your other keys to keep them safe.

IF NOT EXISTS
(SELECT * FROM sys.symmetric_keys WHERE symmetric_key_id = 101)
CREATE MASTER KEY ENCRYPTION BY
PASSWORD = 'Some long key that you will guard with your life'
GO

(Important: Make sure you save your Master Key Password someplace safe!)

Now we need to create a Symmetric Key that will encrypt the data, and a Certificate to access the Key:

CREATE CERTIFICATE CreditCards
WITH SUBJECT = 'Customer Credit Card Numbers';
GO

CREATE SYMMETRIC KEY CreditCards_Key_01
WITH KEY_SOURCE = 'A pass phrase from which to derive the key.',
IDENTITY_VALUE = 'An identity phrase from which to generate a GUID for tagging data that is encrypted with a temporary key',
ALGORITHM = AES_256
ENCRYPTION BY CERTIFICATE CreditCards;
GO

(Important: Like the Master Key Password, make sure you store the Symmetric Key KEY_SOURCE and IDENTITY_VALUE someplace safe!)

The first block will generate a Certificate that allows you to easily work with the Key without having to provide the Password for that Key. The second block will generate the actual Symmetric Key that is used to perform the encryption and decryption. The Key_Source and Identity_Value options tell SQL Server to generate the Key in a specific way. If we need to regenerate the key on another instance/server we can pass in the same values and get the same Key. This is very important in the case that your server ever dies or you need to migrate your keys for other reasons. The Algorithm is specifying the 256 bit version of the AES encryption algorithm. It’s a standardized, strong algorithm that is frequently used. Finally, note the 2nd to last line where we reference the Certificate.

I would recommend that you always create your Key with a Key_Source and Identity_Value. Without them, I’m not even sure if you can retrieve your Key, and it will definitely be easier tto recreate the Key having those two items on hand. As Michael Coles said:

“For my tastes, it would make more sense to require IDENTITY_VALUE and KEY_SOURCE options by default.”

Now let’s add an extra column to our table to store the encrypted data:

ALTER TABLE Sales.CreditCard
ADD CreditCardNumberEncrypted varbinary(128);
GO

(Note: I haven’t run into any problems with my own data, but if you’re storing “bigger” data, then you might need to increase the varbinary column size)

Great! Now we can encrypt our existing data into the new column:

OPEN SYMMETRIC KEY CreditCards_Key_01
DECRYPTION BY CERTIFICATE CreditCards

UPDATE Sales.CreditCard
SET CreditCardNumberEncrypted = EncryptByKey(Key_GUID('CreditCards_Key_01'), CardNumber);
GO

Finally, let’s look at the data in the table now.

OPEN SYMMETRIC KEY CreditCards_Key_01
DECRYPTION BY CERTIFICATE CreditCards;
GO

SELECT
CardNumber
    , CreditCardNumberEncrypted
    , CONVERT(nvarchar, DecryptByKey(CreditCardNumberEncrypted)) AS 'Decrypted Credit Card Number'
FROM Sales.CreditCard
GO

(Important: If you’re not seeing the correct data come back, make sure that you are converting to the correct type of the original data! In this case, the data was from a nvarchar column. Also, make sure you’re decrypting the correct column.)

That should spit back the original credit card number, the encrypted version, and then the decrypted version (which should match the original).

At this point all of your data should be encrypted, and you should be able to drop the unencrypted column. If you’re working with existing code, you can rename the Encrypted column to match the old name, and just make sure you decrypt the data in your queries. In the specific case of credit cards, you might want to add an additional column to store the last four digits unencrypted for easier retrieval.

(Important: Never store the CCV/CVV from credit cards. I’m pretty sure it’s illegal.)

One last note. If your application user doesn’t have full access to the database (which it probably shouldn’t) then you will need to grant some permissions in order for the user to use the encryption Certificate and Key. From the MSDN: “VIEW DEFINITION permission on the Symmetric Key and CONTROL permission on the Certificate” are required:

GRANT VIEW DEFINITION ON SYMMETRIC KEY::CreditCards_Key_01
TO Test;

GRANT CONTROL ON CERTIFICATE::CreditCards
TO Test;

Just make sure that you are handling permissions correctly!

Thanks for listening, and let me know if you have any feedback!

Full Script

Attached is a SQL Server script of all the commands from the post:

Setup Credit Card Encryption on AdventureWorks SQL Script

Resources/References

Below are some of the references and resources I used to write this post.

General

Good overview of Encryption in SQL Server 2008
Encryption Hierarchy
How to: Encrypt a Column of Data

Backup/Regeneration of Keys and Certificates

“Cloning” Symmetric Keys
How to: Create Identical Symmetric Keys on Two Servers
Deleting and Re-creating Encryption Keys
My ServerFault question on the subject

MSDN T-SQL References

varbinary
CREATE SYMMETRIC KEY
OPEN SYMMETRIC KEY
GRANT Symmetric Key Permissions
GRANT Certificate Permissions

Posted in Programming | Tagged AdventureWorks, AES, Cell-Level Encryption, Certificates, Credit Cards, Cryptography, Decryption, Encryption, SQL, SQL Server, Symmetric Encryption, TDE, Transparent Data Encryption | 2 Responses

In IIS6 HTTP 301 Redirect from non-www to www

By John Bubriski on January 4, 2012

This article applies to IIS6, but the concept applies to almost any public website.  You should probably setup a 301 redirect from http://example.com to http://www.example.com (or the other way around). If you don’t, bad things can happen.  Anyway, here is how you can do it in IIS6:

Instructions

Create a new website with the same IP and host name as your main website, but do not include the www. FYI, I think that IIS will yell at you if you try and create 2 websites with the same IP and host name. I add “redirect” to the end of mine so that I know it’s the redirect website.

IIS6 Redirect Website Setup

IIS6 Redirect Website Setup

Then, in the “Home Directory” tab of the redirect website:

  1. Check the radio button that says “A redirection to a URL”.
  2. Enter in your domain like this, without the double quotes: “http://www.example.com$S$Q”
  3. Check the box that says “The exact URL entered above”.
  4. Check the box that says “A permanent redirection for this resource”.
IIS6 Website Settings

IIS6 Website Settings

Now I would test that the non-www version of your website redirects to the www version.  If you want to be 100% sure what is happening, look at the Net tab in Firebug or the Network tab in the Google Chrome Web Inspector.

Caveats/Debugging

If your company manages your internal DNS, you might encounter an issue resolving some of the hostnames internally.  For example, at the time of writing, “http://example.com” doesn’t work from inside our corporate network!  It’s not a big deal, but in our case it times out so it might give the illusion that the website is down.

I’m pretty sure this wont handle the HTTPS version of your site.  You would need to add another redirect website for that.   However, I don’t think that will work correctly because modern browsers will realize that there is no cert for the non-www, and never even load the content from the site.  You would probably get some big warning instead.  So just make sure that you don’t link the https://example.com anywhere.

Credit

I actually found this solution inside a question on Stackoverflow about a problem with setting up 301 redirects in IIS 6.  There is also a link in the first paragraph of this post about reasons you should do this.

Posted in Programming | Tagged HTTP 301 Redirect, IIS, IIS6 | Leave a response

New Developer Resources Page on Johnny Code!

By John Bubriski on November 17, 2011

I’ve added a new page called Developer Resources.  It’s going to be a repository of all of the blogs I read and podcasts I listen to.  It’s a work in progress, but most of the podcasts I listen to regularly are up there now.  Feel free to post suggestions!  Most everything there will be programming/IT related.

Posted in Programming | Tagged Blogs, Podcasts, Resources | Leave a response

ASP.NET MVC Extension Method for the ID in the Route

By John Bubriski on November 9, 2011

If you’ve worked on an ASP.NET MVC site, you may have had to reference the ID in the current route.  In a Razor view you can reference it via the following variable:

@Url.ViewContext.RouteData.Values["id"]

You may use this a lot if you have a lot of inter-action navigation. Why not throw it into an extension method!?

This makes the assumption that you’re using the default route, or a similar one with an “id” parameter:

namespace System.Web.Mvc
{
    public static class ContextExtensions
    {
        public static string Id(this HtmlHelper helper)
        {
            return helper.ViewContext.RouteData.Values["id"].ToString();
        }
    }
}

Now you can reference the id much easier like this:

@Html.Id()

And if you ever need to change it, you can update it in one place!

Posted in Programming | Tagged .NET Framework, ASP.NET, ASP.NET MVC, C#, Code, Extension Method | Leave a response

Custom Validation with BizForms

By John Bubriski on October 17, 2011

Ever need to inject some custom validation into a BizForm?  Check it:

Below I’ve provided a method you can drop into your BizForm code behind, or the code behind of a BizForm clone.  Then, call this method from an event handle for the OnBeforeValidate event.  If Field A has a value this validation method forces the user to enter a value for Field B.

Keep in mind that this is simply an example of adding custom validation.  Just remember: the sky is the limit!

One last quick note: This example used BizForms, but you can probably apply this same technique to Document Forms and Custom Table Forms.

private void ShowErrorIfParentHasValueAndChildIsEmpty(string fieldAName, string fieldBName, string errorMessage)
{
    var parentControl = (EditingFormControl)uxBizForm.BasicForm.FieldEditingControls[fieldAName];
    var childControl = (EditingFormControl)uxBizForm.BasicForm.FieldEditingControls[fieldBName];

    var parentControlValue = parentControl.Value.ToString();
    var childControlValue = childControl.Value.ToString();

    if (!string.IsNullOrWhiteSpace(parentControlValue) &amp;&amp; string.IsNullOrWhiteSpace(childControlValue))
    {
        var errorLabel = uxBizForm.BasicForm.FieldErrorLabels[fieldBName] as LocalizedLabel;
        errorLabel.Text = errorMessage;
        errorLabel.Visible = true;

        uxBizForm.BasicForm.StopProcessing = true;
    }
    else
    {
        var errorLabel = uxBizForm.BasicForm.FieldErrorLabels[fieldBName] as LocalizedLabel;
        errorLabel.Text = "";
        errorLabel.Visible = false;
    }
}

And here is the wire up code for the event handler (Put this in the SetupControl method):

uxBizForm.OnBeforeValidate += uxBizForm_OnBeforeValidate;

And here is the event handler where you can call the validation method from above:

protected void uxBizForm_OnBeforeValidate()
{
    ShowErrorIfParentHasValueAndChildIsEmpty("FirstName", "LastName", "We don't like John and Aaron and nobody!");
}

Posted in Kentico, Programming | Tagged .NET Framework, ASP.NET, C#, Code, Kentico API Programming, Kentico BizForms, Kentico CMS | Leave a response

New Kentico Pages on Johnny Code!

By John Bubriski on October 13, 2011

I just wanted to let you know that I have 2 new pages on the site!

There is a new Kentico Resources page that contains a short list of some important resources.  Feel free to let me know about any others

Also, there is a new Kentico Tips and Tricks page that contains… you guessed it!  Tips and Tricks!  Really, it’s just a place I’m going to start putting some of the API calls and other information that is hard to find.

Posted in Kentico, Programming | Tagged Kentico API Programming, Kentico CMS | Leave a response

5 More Visual Studio Productivity Tips Every Developer Should (Probably) Know

By John Bubriski on September 12, 2011

Code Snippets

Another great tip for cranking out the code, or in case you don’t remember the syntax of certain keywords.  Just start typing the shortcut for a code snippet and hit tab twice, it’s that easy.

prop ->tab tab

For example, after you type “prop” you should see this:

Then you will see this after you press “Tab” twice:

Search Quickly

Ever notice that little text box on the menu bar?  That is for searching

ctrl + d

Delete Lines

We all mistakes!  Quickly delete code by the line using this shortcut:

ctrl + l

or the lazy-man’s shortcut would be to “cut” while having no selection on the desired line (However, that obviously overwrites your clipboard buffer):

ctrl + x

Extract an Interface

Let’s say you’re creating a shiny new ASP.NET MVC site and you want to use Inversion Of Control of Dependency Injection.  You probably need an interface for the services/providers that you will be injecting into your controllers.  If you already have those service or provider classes, you can use the built in Visual Studio refactoring features to automatically extract an interface.

Right click on your class:

Right click to extract an interface

Click “Extract Interface” to bring up the “Extract Interface” dialog:

Extract Interface Dialog

And here is the generated interface:

Extract Interface Code

Pretty nice!  Just don’t forget to mark the interface as Public if you need to.  That often bites me because I have my interfaces in a separate class library from my implementations.

Extend Your Visual Studio

OK, so I couldn’t really think of a good tip off the top of my head, so I instead am copping out and telling you about the Extension Manager which is new in Visual Studio 2010.  You probably know about this unless:

  1. You don’t have Visual Studio 2010.
  2. You have Visual Studio 2010 C# Express Edition (or Web Developer, or whatever).
  3. You didn’t look at the feature list.
  4. You live under a rock.
The extension manager has all sorts of goodies.  There is everything from free extensions, to paid version, to ones provided by Microsoft to support out-of-band releases.  Take a look at what’s there, and let me know if you find something good!  Here is what I use:
  • Indent Guides
  • JScript extensions (All the ones from Microsoft to enhance the IDE’s JavaScript support)
  • NuGet Package Manager
  • PowerCommands for Visual Studio 2010
  • Productivity Power Tools
  • VS Commands 2010
  • WoVS Quick Add Reference
I’ve used a bunch of others, but some of them didn’t stick, or I wasn’t actively using them so I removed them.  Keep in mind that any extensions you install could cause instability or performance issues.

Posted in Programming | Tagged Productivity, Quick Tip, Shortcuts, Time Saver, Visual Studio | 1 Response

« PreviousNext »

About Me

I'm a Software Engineer at Worcester Envelope in Auburn, MA. Check out the About page to learn more about me.
Follow @JohnBubriski

Pages

  • About Me
  • Achievements!
  • Contact Me
  • Developer Resources
  • Kentico Resources
    • Kentico Tips and Tricks
    • Settings Module for Kentico CMS

Tags

.NET Framework AES ASP.NET ASP.NET MVC ASP.NET Web API AspDotNetStoreFront blogging C# Code Code Camp Cryptography Decryption Elmah Encryption Entity Framework Exceptions Extension Method HTML IIS IIS6 javascript jQuery JSON Kentico API Programming Kentico BizForms Kentico CMS Kentico Event Log Kentico Module Development Learning Python 3 Microsoft PHP Productivity Quick Tip REST Shortcuts SQL SQLite Development Symmetric Encryption Time Saver Travian Add On Project URL Routing Using PyGame Visual Studio web-service wordpress

Archives

  • 2012 (15)
  • 2011 (11)
  • 2010 (19)
  • 2009 (11)

Programming Blogs

  • Stack Overflow
  • Coding Horror
  • Code: Impossible
  • Self Elected
  • Chris Jenning's Blog

Meta

  • Log in
  • Entries RSS
  • Comments RSS
  • WordPress.org

Copyright © 2012 Johnny Code.

Powered by WordPress and Hybrid.

Maintained by John Bubriski