Generate MachineKey using Windows PowerShell

In this post we will see how we can Generate MachineKey using Windows PowerShell from our local development machine.

Many a times when a ASP.Net application is running on production server, we get an error message stating – “Validation of viewstate MAC failed. If this application is hosted by a web farm or cluster, ensure that <machineKey> configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.” This error happens because of missing machineKey property  in the web.config file.

The <machineKey> property in web.config file configures algorithms and keys to use for encryption, decryption, and validation of forms-authentication data and view-state data, and for out-of-process session state identification.This encryption prevents tempering of session data on the server. It is present under <system.web> node in web.config file and looks like below –

<machineKey decryption="AES" decryptionKey="CFCDE8D5806F93E854A74B371BAA279A67D2729DF71A735D0AA3FEDE263C5F59" validation="HMACSHA256" validationKey="9039935908214E31A9705B96C7B2BC93FA966F5FF50748B01FC4F22B24A4149E88298E17B5419E6A054C6FB3883A2C753979A2603F1B85F078DD6383C30CC395" />

N.B: Do not use this machineKey on your production servers. Instead follow the steps mentioned below to generate a new one only for you.

We will use a PowerShell script to create this machineKey. Here’s the Powershell Script

# Generates a <machineKey> element that can be copied + pasted into a Web.config file.
function Generate-MachineKey {
  param (
    [ValidateSet("AES", "DES", "3DES")]
    [string]$decryptionAlgorithm = 'AES',
    [ValidateSet("MD5", "SHA1", "HMACSHA256", "HMACSHA384", "HMACSHA512")]
    [string]$validationAlgorithm = 'HMACSHA256'
  process {
    function BinaryToHex {
        process {
            $builder = new-object System.Text.StringBuilder
            foreach ($b in $bytes) {
              $builder = $builder.AppendFormat([System.Globalization.CultureInfo]::InvariantCulture, "{0:X2}", $b)
    switch ($decryptionAlgorithm) {
      "AES" { $decryptionObject = new-object System.Security.Cryptography.AesCryptoServiceProvider }
      "DES" { $decryptionObject = new-object System.Security.Cryptography.DESCryptoServiceProvider }
      "3DES" { $decryptionObject = new-object System.Security.Cryptography.TripleDESCryptoServiceProvider }
    $decryptionKey = BinaryToHex($decryptionObject.Key)
    switch ($validationAlgorithm) {
      "MD5" { $validationObject = new-object System.Security.Cryptography.HMACMD5 }
      "SHA1" { $validationObject = new-object System.Security.Cryptography.HMACSHA1 }
      "HMACSHA256" { $validationObject = new-object System.Security.Cryptography.HMACSHA256 }
      "HMACSHA385" { $validationObject = new-object System.Security.Cryptography.HMACSHA384 }
      "HMACSHA512" { $validationObject = new-object System.Security.Cryptography.HMACSHA512 }
    $validationKey = BinaryToHex($validationObject.Key)
      "<machineKey decryption=`"{0}`" decryptionKey=`"{1}`" validation=`"{2}`" validationKey=`"{3}`" />",
      $decryptionAlgorithm.ToUpperInvariant(), $decryptionKey,
      $validationAlgorithm.ToUpperInvariant(), $validationKey)

You can save this PowerShell script as “generateMachineKey.ps1” on your hard disk. Now open Windows Powershell and perform the following steps –

  • Go to the folder where you have stored the .ps1 filepowershell machineKey aspnet
  • Load the Scriptpowershell machineKey aspnet
  • Call the PowerShell Functionpowershell machineKey aspnet

This will give you a new machineKey. You can copy this and paste it on to your web.config file now.

Hope you like this post.

Was the post helpful? Do let me know if you’re aware of any other way of generating machineKey in comments. Cheers!


Awarded C# Corner MVP for 5th consecutive year

This has been a great start to the new year as I received an email from C# Corner this morning stating they have re-awarded me the C# Corner MVP (Most Valuable Professional) award for the 5th consecutive year. It is definitely an honor to receive the MVP award. Out of 4 million registered users on the website, the award is given to a selected set of users (around 100) and getting selected in this elite group means a lot.

mvp award 2017

A huge Thanks to the entire team of C# Corner . Thank you Mahesh Sir, Praveen Kumar, Dinesh Beniwal, entire C# Corner team for this honor.

c# mvp, mvp

Here’s the announcement –

You can see all MVPs here.

Look forward contributing to the community in this year as well 🙂

Wishing You a Happy New Year 2017

To all my readers, Wishing you and your family a very happy and prosperous New Year 2017.  May this new year bring many opportunities your way to explore every joy of life. I hope this new year fills your life with happiness and perfect health always, much more success and happiness.

I would like to thank all the visitors, readers, followers of my blog for their feedback and support throughout the year. I look forward to your participation in the coming year as well.

Thank you all again for your continuous support and feedback.

Keep in with me on Twitter at @niteshluharuka and  at my Facebook Page

Again Wish you all a very Happy New Year 2017.


Solution: Error with Entity Framework – Incorrect syntax near ‘OFFSET’


This post explains the solution to an issue that occurs with Entity Framework used against SQL Server 2008 database. The error is –

An error occurred while executing the command definition. See the inner exception for details. —> System.Data.SqlClient.SqlException: Incorrect syntax near ‘OFFSET’.

The error occurs if you are using Entity Framework EDMX file (this is to be noted that the error occurs only with Database first and not code-first approach) in your project and are taking benefit of the Take() or Skip() functions. Also, the error occurs only when the EDMX file has been generated the designer file using SQL Server 2012 but are trying to run the code against a production SQL server using 2008 or 2008 R2.

var data = db.Employees.Where(v => v.PatientID == patientID).OrderByDescending(v=>v.ID).Take(10).Skip(1).ToList();

The solution is to open the EDMX designer in a XML editor and change the value of ProviderManifestToken property from “2012” to “2008”.

Hope this small tip helps you. Cheers.

How To Install Spire.Office On your Machine

In this post we will see how to install Spire.Office software on your machine. Spire.Office for .NET is a combination of Enterprise-Level Office .NET components that includes Spire.Doc, Spire XLS, Spire.Spreadsheet, Spire.Presentation, Spire.PDF, Spire.DataExport, Spire.PDFViewer, Spire.DocViewer and Spire.BarCode. This product enables developers to open, create, modify, convert, print, View Office and PDF documents without the need of MS-Office being installed on the machine. You can download the tool from here.

  • After downloading, double-click the installer to start the installation process & Click Next.
  • Accept the EULA & Click Next.
  • If you want to integrate the Spire.Office tools directly into your Visual Studio Toolbox, you can check the “Add” checkbox else it can be left as unchecked safely. Click Next.
  • Select the Tools you want to install from the library. Also, you can change the path of the installation folder in case you have a “Program Files” in another directory as well. This is to be noted that the library takes around 725MB of the disk space. Click Next.install-spire4
  • Click the “Install” button to start the installation process.
  • Click the “Finish” button to complete the installation.

For further reading on Spire.Office components and functions, you can check here. Cheers!