# 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>

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.

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”

# Host create-react-app on IIS Server

Install create-react-app globally as below:

``npm i -g create-react-app``

Create the react-app in the folder of your choice on your local machine:

``create-react-app hell-world-app``

Modify the index.js file as shown below:

``````import React from "react";
import ReactDOM from "react-dom";

const element = <h1>Hello World</h1>;

//console.log(element);

ReactDOM.render(element, document.getElementById("root"));``````

Test the app on localhost:

``npm start``

Build the production optimized app:

``npm run-script build``

Copy the contents of the build folder and paste it on the Server at the location where you want to host it e.g. C:\data\testreactapp. Open IIS on the Server and add Website by right-clicking on Sites as shown below. Give it the required hostname or port to test it in browser e.g. http://helloworldapp.

The index.html file is already present at the Physical path created by the build which the IIS Server will look for as the default document.

Authentication can be Anonymous for testing purpose. However, please change as per your requirement. The AppPool by default runs with CLR 4.0 version and Integrated mode.

This approach is especially helpful when you have a back-end .Net Web API hosted on the same IIS Server to improve speed.

# Create Virtual Directory in IIS

Create the Website under IIS as shown below on port 80 so it can be accessed using http and give the appropriate hostname as required. The hostname should be available in the DNS records to access over Internet/Intranet.

Create the virtual directory as shown below. Use the default Pass-through authentication for demo purpose. You can also use Physical Path credentials on your folder if required and manage using Connect as button.

The below image shows how the Virtual Directory will look like under your website in IIS. So if you have a file saved under the Attachments folder under C:\Data\Attachments\doc1.docx, the URL to access the document will be http://mywebsite/attachments/doc1.docx. The folder can also be created on another physical drive on the same Server or can also be accessed using a UNC path.

# Update iframe without affecting browser history

You may face a scenario where you need to update the iframe element on your html page based on some JavaScript condition e.g. a calendar component may be running inside the iframe. Simply updating the “src” attribute causes the browser history to be updated and enables the forward and back browser buttons. This may cause issues in enabling/disabling holidays or weekend dates.

``document.getElementById('calfrm1').src = "popcal.asp?target=form1.duedate&weekends=Y``

The below code snippet uses contentWindow property of the iframe and replaces the location without affecting the browser history.

``````var ifr = document.getElementById("calfrm1");

ifr.contentWindow.location.replace("popcal.asp?target=form1.duedate");``````

Using replace() works only within your own domain iframes. It fails to work on remote sites.

You can remove and construct a new iframe element in the same spot to handle this. When you modify the src attribute, it creates history items as mentioned above, so make sure to set it before the append.

``````var container = iframe.parent();

iframe.remove();

container.append(iframe);``````

# Create basic ReactJS app using VS Code

We’ll be using VS Code editor to create the basic app to get started.

Install Extensions like Simple React Snippets and Prettier in VS Code to help with writing basic react snippets faster and properly formatted.

From the VS Code menu, Select Preferences-> User settings->search for Format on Save. This will help format the code on saving the file using the Prettier extension.

You’ll also need the latest stable versions of Node and npm installed.

Enter in Command Prompt on Windows or Command Line on Mac the below commands:

``npm i -g create-react-app@1.5.2``

This will install the Create React package globally.

Enter the below command to create the App in the directory of your choice:

``create-react-app react-app``

What is JSX?

JSX is a syntax extension to JavaScript. It is recommended using it with React to describe what the UI should look like, however it is not necessary. JSX produces React “elements”. JSX code is compiled by Babel, which is a modern JavaScript compiler that compiles JSX code to corresponding React code that Browsers can understand. The render method may contain JSX code.

Sample React class looks like below:

``````class MyComp {
state = {};
render() {

}
}``````

State holds the data to be displayed in the UI and render method is responsible for describing what the UI should look like i.e. a React element.
This React element is a plain Javascript object that maps to a DOM element.

How React reacts!

It is a light-weight representation of the DOM in memory which is also called Virtual DOM. This virual DOM is cheap to create. When we change the state of a component, we get a new React element. React will then compare this element and it’s children with the previous one and it figures out what is changed. Then it will update a part of the real DOM to keep it in sync with the Virtual DOM. Hence we don’t need to use the DOM API to manipulate it or attach event handlers with the DOM elements. React will automatically update the DOM to match that state.

React simply reacts to the state change and updates the DOM.

index.js is the entry point for the default created application.

registerServiceWorker.js serves assets from a local cache in the Production environment. It may change or disappear in the future.

index.html has a div element as a container with id “root” that will render all the React Components.

Run below command in the integrated terminal in VS Code, this will run the app using the light-weight development Server installed with create command above using default port 3000:

``npm run start``

You can access the app using http://localhost:3000 in a browser as below:

Delete all the existing files in the src folder. Create a new file called index.js.

Make changes to the file and save it. It will refresh in the browser which is called hot module reloading.

Modify index.js file as below:

``````import React from "react";
import ReactDOM from "react-dom";

const element = <h1>Hello World</h1>;

console.log(element);``````

This Object as shown in the browser dev tools above is part of the Virtual DOM.

So, whenever this Object changes, React will get a new React element, it will then compare this element with the previous one. It will figure what is changed. Then it will reach out to the real DOM and update it accordingly.

Remove the line console.log in the index.js file with below and save:

``ReactDOM.render(element, document.getElementById("root"));``

Run the application and inspect the element in the browser to see how the element is rendered.

# 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.

``````<configuration>