Change app pool settings iis express

You may face an Asp.Net error while running your Web Application Project in Debug mode using IIS Express:

“an asp.net setting has been detected that does not apply in integrated managed pipeline mode”

This error means that the framework expects the App Pool to be running the Managed Pipeline Mode as Classic. In Classic mode, managed application events are executed by using ISAPI.

There are other ways to suppress the error by making an entry in the Web.Config file to set the validateIntegratedModeConfiguration to false. But it is better to set the correct application pool.

Select your Project under the Solution and press F4 on your keyboard to access the Project Properties as shown below:

Also, you can enable/disable the Authentication for Anonymous and Windows modes.

Check this post on how to create Virtual Directory in IIS Express.

Deploy WebAPI with TFS Build Definition

To deploy and Publish a WebAPI or MVC application, these 2 steps should work most of the time:

  1. Visual Studio Build
  2. Publish Build Artifacts

If you right-click on your WebAPI Project, go to “Package/Publish Web” tab and check the Items to deploy drop-down, the default value selected is:
Only files needed to run this application

The below solution produces the same output as when you build the WebAPI in Visual Studio.

This is the cue, that let me find the solution to build my WebAPI Project. The WebAPI Project consists of multiple Class Libraries with Business and DAL layers as well.

Follow the steps as below:

  • Add /p:DeployOnBuild=true /p:OutDir=”$(build.artifactstagingdirectory)\” arguments in Visual Studio Build step:
  • Change “Path to Publish” of Publish Build Artifacts task to $(build.artifactstagingdirectory)\_PublishedWebsites\ProjectName:

I’ve written another post on Creating Build Definition here.

Add Strict-Transport-Security (HSTS) response header to IIS hosted site

The HTTP protocol by itself is clear text, meaning that any data that is
transmitted via HTTP can be captured and the contents viewed. To keep data private and prevent it from being intercepted, HTTP is often tunnelled through either Secure Sockets Layer (SSL) or Transport Layer Security (TLS). When either of these encryption standards are used, it is referred to as HTTPS.

HTTP Strict Transport Security (HSTS) is an optional response header that can be configured on the server to instruct the browser to only communicate via HTTPS. This will be enforced by the browser even if the user requests a HTTP resource on the same server.

Cyber-criminals will often attempt to compromise sensitive information passed from the client to the server using HTTP. This can be conducted via various Man-in-The-Middle (MiTM) attacks or through network packet captures.

Security Scanners would recommend to using adding a response header HTTP Strict-Transport-Security or HSTS when the application is using Https.

Depending on the framework being used the implementation methods will vary, however it is advised that the Strict-Transport-Security header be configured on the server. One of the options for this header is max-age, which is a representation (in milliseconds) determining the time in which the client’s browser will adhere to the header policy. The browser will memorize the HSTS policy for the period specified in max-age directive.
Within this period, if an user tries to visit the same website but types http:// or omits the scheme at all, the browser will automatically turn the insecure link to the secure one (https://) and make an HTTPS connection to the server. Depending on the environment and the application this time period could be from as low as minutes to as long as days.

Enabling includeSubDomains attribute of the element of the root domain further enhances the coverage of the HSTS policy to all its subdomains.
HSTS has a separate mechanism to preload a list of registered domains to the browser out of the box.

It is also usually recommended to redirect all http traffic to https. I’ve written another post on how to do that.

To add the HSTS Header, follow the steps below:

  1. Open IIS manager.
  2. Select your site.
  3. Open HTTP Response Headers option.
  4. Click on Add in the Actions section.
  5. In the Add Custom HTTP Response Header dialog, add the following values:
    Name: Strict-Transport-Security
    Value: max-age=31536000; includeSubDomains; preload

Or directly in web.config as below under system.webServer:

<httpProtocol>
	<customHeaders>
		<add name="Strict-Transport-Security" value="max-age=31536000; includeSubDomains; preload" />
	</customHeaders>
</httpProtocol>

Handle WebDriver browser prompt for ADFS credentials Selenium C#

While working on Automating the UI using Selenium C#, you might encounter a scenario where a website requires to be authenticated with ADFS. The browser would prompt the user to provide the AD domain credentials to authorize for accessing the website. So automating this scenario with the Selenium C# API, would require you to provide the domain credentials programatically.

The WebDriver used is Firefox with Geckodriver. Another post explains the working of the automation and initialization of the WebDriver in detail here.

Code sample is as shown below:

public static IWebDriver driverWeb;
driverWeb.Navigate().GoToUrl(link);
try
{
	driverWeb.SwitchTo().Alert().SendKeys("Username" + Keys.Tab + "Password");
	driverWeb.SwitchTo().Alert().Accept();
}
catch { }

try
{
	driverWeb.FindElement(By.Id("acknowledgeCookieId")).Click();
}
catch { }

Standard deviation using C# and Ruby

Standard Deviation definition states:

A quantity expressing by how much the members of a group differ from the mean value for the group.

The logic below calculates the Standard Deviation for the population of values. If the data is being considered a population on its own, we divide by the number of data points, say N. If the data is a sample from a larger population, we divide by one fewer than the number of data points in the sample, n-1. So you can change the formula accordingly.

Ruby code sample:

#sample = Array[1,2,3,4,5,6,7,8]
sample = Array[1,2,3,4,5]

def calc_standard_deviation(values)
    avg = values.sum {|x| x.to_f} / values.size.to_f
    Math.sqrt(values.sum {|x| (x.to_f - avg.to_f) ** 2} / values.size)
end

puts "Standard Deviation is: " + calc_standard_deviation(sample).to_s

Run the Ruby code to test as below in VS Code:

PS C:\code\Ruby test> ruby .\stdDev.rb
#Ruby Output: Standard Deviation is: 1.4142135623730951

C# code sample:

static void Main(string[] args)
{
	//double[] sample = new double[8] { 1, 2, 3, 4, 5, 6, 7, 8 };
	double[] sample = new double[5] { 1, 2, 3, 4, 5 };

	Console.WriteLine("Standard Deviation is: " + StdDev(sample));
}

public static double StdDev(IEnumerable<double> values)
{
	// Get the mean.
	double mean = values.Sum() / values.Count();

	// Get the sum of the squares of the differences
	// between the values and the mean.
	var squares_query =
					from double value in values
					select (value - mean) * (value - mean);
	double sum_of_squares = squares_query.Sum();

	return Math.Sqrt(sum_of_squares / values.Count());
}

C# Output: Standard Deviation is: 1.4142135623731

Encrypt web.config with RSA encryption

Encryption done locally on a Server using command line can be used only if the Application is hosted on the same machine. If the Application is hosted in a load-balanced environment, the encryption should be done in a way so that the private key can be imported on all the load-balanced machines.
The commands need to be run with Admin permissions on the machine.

Run the following commands in Command Prompt in the similar order with Admin permissions:

Traverse to the path as per .Net Framework-

cd C:\Windows\Microsoft.NET\Framework\v4.0.30319

Encrypting Config file without using RSA Provider

aspnet_regiis.exe -pef <section name>  <path to the config file>

-pef is the action to be performed for encryption.

e.g. aspnet_regiis.exe -pef “connectionStrings” “C:\Data\TestWebApp”

All the connection strings present in the above example will be encrypted.

Encrypting Config file using RSA Provider

Creating Key containers:

Aspnet_regiis.exe -pc “<name of Key container>” -exp

Asymmetric private keys should always be stored in a key container.

Add configProtectedData section in web.config to be encrypted:

<configProtectedData>
<providers>

<add name="MyRSAProvider"

type="System.Configuration.RsaProtectedConfigurationProvider, System.Configuration, Version=4.0.30319.0,

Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a,processorArchitecture=MSIL"

keyContainerName="MyRSAKey"

useMachineContainer="true" />

</providers>

</configProtectedData>

The above section can only be added after < configSections > else it’ll be removed automatically.

The PublicKeyToken above can be found for the System.Configuration dll using the sn utility:

sn -T "C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.Configuration.dll"

The key container name and the Provider name used above can be used in the example commands below.

Granting Access to an RSA Key Container to the AppPool:

aspnet_regiis -pa “<name of Key container>” “NT AUTHORITY\NETWORK SERVICE” -full

Encrypt command using Provider:

aspnet_regiis.exe -pef <name of config section> <path to the Config file> -prov “<name of Provider>”

Exporting the Key Container in Order to be used on Other Machines:

aspnet_regiis -px “< name of Key container >” <Path for Keys XML file> -pri

Import Key Container on another machine:

aspnet_regiis -pi “< name of Key container>” <Path for Keys XML file>

Path for keys e.g. C:\rsakeys.xml. The xml file can be copied to the same path on the other machine.

Delete the Xml File from Your Server

ASP.Net will automatically decrypt the Connection String using the grant permission given above to the AppPool and hence you need to access the Connection String in the same way as you would do normally.

To decrypt the config section locally using aspnet_regiis.exe use the below command:

Decrypt command: aspnet_regiis.exe -pdf < name of config section> <Path to the Config file>

e.g. aspnet_regiis.exe -pdf “connectionStrings” “C:\Data\TestWebApp”

Redirect website traffic to https with IIS hosting

Securing the traffic coming to your website is of utmost importance. Websites today running without an SSL certificate or without https cannot be trusted. If your application is hosted on IIS, one trick to redirect (not re-write URL) all traffic via https is to create a new Website in IIS and add httpRedirect in your web.config. HTTP Redirection is not available on the default installation of IIS 7 and later.

If your website domain is e.g. https://www.abc.com, this means the IIS binding on port 443 for your website is using host name “www.abc.com”.
The dns requires to be created pointing to the Hosting Application Server. The new Website that you create for redirection should have a port 80 binding with the same domain name.

Also, add the below configuration in your web.config file:

<configuration>
	<system.webServer>
		<httpRedirect enabled="true" destination="https://www.abc.com$Q" exactDestination="true" httpResponseStatus="Permanent" />
	</system.webServer>
</configuration>

The $Q in the destination URL will preserve the Query strings if any. The httpResponseStatus with value Permanent will redirect the traffic to the destination URL with status code 301.