Friday, 30 November 2018

Encrypt and Decrypt of Connection string in Web.config file

This article explains encryption and decryption of Connection String section of the Web.Config file using aspnet_regiis.exe Command Line Utility of the Visual Studio.


The Plain Connection Strings section in the Web.Config file
The below screenshot shows the Plain Connection Strings section in the Web.Config file before encryption.





Encrypting the Connection Strings section in Web.Config file
You need to follow the following steps for encrypting the Connection Strings section in the Web.Config file

1. Open Visual Studio Command Prompt 
You will need to open the Visual Studio Command Prompt from the Start Menu => Programs => Microsoft Visual Studio 2017 => Visual Studio Tools => Visual Studio Command Prompt.
Note: You must be log in as Administrator and right click Visual Studio Command Prompt and select Run as Administrator.
Note: In this tutorial, I am explaining the process using Microsoft Visual Studio 2010. The same process will be applicable for the other versions. The only difference will be that you need to open Visual Studio Command Prompt from the folder of the respective version of Visual Studio installed on your machine.

2. Encrypting the Connection Strings section in Web.Config using aspnet_regiis.exe tool
In order to encrypt the ConnectionString section in the Web.Config file, we will need to use the aspnet_regiis.exe tool.
Parameters
Action – It notifies the action to be performed. In order to perform Encryption, the parameter value is -pef.
Section Name – The name of the section of the Web.Config file to be encrypted. For this case, the value will be connectionStrings.
Path of the folder – Here we need to specify the path of the folder containing the Web.Config file.
Syntax
aspnet_regiis.exe -pef "connectionStrings" "<Path of the Folder containing the Web.Config file>"

Example
aspnet_regiis.exe -pef "connectionStrings" "D:\Sai\Projects\MyTestWebsite"

Note: The above command will encrypt all the Connection Strings present in the ConnectionStrings section of the Web.Config file.

Encrypted Connection Strings section in the Web.Config file
You can see Encrypted Connection Strings section in the Web.Config file after encryption.
Accessing the Encrypted Connection String value in ASP.Net Code behind
ASP.Net will automatically decrypt the Connection String when it is fetched in the code behind and hence in code behind you need to access the Connection String in the same way as you would do normally.
Decrypting the Connection Strings section in Web.Config using aspnet_regiis.exe tool 
In order to decrypt the ConnectionString section in the Web.Config file, we will need to use the same aspnet_regiis.exe tool that was used for encryption.
Parameters
Action – It notifies the action to be performed. In order to perform Decryption, the parameter value is -pdf.
Section Name – The name of the section of the Web.Config file to be decrypted. For this case the value will be connectionStrings.
Path of the folder – Here we need to specify the path of the folder containing the Web.Config file.
Syntax
aspnet_regiis.exe -pdf "connectionStrings" "<Path of the Folder containing the Web.Config file>"

Example
aspnet_regiis.exe -pdf "connectionStrings" "D:\Sai\Projects\MyTestWebsite"

Note: The above command will decrypt all the Connection Strings present in the ConnectionStrings section of the Web.Config file.

Tuesday, 24 July 2018

MVC Error Handling


4 Ways to do MVC Error Handling

Between .NET, ASP.NET, and MVC there are several potential ways to handle application errors.

  • Web.Config customErrors
  • MVC HandleErrorAttribute
  • Controller.OnException method
  • HttpApplication Application_Error event

Must Have: Global Error Page With Web.Config <customErrors>
The last thing you ever want your users to see is a “yellow screen of death” type error. If you don’t know what that is, I’m referring the standard yellow ASP.NET error screen.
For any application, I would always recommend specifying a custom error page in your Web.Config. Worst case scenario, your users will see this page if an unhandled exception occurs.
<system.web>
    <customErrors mode="On" defaultRedirect="~/ErrorHandler/Index">
        <error statusCode="404" redirect="~/ErrorHandler/NotFound"/>
    </customErrors>
<system.web/>

Use MVC HandlerErrorAttribute to Customize Responses
The HandleErrorAttribute inherits from FilterAttribute and can be applied to an entire controller or individual controller action methods.
It can only handle 500 level errors that happen within an MVC action method. It does not track exceptions that help outside of the MVC pipeline. Exceptions may occur in other HTTP modules, MVC routing, etc.
When to Use HandleErrorAttribute
Since it does not provide a way to collect all exceptions that could ever happen, it is a bad solution for a global unhandled error handler.
It works perfectly for tailoring specific error pages for a specific MVC controller or action method. Specifying an error page in your Web.Config <customErrors> works ideal for a universal error page. The HandleErrorAttribute gives you fine-grained control if you need it.

Note: HandleErrorAttribute requires customErrors to be enabled in your Web.Config.
For example, if you wanted to show a particular MVC view when a SqlException happens, you can do it with the code below:
[HandleError(ExceptionType = typeof(SqlException), View = "SqlExceptionView")]
public string GetClientInfo(string username)
{            
   return "true";
}

The problem with HandleErrorAttribute is it doesn’t provide a way to log the exception!

Use MVC Controller OnException to Customize Responses
OnException is similar to HandleErrorAttribute but provides more flexibility. It works with all HTTP status codes, and not just 500 level responses. It also gives you the ability to log the errors!
public class UserMvcController : Controller
{
   protected override void OnException(ExceptionContext filterContext)
   {
      filterContext.ExceptionHandled = true;
                 //Log the error!!
      _Logger.Error(filterContext.Exception);
      //Redirect or return a view, but not both.
      filterContext.Result = RedirectToAction("Index", "ErrorHandler");
      // OR 
      filterContext.Result = new ViewResult
      {
         ViewName = "~/Views/ErrorHandler/Index.cshtml"
      };
   }
}

When to Use OnException for MVC Error Handling
If you want a way to present your users custom MVC views or custom log exceptions, OnException is a good solution for you. It provides more flexibility than HandleErrorAttribute and does not require customErrors to be enabled in your Web.Config file.
Note: OnException gets called for all HTTP status codes. So be careful how you handle simple issues like a 404 caused by a bad URL.
public class BaseController : Controller

    {

        protected override void OnException(ExceptionContext filterContext)

        {

            filterContext.ExceptionHandled = true;

            ViewData["Data"] = filterContext.Exception.Message.ToString();

            filterContext.Result = new ViewResult { ViewData = this.ViewData, ViewName = "Error" };

            base.OnException(filterContext);

        }

    }
Use HttpApplication Application_Error as Global Exception Handler
So far we have covered three different ways to customize the response that your users see if an exception occurs. Only within OnException can you potentially log exceptions.
To log all unhandled exceptions that may occur within your application, you should implement basic error logging code as shown below.
public class MvcApplication : System.Web.HttpApplication
{
   protected void Application_Start()
   {
      AreaRegistration.RegisterAllAreas();
      FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
      RouteConfig.RegisterRoutes(RouteTable.Routes);
      BundleConfig.RegisterBundles(BundleTable.Bundles);
   }
   protected void Application_Error()
   {
      var ex = Server.GetLastError();
      //log the error!
      _Logger.Error(ex);
   }
}
When to Use Application_Error
Always! HttpApplication’s Error even provides the best mechanism to collect and log all unhandled application errors.




Thursday, 12 July 2018

Exporting & Importing Websites and AppPoll configuration between multiple IIS instances


Export the all Application Pools
The first thing you have to do is to export/import the application pools, since they will most likely be used in your web sites and you won’t be able to import those without having their relevant app pool into place. Here’s the command-line: 
%windir%\system32\inetsrv\appcmd list apppool /config /xml > c:\apppools.xml
This command will export all your application pools – including the default ones. You’ll need to remove those, as they will most likely be in your target IIS instance with the same name and therefore they will raise a duplicate name error, blocking the whole import. In order to avoid that, open the newly created apppools.xml  file and remove the default ones such as:
·        DefaultAppPool

·        Classic .NET AppPool

·        .NET v2.0

·        .NET v2.0 Classic

·        .NET v4.5

·        .NET v4.5 Classic

Import the Application Pools
Copy the apppools.xml  file to your target webserver and run the following command:
1
%windir%\system32\inetsrv\appcmd add apppool /in < c:\apppools.xml
Each and every Application Pool mentioned in the xml file will be created on your target IIS instance.

Export the all Websites
Open up again a command-line console on your source webserver and type in the following command:
%windir%\system32\inetsrv\appcmd list site /config /xml > c:\websites.xml
Again, you’ll have to remove the default websites –  you’ll most likely have only one default website, which is Default Website – as well as any other website you don’t want to copy and/or is already existing on the target IIS instance, otherwise the import command won’t work.

Import the Websites
Just like you did with the App Pools file, copy the websites.xml  file to your target webserver and run the following command: 
%windir%\system32\inetsrv\appcmd add site /in < c:\websites.xml

Export/Import a single App Pool or Website
These commands can also be used to export/import a single application pool or a specific website. You just have to add their identifying name to the command-line, such as:
Export a specific Application Pool
%windir%\system32\inetsrv\appcmd list apppool “CustomAppPool” /config /xml > c:\customapppool.xml
Import a specific Application Pool
%windir%\system32\inetsrv\appcmd add apppool /in < c:\customapppool.xml

Export a specific Website
%windir%\system32\inetsrv\appcmd list site “CustomWebsite” /config /xml > c:\customwebsite.xml
Import a specific Website
%windir%\system32\inetsrv\appcmd add site /in < c:\customwebsite.xml

2 Using Export configuration in IIS. 
I'd say export your server config in IIS manager:
In IIS manager, click the Server node
Go to Shared Configuration under "Management"
Click “Export Configuration”. (You can use a password if you are sending them across the internet, if you are just gonna move them via a USB key then don't sweat it.)
Move these files to your new server
administration.config
applicationHost.config
configEncKey.key 
On the new server, go back to the “Shared Configuration” section and check “Enable shared configuration.” Enter the location in physical path to these files and apply them.
 It should prompt for the encryption password (if you set it) and reset IIS.

http error 403.14 – forbidden: the web server is configured to not list the contents of this directory. Mvc


When we publish MVC application to IIS sometimes we got this error.
Following are the possible causes/ fixes for this 
·        Make sure the Application pool targets correct version of .NET framework (i.e .NET Framework v4.0.30319 for .NET 4 and 4.5)

·        Make sure the Pipeline mode of IIS Application pool is "Integrated"

·        Check UrlRoutingModule-4.0 is added in the modules of that website, if not add following into Web.config module section.
<add name="UrlRoutingModule-4.0"
           type="System.Web.Routing.UrlRoutingModule"
            preCondition="" />
<remove name="FormsAuthenticationModule" />

·        Make sure you have following element added in system.webServer section of website's web.config

<system.webServer>
<modules runAllManagedModulesForAllRequests="true"></modules> 
</system.webServer>




Monday, 8 January 2018

Virtual Machine

VM Creation:

Create VM-> choose image
Step1: Provide Basic details
Step2: Choose a size
Step3: provide settings

Step4: Create

Add Data Disks

We can add extra data disks to Virtual machines.
Create VHD in on-premise
·        Open Disk management->Create VHDàprovide VHD name path.
·        Click on Disks->Initialize disk
·        Click on unallocated sizeàRight click select New Simple Volume.
·        Click on disk->detach VHD
Upload VHD to blobàGo to VM->disks->add disk-> add blob url.
Capture VM image
It will use for create VM image multiple times based on single VM Image(both OS and Data).
Login VMà Open sysprep:  C:\Windows\System32\Sysprep sysprep.exe
Select generalize checkbox
Click Capture in Azure VM
Enter Name in Create image section
Note: Once you create generalize image, then VM is not useful, we need to delete it.



Backup
Goto->VM ->Backup->Provide Recovery service vault name and policy->create.
Recovery
Goto Recovery Vault ->Click on backup items->Virtual machines->Click on VM NameàRestore VM
Load balancer
It is a VM container and it manages the load between VM’s.
Azure Load Balancer delivers high availability and network performance to your applications. It is a Layer 4 (TCP, UDP) load balancer that distributes incoming traffic among healthy instances of services defined in a load-balanced set.
  Load balance incoming Internet traffic to virtual machines. This configuration is known as Internet-facing load balancing.
  Load balance traffic between virtual machines in a virtual network, between virtual machines in cloud services, or between on-premises computers and virtual machines in a cross-premises virtual network. This configuration is known as internal load balancing.
  Forward external traffic to a specific virtual machine.
 Availability set overview
An Availability Set is a logical grouping capability that you can use in Azure to ensure that the VM resources you place within it are isolated from each other when they are deployed within an Azure datacenter. Azure ensures that the VMs you place within an Availability Set run across multiple physical servers, compute racks, storage units, and network switches.
If a hardware or Azure software failure occurs, only a subset of your VMs are impacted, and your overall application stays up and continues to be available to your customers. Availability Sets are an essential capability when you want to build reliable cloud solutions.

Fault Domain :
  A fault domain is a physical point of failure. Think of a computer (or a rack of servers) that is physically plugged in to a power outlet in one location (Unplanned update). If a power outage happens, that computer goes offline.
When creating a new virtual machine instance, Azure will automatically place that instance in a new Fault Domain. This ensures that if you have 2 instances of a service, they cannot be in the same fault domain.

Update Domain:
  Whereas Fault Domains are a physical separation, Upgrade Domains are a logical separation. Upgrade domains exist so when Microsoft rolls out a new software feature or bug fix (Planned update), each upgrade domain is upgraded at different times. This ensures that if you have at least 2 instances, your service will never go down as the result of an upgrade.
  Azure services can have up to 5 upgrade domains by default (max of 20). When you create a new service instance, Azure automatically places it in the next upgrade domain. If you have more than 5 instances, 7 for example, upgrade domains 0-1 will have 2 instances and upgrade domains 2-4 will have 1 instance.
 Load balancer setup process:
   You must add Availability set for all Virtual machines that you are going to add in Load balancer.
   Availability set only enable at the time of VM creation.
   All Availability set VM should use same Virtual Network.


IOPS and DiskPool 

SQLIO: https://www.microsoft.com/en-us/download/details.aspx?id=20163
Download and install to test the IOPS of disk.
Diskspd.exe -b8K -d1 -r -w50 -c50M c:\io.dat
d- number of seconds.
b- IO block size in bytes
r- Read operations
w- write operations
c-create file
IOPS- Input ouput operations
Create 4 or 5 data disks based on your requirement
Server Manager->File and Storage services->Storage pool->Select all disks and right click, choose new storage pool.
Under Virtual Disk->new virtual disk ->etc
It will create disk pool and it will have more IOPS than normal disk.




Azure VNET

VNET- Customer managed secure, isolated virtual network.
·        Services and VMs that are part of VNET can access each other.
·        Each VNET can have as many subnets
·        All services deployed within a VNET can access internet 
Typed of VNET's
·        Cloud only VNET
o   When a VNET created in Azure
o   VMs and services access through endpoints.
o   No configuration of VPN device required.
·        Cross premise Virtual network(Hybrid network)
o   Connection of On-Premise network with the Cloud VNET through site to site tunnel.
o   Requires a VPN device.
VNet Address space and Subnet
o   Specify Topology during VNET creation: address space and subnet
o   Private address space
§  This is the range VMs and services can use
§  Non Routable(these can’t access by public network)
§  Specified in CIDR Notation (classless inter domain routing)
·        10.0.0.0/8: 10.0.0.0 to 10.255.255.255
·        172.16.0.0/12: 172.16.0.0 to 172.31.255.255
·        192.168.0.0/16:192.168.0.0 to 192.168.255.255
o   Subnet
§  Break up the network with more manageable sections.
§  All services can access across subnets.
§  Network security groups can be utilized to implement rules .
VNet Creation and NSG.
VNET Creation:

Subnet:


 
Inbound/outbound rules:



VIP- Public IP address.
DIP- Private IP address.
Click on subnets and add NSG, users to your subnet. NSG and users should be created before assigning to subnet.
NSG creation and add security rules:
·        Go to NSG->Provide name, same resource group as VNET->Same location->Create
·        Add inbound , outbound rules that you want to assign to subnet.
You can use firewall rules to block or allow specific traffic passing through from one side to the other. 
·        Inbound rules (WAN to LAN) restrict access by outsiders to private resources, selectively allowing only specific outside users to access specific resources. 
·        Outbound rules (LAN to WAN) determine what outside resources local users can have access to.
If the Windows Firewall is turned off then it will have no effect, and the Inbound and Outbound rules will mean nothing.
·        You can associate subnet in NSG.  

Some Important 18 protocols and ports in Network.

TCP
Transport control Protocol
(Connection Oriented)
UDP
User datagram protocol
(Connection less)

FTP-File Transfer protocol
20 – File Transfer
,21 –Connection establish
SNMP-Simple Network management  protocol
161,162
  TFTP- Trivial File Transfer Protocol
69
NTP- Network Time Protocol
123
SFTP- Secure File Transfer protocol
22
SIP- Session Initiation Protocol
5060, 5061

SSH – Secure shell
22
RTSP – Real Time Streaming protocol
554
                                                           LDAP- Lightweight Directory Access protocol
                                                          389
                                                          RDP- Remote desktop protocol
                                                          3389
TELNET
23

SMTP- Simple Mail transfer protocol
25
IF SSL
465

IMAP4 – Internet message access protocol
143
If SSL
993

POP3 -  Post office protocol
110
If SSL
995

HTTP- Hyper text transfer protocol
80

HTTPS- Hyper text transfer protocol secure
443


Hybrid network connectivity

·        Connecting On premise network to the Azure Virtual network
·        Connecting from Azure Vnet to Vnet
Following options available in cross premise connectivity.
·        Point to Site VPN
·        Site to Site VPN
·        Express route
·        VNet to VNet
·        Multi site VPN
VPN Gateways:
Point to site and site to site both require setting up a VPN gateway.
2 types of VPN gateways:
·        Static routing VPN Gateway-Policy based. Encrypt and encapsulate a subset of traffic flowing through an interface according to custom defined policy. The policy dictates the interesting traffic.
·        Dynamic routing VPN Gateway-Route based VPN. A tunnel interface is employed. Any traffic going to tunnel interface is placed into the VPN.
Multi-site VPN, VNet to Vnet and Point to site require dynamice routing VPN gateways.
Point to site VPN.
Providing organization employees/users to organization network access from anywhere.
·        individual client machines connect to Azure VNet using traditional VPN client
·        Utilizes SSTP(secure socket tunnel protocol).
·        Users certificate authentication between client computers and Vnets.
·        Individually configured: VPN client installed on client computer.
Sequence of steps to establish Point to Site VPN
1.      Create a VNet in Azure.
2.      Create a Network gateway and Virtual network gateway from management portal or Powershell.
a.      Go to VNet subnet section, create network gateway subnet. It will create range Ip address that be used by VPN clients.
b.      Goto Virtual network Gateway and provide information.
3.      Create self-signed root certificate.
a.      We need a Makecert.exe to create root certificate, enter dir/s makcert.exe in cmd prompt to find out makecert exist in machine, if not found download it from here: Makecert.
b.      Before going to run makecert command, we need to do these: Open Root console(type mmc in Win+R)-> File->add/Remove snap in->Certificate->add->my user account->finish.
c.      Cd to makecert location and run ” makecert -sky exchange -r -n "CN=VnetP2SRootCer" -pe -a sha1 -len 2048 -ss My .\VnetP2SRootCertOrg.cer “.
d.      You should see Root certificate in mmc console personal folder.
4.      Create self-signed client cert from root cert.
a.      Create client cert using root cert, run this command “makecert -n "CN=VnetP2SClient" -pe -sky exchange -m 96 -ss My -in "VnetP2SRootCer" -is My -a sha1”
b.      You should see client certificate in mmc console personal folder.
5.      Export root and client cert from certificate store.
a.      Right Click on root cert ->all tasks->export ->No, Don’t export private key->Check Base 64 format->save.
b.      Right Click on client cert ->all tasks->export ->Yes,  export private key->provide password >save.
6.      Upload Root authentication cert to azure.
a.      Open exported Root Cert in Edit plus/Visual studio, make cert text in one line and copy.
b.      Goto portal->Virtual network gateway->Point to site configuration->provide not overlap IP with Vnet->provide copied root cert data and save it.
7.      Install the client certificate on the client machine to authenticate to the VNET.
a.      Install the Client cert in user machine by clicking on client cert->Enter password->Next(everything should be default)-> Save.
b.      You should see client certificate in mmc console trusted certifcate folder.
8.      Install client VPN package-Download from azure.
a.      Download VPN package from Virtual network gateway and install it on machine.
b.      You can see VnetP2SClient option in wifi network section in windows.
9.      Establish VPN and verify connectivity.
a.      Open Network and connect to Vnet.
b.      You can access VNET resources.