Saturday, March 29, 2014

C# OOPs Concepts



Encapsulation: Encapsulation is a process of binding the data members and member functions into a single unit.

Example for encapsulation is class. A class can contain data structures and methods.
Consider the following class

public class Aperture
{
public Aperture ()
{
}
protected double height;
protected double width;
protected double thickness;
public double get volume()
{
Double volume=height * width * thickness;
if (volume<0 span="">
return 0;
return volume;
}
}

In this example we encapsulate some data such as height, width, thickness and method Get Volume. Other methods or objects can interact with this object through methods that have public access modifier

Abstraction: Abstraction is a process of hiding the implementation details and displaying the essential features.

Example1: A Laptop consists of many things such as processor, motherboard, RAM, keyboard, LCD screen, wireless antenna, web camera, usb ports, battery, speakers etc. To use it, you don't need to know how internally LCD screens, keyboard, web camera, battery, wireless antenna, speaker’s works.  You just need to know how to operate the laptop by switching it on. Think about if you would have to call to the engineer who knows all internal details of the laptop before operating it. This would have highly expensive as well as not easy to use everywhere by everyone.

So here the Laptop is an object that is designed to hide its complexity.
How to abstract: - By using Access Specifiers

.Net has five access Specifiers

Public - Accessible outside the class through object reference.
Private - Accessible inside the class only through member functions.
Protected -- Just like private but Accessible in derived classes also through member 
functions.
Internal -- Visible inside the assembly. Accessible through objects.
Protected Internal -- Visible inside the assembly through objects and in derived classes outside the assembly through member functions.

In object-oriented software, complexity is managed by using abstraction.

Abstraction is a process that involves identifying the critical behavior of an object and eliminating irrelevant and complex details.

Inheritance:Inheritance is a process of deriving the new class from already existing class
C# is a complete object oriented programming language. Inheritance is one of the primary concepts of object-oriented programming. It allows you to reuse existing code. Through effective use of inheritance, you can save lot of time in your programming and also reduce errors, which in turn will increase the quality of work and productivity. A simple example to understand inheritance in C#.


Using System;
Public class BaseClass
{
    Public BaseClass ()
    {
        Console.WriteLine ("Base Class Constructor executed");
    }
                                 
    Public void Write ()
    {
        Console.WriteLine ("Write method in Base Class executed");
    }
}
                                 
Public class ChildClass: BaseClass
{
                                 
    Public ChildClass ()
    {
        Console.WriteLine("Child Class Constructor executed");
    }
   
    Public static void Main ()
    {
        ChildClass CC = new ChildClass ();
        CC.Write ();
    }
}

In the Main () method in ChildClass we create an instance of childclass. Then we call the write () method. If you observe the ChildClass does not have a write() method in it. This write () method has been inherited from the parent BaseClass.

The output of the above program is

Output:
  Base Class Constructor executed
  Child Class Constructor executed
  Write method in Base Class executed

this output proves that when we create an instance of a child class, the base class constructor will automatically be called before the child class constructor. So in general Base classes are automatically instantiated before derived classes.

In C# the syntax for specifying BaseClass and ChildClass relationship is shown below. The base class is specified by adding a colon, ":", after the derived class identifier and then specifying the base class name.

Syntax:  class ChildClassName: BaseClass
              {
                   //Body
              }

C# supports single class inheritance only. What this means is, your class can inherit from only one base class at a time. In the code snippet below, class C is trying to inherit from Class A and B at the same time. This is not allowed in C#. This will lead to a compile time 
error: Class 'C' cannot have multiple base classes: 'A' and 'B'.

public class A
{
}
public class B
{
}
public class C : A, B
{
}

In C# Multi-Level inheritance is possible. Code snippet below demonstrates mlti-level inheritance. Class B is derived from Class A. Class C is derived from Class B. So class C, will have access to all members present in both Class A and Class B. As a result of multi-level inheritance Class has access to A_Method(),B_Method() and C_Method().

Note: Classes can inherit from multiple interfaces at the same time. Interview Question: How can you implement multiple inheritance in C#? Ans : Using Interfaces.

Using System;
Public class A
{
    Public void A_Method ()
    {
        Console.WriteLine ("Class A Method Called");
    }
}
Public class B: A
{
    Public void B_Method ()
    {
        Console.WriteLine ("Class A Method Called");
    }
}
Public class C: B
{
    Public void C_Method ()
    {
        Console.WriteLine ("Class A Method Called");
    }
                   
    Public static void Main ()
    {
        C C1 = new C ();
        C1.A_Method ();
        C1.B_Method ();
        C1.C_Method ();
    }
}
When you derive a class from a base class, the derived class will inherit all members of the base class except constructors. In the code snippet below class B will inherit both M1 and M2 from Class A, but you cannot access M2 because of the private access modifier. Class members declared with a private access modifier can be accessed only with in the class.

Common Interview Question: Are private class members inherited to the derived class?
Ans: Yes, the private members are also inherited in the derived class but we will not be able to access them. Trying to access a private base class member in the derived class will report a compile time error.

Using System;
Public class A
{
Public void M1 ()
{
}
Private void M2 ()
{
}
}

Public class B: A
{
Public static void Main ()
{
B B1 = new B ();
B1.M1 ();
//Error, Cannot access private member M2
//B1.M2 ();
}
}

What is wrong with multiple inheritance?

The main problem with multiple inheritance is that there can be times when the results of using multiple inheritance will be uncertain. The best example of this is the classic problem known as the diamond problem where a class inherits from 2 different classes, but those 2 different classes inherit from the same class, like in the graphic below (where class D derives from both classes B and C, and classes B and C both derive from class A:

And here is what the code for that example would look like:
class A {
           protected: 
               bool testing;
};
 
class B: public A { };
 
class C: public A { };
 
class D: public B, public C  {
  public:
    void setTesting ( bool xTesting)  {
            testing = xTesting; // this is uncertain
           }
};
 
In the code above we have the testing data member which is defined by class A. But, the problem is that class D derives from both classes B and C, which both derive from class A. This means that there are essentially 2 copies of the testing flag that are available because there are 2 instances of A in D’s class hierarchy. So, this creates a problem because which copy of the testing flag will be set? And the compiler will give an error and say that the reference to testing in class D is ambiguous.
But, there are some fixes to this problem. One fix is to make it very clear which classe’s version of testing is going to be set:
B :: testing = xTesting;  // use B's version of testing
The other fix for this problem is to declare B and C as virtual base classes. This allows only one copy of A to be created for class D, and that clears up any ambiguities.
Different languages actually have different expectations for how multiple inheritance works. For example, how conflicts are resolved and whether duplicate bases are merged or redundant. Before microsoft can implement multiple inheritance  in the CLR, microsoft have to do a survey of all the languages, figure out the common concepts, and decide how to express them in a language-neutral manner. microsoft could also have to decide whether multiple inheritance belongs in the CLS and what this would mean for languages that don't want this concept (presumably VB.NET, for example).
Polymorphism: Polymorphism means many forms (ability to take more than one form).
In polymorphism we will declare methods with same name and different parameters in same class or methods with same name and same parameters in different classes. Polymorphism has ability to provide different implementation of methods that are implemented with same name.

In Polymorphism we have 2 different types those are
     -      Compile Time Polymorphism (Called as Early Binding or Overloading or static binding)
     -      Run Time Polymorphism (Called as Late Binding or Overriding or dynamic binding)

Compile Time Polymorphism or Early Binding

In Compile time polymorphism, the decision is made at compile time. It means we will declare methods with same name but different signatures because of this we will perform different tasks with same method name. This compile time polymorphism also called as early binding or method /operator /constructor overloading.

Overloading is mainly three types i.e.
1.       Method Overloading: Method Overloading or compile time polymorphism means same method names with different signatures (different parameters)
2.       Operator Overloading
3.       Constructor overloading
                                                 
Example:
public class Class1
{
public void NumbersAdd(int a, int b)
{
Console.WriteLine(a + b);
}
public void NumbersAdd(int a, int b, int c)
{
Console.WriteLine(a + b + c);
}
}

In above class we have two methods with same name but having different input parameters this is called method overloading or compile time polymorphism or early binding. 

Run Time Polymorphism or Late Binding

Run time polymorphism also called as late binding or method overriding or dynamic polymorphism. Run time polymorphism or method overriding means same method names with same signatures.

In this run time polymorphism or method overriding we can override a method in base class by creating similar function in derived class this can be achieved by using inheritance principle and using “virtual & override” keywords.

In base class if we declare methods with virtual keyword then only we can override those methods in derived class using override keyword





Example:

//Base Class
public class Bclass
{
public virtual void Sample1()
{
Console.WriteLine("Base Class");
}
}
// Derived Class
public class DClass : Bclass
{
public override void Sample1()
{
Console.WriteLine("Derived Class");
}
}
// Using base and derived class
class Program
{
static void Main(string[] args)
{
// calling the overriden method
DClass objDc = new DClass();
objDc.Sample1();
// calling the base class method
Bclass objBc = new DClass();
objBc.Sample1();
}
}
Virtual Method: Virtual method is a method whose behavior can be overridden in derived class. Virtual method allows declare a method in base class that can be redefined in each derived class.
  • By default, methods are non-virtual. You cannot override a non-virtual method.
  • You cannot use the virtual modifier with the static, abstract, private or override modifiers.
  • Virtual properties behave like abstract methods, except for the differences in declaration and invocation syntax.
  • A virtual inherited property can be overridden in a derived class by including a property declaration that uses the override modifier.
·         If a Virtual function derived in derived class without mentioning “override” keyword then it will work as in case of new keyword.

Sealed Keyword: Sealed keyword can be used to stop method overriding in a derived classes.  Sealed function cannot be hidden by new keyword.



Friday, March 28, 2014

SQL -Server - In case of multiple transaction in a procedure, what will happen if error will occur after inner transaction commit statement?

Committing inner transactions is ignored by the SQL Server Database Engine. The transaction is either committed or rolled back based on the action taken at the end of the outermost transaction. If the outer transaction is committed, the inner nested transactions are also committed. If the outer transaction is rolled back, then all inner transactions are also rolled back, regardless of whether or not the inner transactions were individually committed.

Thursday, September 19, 2013

Dotnet Interview Question

1. What is Property?
A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.

Example:

class TimePeriod
{
    private double seconds;

    public double Hours
    {
        get { return seconds / 3600; }
        set { seconds = value * 3600; }
    }
}
 
2. What is the difference between abstraction and encapsulation?
Abstraction:
Abstraction lets you focus on what the object does instead of how it does it
That means we use the object without knowing the source code of the class.

Encapsulation:
Encapsulation means hiding the internal details or mechanics of how an object does something.
Encapsulation is warping data into single unit.


3. What is the difference between classes and structs in Microsoft.Net? 
  • A struct is a value type, while a class is a reference type.
  • When we instantiate a class, memory will be allocated on the heap, But when struct gets initiated, it gets memory on the stack.
  • Classes can have explicit parameter less constructors. But structs cannot have this.
  • Classes support inheritance. But there is no inheritance for structs. A struct cannot inherit from another struct or class, and it cannot be the base of a class. Like classes, structures can implement interfaces.
  • We can assign null variable to class. But we cannot assign null to a struct variable, since structs are value type.
  • We can declare a destructor in class but can not in struct.

4. In which event are the controls fully loaded?
Page load event guarantees that all controls are fully loaded. Controls are also accessed in Page_Init events but you will see that view state is not fully loaded during this event.


5. How can we identify that the Page is Post Back?
Page object has an "IsPostBack" property, which can be checked to know that is the page posted back.

6. What is Query String? What are its advantages and limitations?

The Query String helps in sending the page information to the server.

The Query String has the following advantages:
  • Every browser works with Query Strings.
  • It does not require server resources and so does not exert any kind of burden on the server.
The following are the limitations of Query String:
  • Information must be within the limit because URL does not support many characters.
  • Information is clearly visible to the user, which leads to security threats.
7. What is View State?
The View State is a feature used by ASP.NET web page to store the value of a page and its controls just before posting the page. Once the page is posted, the first task by the page processing is to restore the View State to get the values of the controls.

8. How can you register a custom server control to a web page?
You can register a custom server control to a Web page using the @Register directive.
OR
You can also add in web config like below
<pages>
      <controls>
        <add assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="ajax"></add></controls></pages>

9.  What are the types of comment in C# with examples?
Single line
Eg:
[csharp]   //This is a Single line comment[/csharp]
ii. Multiple line (/* */)
Eg:
[csharp] /*This is a multiple line comment
We are in line 2
Last line of comment*/[/csharp]
iii. XML Comments (///).
Eg:
[csharp]/// summary;
///  Set error message for multilingual language.
/// summary[/csharp]
10. Can multiple catch blocks be executed?
No, Multiple catch blocks can’t be executed. Once the proper catch code executed, the control is transferred to the finally block and then the code that follows the finally block gets executed.

11. Can “this” be used within a static method?  
We can’t use ‘This’ in a static method because we can only use static variables/methods in a static method.

12. What is difference between constants and read-only?
Constant and ReadOnly keyword are used to make a field constant which value cannot be modified.

Constant
Constant fields or local variables must be assigned a value at the time of declaration and after that they cannot be modified. By default constant are static, hence you cannot define a constant type as static.
public const int X = 10;
A const field is a compile-time constant. A constant field or local variable can be initialized with a constant expression which must be fully evaluated at compile time.
void Calculate(int Z)
{
  const int X = 10, X1 = 50;
  const int Y = X + X1; //no error, since its evaluated a compile time
  const int Y1 = X + Z; //gives error, since its evaluated at run time
}
You can apply const keyword to built-in value types (byte, short, int, long, char, float, double, decimal, bool), enum, a string literal, or a reference type which can be assigned with a value null.
const MyClass obj1 = null;//no error, since its evaluated a compile time
const MyClass obj2 = new MyClass();//gives error, since its evaluated at run time
Constants can be marked as public, private, protected, internal, or protected internal access modifiers.
Use the const modifier when you sure that the value a field or local variable would not be changed.

ReadOnly
A readonly field can be initialized either at the time of declaration or with in the constructor of same class. Therefore, readonly fields can be used for run-time constants.
class MyClass {
  readonly int X = 10; // initialized at the time of declaration
  readonly int X1;

  public MyClass(int x1)
  {
    X1 = x1; // initialized at run time
  }
}
Explicitly, you can specify a readonly field as static since, like constant by default it is not static. Readonly keyword can be apply to value type and reference type (which initialized by using the new keyword) both. Also, delegate and event could not be readonly.
Use the readonly modifier when you want to make a field constant at run time.


Tuesday, August 13, 2013

AMAZON - Create SSL Certificate for a Load Balancer

AMAZON - Create SSL Certificate for a Load Balancer
This section describes the process of generating a server certificate and preparing it to use with AWS products through IAM. To create a certificate, you perform a series of tasks as described by the following topics. Note: If you want to create user signing certificate that you can use to sign SOAP requests in EC2, see Creating and Uploading a User Signing Certificate Topics
  • Install and Configure OpenSSL
  • Create a Private Key
  • Create a Certificate Signing Request
  • Submit the CSR to a Certificate Authority

Install and Configure OpenSSL
Creating and uploading a certificate requires a tool that supports the SSL and TLS protocols. OpenSSL is an open-source tool that provides the basic cryptographic functions necessary to create an RSA token and sign it with your private key. If you don't already have OpenSSL installed, follow the instructions in this section.
  • To install OpenSSL on Windows
    1. Go to OpenSSL: Binary Distributions (http://www.openssl.org/related/binaries.html).
    2. Click OpenSSL for Windows.
  • A new page displays with links to the Windows downloads.
    1. If it is not already installed on your system, select the Microsoft Visual C++ 2008 Redistributables link appropriate for your environment and click Download. Follow the instructions provided by the Microsoft Visual C++ 2008 Redistributable Setup Wizard.
    2. After you have installed the Microsoft Visual C++ 2008 Redistributables, select the appropriate version of the OpenSSL binaries for your environment and save the file locally. The OpenSSL Setup Wizard launches.
    3. Follow the instructions described in the OpenSSL Setup Wizard. Save the OpenSSL binaries to a folder in your working directory.
  • Before you use OpenSSL commands, you must configure the operating system so that it has information about the location of the OpenSSL install point.
  • To configure OpenSSL on Windows
    1. Open a Command Prompt window.
    2. Set the OpenSSL_HOME variable to the location of the OpenSSL installation:
      set Path=OpenSSL_HOME\bin;%Path%
    3. Set the path to the OpenSSL installation:
      set Path=OpenSSL_HOME\bin;%Path%
Note: Any changes you make to Windows environment variables in a Command Prompt window are valid only for the current command-line session. You can make persistent changes to the environment variables by setting them as system properties. The exact procedures depend on what version of Windows you're using. (For example, in Windows 7, open Control Panel > System and Security > System. Then choose Advanced system settings > Advanced tab > Environment Variables.) For more information, see the Windows documentation.

Create a Private Key
You need a unique private key to create your Certificate Signing Request (CSR).
At the command line, use the openssl genrsa command and the following syntax:
openssl genrsa 2048 > private-key.pem For private-key.pem
specify your own file name. In the example, 2048 represents 2048-bit encryption. AWS also supports 1024-bit and 4096-bit encryption. We recommend you create an RSA key that is 2048 bits.

Create a Certificate Signing Request
The next step is to create a Certificate Signing Request (CSR). This is a file that you can send to a certificate authority (CA) to apply for a server certificate.
• Use the openssl req command to create a CSR and the following syntax:
openssl req -new -key private-key.pem -out csr.pem
The output will look similar to the following example:

You are about to be asked to enter information that will be incorporated into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank.
For some fields there will be a default value.
If you enter '.', the field will be left blank.

The following table can help you create your certificate request.
Name Description Example
Country Name The two-letter ISO abbreviation for your country. US = United States
State or Province The name of the state or province where your organization is located. This name cannot be abbreviated. Washington
Locality Name The name of the city where your organization is located. Seattle
Organization Name The full legal name of your organization. Do not abbreviate your organization name. Example Corp.
Organizational Unit Optional, for additional organization information. Marketing
Common Name The fully qualified domain name for your CNAME. You will receive a certificate name check warning if this is not an exact match. www.yourdomain.com
Email address The server administrator's email address someone@yourdomain.com

Note:The Common Name field is often misunderstood and is completed incorrectly. The common name is typically your host plus domain name. It will look like "www.company.com" or "company.com". You need to create a CSR using your correct common name.

Submit the CSR to a Certificate Authority
Your CSR contains information identifying you. To apply for a server certificate, send your CSR to a certificate authority (CA). The CA might require other credentials or proofs of identity.
If the request for a certificate is successful, the CA returns an identity certificate (and possibly a chain certificate) that is digitally signed.
AWS does not recommend a specific CA. For a partial listing of available CAs, see Third-Party Certificate Authorities.

Steps to update SSL Certificate on Amazon Elastic Load Balancer

  1. Sign in to the AWS Management Console and open the Amazon EC2 console at https://console.aws.amazon.com/ec2/.
  2. On the Amazon EC2 Getting Started page, in the EC2 Dashboard pane, under NETWORK & SECURITY, click Load Balancers.
  3. On the Load Balancers page, select your load balancer.
  4. The bottom pane displays the details of your load balancer.
  5. Click the Listeners tab.
  6. Click Change in the SSL Certificate column of the certificate you want to update.
  7. On the Configure SSL Certificate page, select Choose from your existing SSL Certificates to use previously uploaded SSL certificate and select the certificate from the drop-down box.
  8. Or, select Upload a new SSL Certificate if you have a SSL certificate and want to uploaded it.
    Before you upload, ensure that your certificate meets the following citeria:
    • Certificates must follow the X.509 PEM format.
    • The current date must be between the certificate’s start and end date.
    • Public and private certificate files must contain only a single certificate.
    • The private key must match the public key that is in the digital server certificate.
    • The private key must be an RSA private key in PEM format, where the PEM header is BEGIN RSA PRIVATE KEY and the footer is END RSA PRIVATE KEY.
    • The private key cannot be encrypted with a password.
    • A certificate chain starts with the immediate signing certificate and is then followed by any intermediaries in order. Intermediaries that are not involved in the trust path must not be included. The trusted root certificate can be optionally included as the last certificate.
    If your certificate does not meet the criteria listed in this step, you might get an error when you upload it. Create a new SSL certificate and upload the certificate using AWS Identity and Access Management (IAM). For instructions on creating and uploading the SSL certificate, go to Creating and Uploading Server Certificates in Using AWS Identity and Access Management.

    Step through the following instructions to continue uploading your SSL certificate.
    • Enter the name of the certificate to upload.
    • Copy and paste the contents of the private key file (PEM-encoded) in the Private Key box.
    • Copy and paste the contents of the public key certificate file (PEM-encoded) in the Public Key Certificate box.
    • [Optional] Copy and paste the contents of the public key certificate chain file (PEM-encoded) in the Certificate Chain box.
    Note The certificate chain must be ordered such that the root certificate is the last certificate in the chain. If you use a certificate chain in a different order, you will receive an error.
  9. Click Save.

Steps to Create SSL Certificate for Amazon Elastic Load Balancer and Update SSL Certificate on Elastic Load Balancer

his section describes the process of generating a server certificate and preparing it to use with AWS products through IAM. To create a certificate, you perform a series of tasks as described by the following topics. Note: If you want to create user signing certificate that you can use to sign SOAP requests in EC2, see Creating and Uploading a User Signing Certificate Topics
  • Install and Configure OpenSSL
  • Create a Private Key
  • Create a Certificate Signing Request
  • Submit the CSR to a Certificate Authority
  • To update an SSL certificate for an HTTPS load balancer
  • Sample server certificate

Install and Configure OpenSSL
Creating and uploading a certificate requires a tool that supports the SSL and TLS protocols. OpenSSL is an open-source tool that provides the basic cryptographic functions necessary to create an RSA token and sign it with your private key. If you don't already have OpenSSL installed, follow the instructions in this section.
  • To install OpenSSL on Windows
    1. Go to OpenSSL: Binary Distributions (http://www.openssl.org/related/binaries.html).
    2. Click OpenSSL for Windows.
  • A new page displays with links to the Windows downloads.
    1. If it is not already installed on your system, select the Microsoft Visual C++ 2008 Redistributables link appropriate for your environment and click Download. Follow the instructions provided by the Microsoft Visual C++ 2008 Redistributable Setup Wizard.
    2. After you have installed the Microsoft Visual C++ 2008 Redistributables, select the appropriate version of the OpenSSL binaries for your environment and save the file locally. The OpenSSL Setup Wizard launches.
    3. Follow the instructions described in the OpenSSL Setup Wizard. Save the OpenSSL binaries to a folder in your working directory.
  • Before you use OpenSSL commands, you must configure the operating system so that it has information about the location of the OpenSSL install point.
  • To configure OpenSSL on Windows
    1. Open a Command Prompt window.
    2. Set the OpenSSL_HOME variable to the location of the OpenSSL installation:
      set Path=OpenSSL_HOME\bin;%Path%
    3. Set the path to the OpenSSL installation:
      set Path=OpenSSL_HOME\bin;%Path%
Note: Any changes you make to Windows environment variables in a Command Prompt window are valid only for the current command-line session. You can make persistent changes to the environment variables by setting them as system properties. The exact procedures depend on what version of Windows you're using. (For example, in Windows 7, open Control Panel > System and Security > System. Then choose Advanced system settings > Advanced tab > Environment Variables.) For more information, see the Windows documentation.

Create a Private Key
You need a unique private key to create your Certificate Signing Request (CSR).
At the command line, use the openssl genrsa command and the following syntax:
openssl genrsa 2048 > private-key.pem For private-key.pem
specify your own file name. In the example, 2048 represents 2048-bit encryption. AWS also supports 1024-bit and 4096-bit encryption. We recommend you create an RSA key that is 2048 bits.

Create a Certificate Signing Request
The next step is to create a Certificate Signing Request (CSR). This is a file that you can send to a certificate authority (CA) to apply for a server certificate.
• Use the openssl req command to create a CSR and the following syntax:
openssl req -new -key private-key.pem -out csr.pem
The output will look similar to the following example:

You are about to be asked to enter information that will be incorporated into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank.
For some fields there will be a default value.
If you enter '.', the field will be left blank.

The following table can help you create your certificate request.
Name Description Example
Country Name The two-letter ISO abbreviation for your country. US = United States
State or Province The name of the state or province where your organization is located. This name cannot be abbreviated. Washington
Locality Name The name of the city where your organization is located. Seattle
Organization Name The full legal name of your organization. Do not abbreviate your organization name. Example Corp.
Organizational Unit Optional, for additional organization information. Marketing
Common Name The fully qualified domain name for your CNAME. You will receive a certificate name check warning if this is not an exact match. www.yourdomain.com
Email address The server administrator's email address someone@yourdomain.com

Note:The Common Name field is often misunderstood and is completed incorrectly. The common name is typically your host plus domain name. It will look like "www.company.com" or "company.com". You need to create a CSR using your correct common name.

Submit the CSR to a Certificate Authority
Your CSR contains information identifying you. To apply for a server certificate, send your CSR to a certificate authority (CA). The CA might require other credentials or proofs of identity.
If the request for a certificate is successful, the CA returns an identity certificate (and possibly a chain certificate) that is digitally signed.
AWS does not recommend a specific CA. For a partial listing of available CAs, see Third-Party Certificate Authorities.


To update an SSL certificate for an HTTPS load balancer
  1. Sign in to the AWS Management Console and open the Amazon EC2 console at https://console.aws.amazon.com/ec2/.
  2. On the Amazon EC2 Getting Started page, in the EC2 Dashboard pane, under NETWORK & SECURITY, click Load Balancers.
  3. On the Load Balancers page, select your load balancer.
  4. The bottom pane displays the details of your load balancer.
  5. Click the Listeners tab.
  6. Click Change in the SSL Certificate column of the certificate you want to update.
  7. On the Configure SSL Certificate page, select Choose from your existing SSL Certificates to use previously uploaded SSL certificate and select the certificate from the drop-down box.
  8. Or, select Upload a new SSL Certificate if you have a SSL certificate and want to uploaded it.
    Before you upload, ensure that your certificate meets the following citeria:
    • Certificates must follow the X.509 PEM format.
    • The current date must be between the certificate’s start and end date.
    • Public and private certificate files must contain only a single certificate.
    • The private key must match the public key that is in the digital server certificate.
    • The private key must be an RSA private key in PEM format, where the PEM header is BEGIN RSA PRIVATE KEY and the footer is END RSA PRIVATE KEY.
    • The private key cannot be encrypted with a password.
    • A certificate chain starts with the immediate signing certificate and is then followed by any intermediaries in order. Intermediaries that are not involved in the trust path must not be included. The trusted root certificate can be optionally included as the last certificate.
    If your certificate does not meet the criteria listed in this step, you might get an error when you upload it. Create a new SSL certificate and upload the certificate using AWS Identity and Access Management (IAM). For instructions on creating and uploading the SSL certificate, go to Creating and Uploading Server Certificates in Using AWS Identity and Access Management.

    Step through the following instructions to continue uploading your SSL certificate.
    • Enter the name of the certificate to upload.
    • Copy and paste the contents of the private key file (PEM-encoded) in the Private Key box.
    • Copy and paste the contents of the public key certificate file (PEM-encoded) in the Public Key Certificate box.
    • [Optional] Copy and paste the contents of the public key certificate chain file (PEM-encoded) in the Certificate Chain box.
    Note The certificate chain must be ordered such that the root certificate is the last certificate in the chain. If you use a certificate chain in a different order, you will receive an error.
  9. Click Save.

Sample Certificates
The following certificates show the valid format that IAM accepts for server certificates and their associated private key and certificate chain.
The server certificate associates your public key with your identity. When you submit your Certificate Signing Request (CSR) to a certificate authority (CA), a server certificate is returned to you by the CA. The following figure is a sample server certificate:
Sample server certificate
-----BEGIN CERTIFICATE-----
MIIE+TCCA+GgAwIBAgIQU306HIX4KsioTW1s2A2krTANBgkqhkiG9w0BAQUFADCB
tTELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQL
ExZWZXJpU2lnbiBUcnVzdCBOZXR3b3JrMTswOQYDVQQLEzJUZXJtcyBvZiB1c2Ug
YXQgaHR0cHM6Ly93d3cudmVyaXNpZ24uY29tL3JwYSAoYykwOTEvMC0GA1UEAxMm
VmVyaVNpZ24gQ2xhc3MgMyBTZWN1cmUgU2VydmVyIENBIC0gRzIwHhcNMTAxMDA4
MDAwMDAwWhcNMTMxMDA3MjM1OTU5WjBqMQswCQYDVQQGEwJVUzETMBEGA1UECBMK
V2FzaGluZ3RvbjEQMA4GA1UEBxQHU2VhdHRsZTEYMBYGA1UEChQPQW1hem9uLmNv
bSBJbmMuMRowGAYDVQQDFBFpYW0uYW1hem9uYXdzLmNvbTCBnzANBgkqhkiG9w0B
AQEFAAOBjQAwgYkCgYEA3Xb0EGea2dB8QGEUwLcEpwvGawEkUdLZmGL1rQJZdeeN
3vaF+ZTm8Qw5Adk2Gr/RwYXtpx04xvQXmNm+9YmksHmCZdruCrW1eN/P9wBfqMMZ
X964CjVov3NrF5AuxU8jgtw0yu//C3hWnOuIVGdg76626ggOoJSaj48R2n0MnVcC
AwEAAaOCAdEwggHNMAkGA1UdEwQCMAAwCwYDVR0PBAQDAgWgMEUGA1UdHwQ+MDww
OqA4oDaGNGh0dHA6Ly9TVlJTZWN1cmUtRzItY3JsLnZlcmlzaWduLmNvbS9TVlJT
ZWN1cmVHMi5jcmwwRAYDVR0gBD0wOzA5BgtghkgBhvhFAQcXAzAqMCgGCCsGAQUF
BwIBFhxodHRwczovL3d3dy52ZXJpc2lnbi5jb20vcnBhMB0GA1UdJQQWMBQGCCsG
AQUFBwMBBggrBgEFBQcDAjAfBgNVHSMEGDAWgBSl7wsRzsBBA6NKZZBIshzgVy19
RzB2BggrBgEFBQcBAQRqMGgwJAYIKwYBBQUHMAGGGGh0dHA6Ly9vY3NwLnZlcmlz
aWduLmNvbTBABggrBgEFBQcwAoY0aHR0cDovL1NWUlNlY3VyZS1HMi1haWEudmVy
aXNpZ24uY29tL1NWUlNlY3VyZUcyLmNlcjBuBggrBgEFBQcBDARiMGChXqBcMFow
WDBWFglpbWFnZS9naWYwITAfMAcGBSsOAwIaBBRLa7kolgYMu9BSOJsprEsHiyEF
GDAmFiRodHRwOi8vbG9nby52ZXJpc2lnbi5jb20vdnNsb2dvMS5naWYwDQYJKoZI
hvcNAQEFBQADggEBALpFBXeG782QsTtGwEE9zBcVCuKjrsl3dWK1dFiq3OP4y/Bi
ZBYEywBt8zNuYFUE25Ub/zmvmpe7p0G76tmQ8bRp/4qkJoiSesHJvFgJ1mksr3IQ
3gaE1aN2BSUIHxGLn9N4F09hYwwbeEZaCxfgBiLdEIodNwzcvGJ+2LlDWGJOGrNI
NM856xjqhJCPxYzk9buuCl1B4Kzu0CTbexz/iEgYV+DiuTxcfA4uhwMDSe0nynbn
1qiwRk450mCOnqH4ly4P4lXo02t4A/DI1I8ZNct/Qfl69a2Lf6vc9rF7BELT0e5Y
R7CKx7fc5xRaeQdyGj/dJevm9BF/mSdnclS5vas=
-----END CERTIFICATE-----

The private key allows you to decrypt messages that are encrypted with your public key. The following figure is a sample private key: Sample private key

The certificate chain includes all intermediary certificates that lead to the root certificate, as shown in the following example. Intermediaries that are not involved in the trust path must not be included. Sample certificate chain
-----BEGIN CERTIFICATE-----
CA public key certificate
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
Intermediate certificate 2
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
Intermediate certificate 1
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
Optional: Root certificate
-----END CERTIFICATE-----

Friday, August 2, 2013

Configure VPC with scenario 1 "VPC with a Public Subnet Only"

Set up the VPC, subnet, and Internet gateway:
  1. Open the Amazon VPC console at https://console.aws.amazon.com/vpc/.
  2. Click VPC Dashboard in the navigation pane.
  3. Locate the Your Virtual Private Cloud area of the dashboard and clicks get started creating a VPC, if you have no VPC resources, or click Start VPC Wizard.
  4. Select the first option, VPC with a Single Public Subnet Only, and then click Continue.
  5. The confirmation page shows the CIDR ranges and settings that you've chosen. Make any changes that you need, and then click Create VPC to create your VPC, subnet, Internet gateway, and route table.

Create WebServerSG and Adding Rules to the Security Group
The WebServerSG security group is the security group that you'll specify when you launch your web servers into your public subnet. The following table describes the recommended rules for this security group, which allow the web servers to receive Internet traffic, as well as SSH and RDP traffic from your network. The web servers can also initiate traffic to the Internet and read and write requests to the database servers in the private subnet.
Inbound
Source Protocol Port Range Comments
0.0.0.0/0 TCP 80 Allow inbound HTTP access to the web servers from anywhere
0.0.0.0/0 TCP 443 Allow inbound HTTPS access to the web servers from anywhere
18.71.152.166/32 TCP 3389 Allow inbound RDP access to Windows instances from your network (over the Internet gateway)
Outbound
Destination Protocol Port Range Comments
0.0.0.0/0 TCP 80 Allow web servers to initiate outbound HTTP access to the Internet (for example, for software updates)
0.0.0.0/0 TCP 443 Allow web servers to initiate outbound HTTPS access to the Internet (for example, for software updates)
The ID of your DBServerSG security group TCP 1433 Allow outbound Microsoft SQL Server access to the database servers assigned to DBServerSG
Create the WebServerSG security group and add rules:
  1. Open the Amazon VPC console at https://console.aws.amazon.com/vpc/
  2. Security Groups in the navigation pane.
  3. Click the Create Security Group button.
  4. Specify WebServerSG as the name of the security group, and provide a description. Select the ID of your VPC from the VPC menu, and then click Yes, Create
  5. Select the WebServerSG security group that you just created. The details pane include a tab for information about the security group, plus tabs for working with its inbound rules and outbound rules.
  6. On the Inbound tab, do the following:
    • Select HTTP from the Create a new rule list, make sure that Source is 0.0.0.0/0, and then click Add Rule.
    • Select HTTPS from the Create a new rule list, make sure that Source is 0.0.0.0/0, and then click Add Rule.
    • Select RDP from the Create a new rule list, make sure that Source is “Office IP Address” , and then click Add Rule
    • Click Apply Rule Changes to apply these inbound rules.
  7. On the Outbound tab, do the following:
    • Locate the default rule that enables all outbound traffic, and then click Delete.
    • Select HTTP from the Create a new rule list, make sure that Destination is 0.0.0.0/0, and then click Add Rule.
    • Select HTTPS from the Create a new rule list, make sure that Destination is 0.0.0.0/0, and then click Add Rule.
    • Select My SQL from the Create a new rule list, make sure that Destination is “ID of DBServerSG”, and then click Add Rule.
    • Click Apply Rule Changes to apply these outbound rules.


Create DBServerSG and Adding Rules to the Security Group
The DBServerSG security group is the security group that you'll specify when you launch your database servers into your private subnet. The following table describes the recommended rules for this security group, which allow read or write database requests from the web servers. The database servers can also initiate traffic bound for the Internet (your route table sends that traffic to the NAT instance, which then forwards it to the Internet over the Internet gateway).
DBServerSG:Rules
Inbound
Source Protocol Port Range Comments
The ID of your WebServerSG security group TCP 1433 Allow web servers assigned to WebServerSG Microsoft SQL Server access to database servers assigned to DBServerSG
18.71.152.166/32 TCP 3389 Allow inbound RDP access to Windows instances from your network (over the Internet gateway)
Outbound
Destination Protocol Port Range Comments
0.0.0.0/0 TCP 80 Allow outbound HTTP access to the Internet (for example, for software updates)
0.0.0.0/0 TCP 443 Allow outbound HTTPS access to the Internet (for example, for software updates)


To add the recommended rules to the DBServerSG security group
  1. Select the DBServerSG security group that you created. The details pane displays the details for the security group, plus tabs for working with its inbound and outbound rules.
  2. Add rules for inbound traffic using the Inbound tab as follows:
    1. Select MYSQL from the Create a new rule list. In the Source box, specify the ID of your WebServerSG security group, and then click Add Rule.
    2. Select RDP from the Create a new rule list. In the Source box, specify IP Address of office security group, and then click Add Rule.
    3. Click Apply Rule Changes.
  3. Add rules for outbound traffic using the Outbound tab as follows:
    1. Select HTTP from the Create a new rule list. Make sure that Destination is 0.0.0.0/0, and then click Add Rule.
    2. Select HTTPS from the Create a new rule list. Make sure that Destination is 0.0.0.0/0, and then click Add Rule.
    3. Click Apply Rule Changes.

To launch First Web instance
  1. Start the Classic wizard:
    1. Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/.
    2. Click the Launch Instance button from the dashboard.
    3. On the Create a New Instance page, select Classic Wizard, and then click Continue.
  2. On the CHOOSE AN AMI page, the Quick Start tab displays a list of basic configurations called Amazon Machine Images (AMI). Choose the AMI that you want to use and click its Select button.
  3. On the INSTANCE DETAILS page, under Launch Instances, select the subnet to launch the instance into. Keep the other default settings on this page and click Continue.
  4. To use the default settings on the next INSTANCE DETAILS pages, just click Continue on each page.
  5. Select EBS Volume
  6. On the CREATE A KEY PAIR page, you can choose from any existing key pairs that you've created, or follow the wizard directions to create a new key pair.
  7. On the Configure Firewall page, select the security group you want to use for the instance (WebServerSG), and then click Continue.
  8. Review your settings. When you're satisfied with your selections, click Launch.
    Before you can access an instance in your public subnet, you must assign it an Elastic IP address.
To allocate Elastic IP address and assign it to an instance
  1. Open the Amazon VPC console at https://console.aws.amazon.com/vpc/.
  2. Click Elastic IPs in the navigation pane.
  3. Click the Allocate New Address button.
  4. In the Allocate New Address dialog box, in the EIP used in list, select VPC, and then click Yes, Allocate.
  5. Select the Elastic IP address from the list, and then click the Associate Address button.
  6. In the Associate Address dialog box, select the network interface or instance. Select the address to associate the Elastic IP address with from the corresponding Private IP Address list, and then click Yes, Associate.
To create password for this instance
  1. Go to instance in EC2 and Right Click on instance.
  2. Click on “Get Windows Password” , select your Private key pair file and generate password by clicking on “Decrepit Password”
To create password for this instance To launch First Web instance
We have to launch a seperate Instance for Database with the security group "DBServerSG" (specified above) on the same public subnet mask.
Now you can connect to database server from Web server by using Private IP of Database Instance.