Monday, 12 June 2017

Windows Azure random FAQs

1. What are IaaS, PaaS and SaaS?

Basically these are cloud service models for cloud offerings. These are categorized on the basis of cloud management of resources.
SaaS: In this we browsers are used to access the software.  In SaaS, all things are managed by cloud provides like infrastructure, data, storage, security etc.
Example of SaaS: Office365, Web based Email services.
Benefits: Scalability, Multi-Tenancy, Security, Pay only what you use. You don’t need to purchase, install, update or maintain any hardware, middleware or software. SaaS makes costly application like as ERP and CRM affordable for users that lack the resources to buy, deploy and manage the required infrastructure and software themselves.
PaaS: This offers a platform to develop and deploy applications.
IaaS: This offers the cloud servers and associated resources with these servers.

1.       Hosted Applications

All are managed by Cloud Provider.

Managed by User.

Managed by User.
2.       Develop and deployment tools

Managed by cloud provider.
3.       OS
4.       Server and Storage
Managed by cloud provider.
5.       Networking/Firewall Security
6.       Data Centers

2. What is Service bus and its components?

Main use of service bus is to integrate on premise applications with cloud.
It’s something like postal service that we see in real world. This ensure the communication between two parties even both are not online at same time. That’s why it is brokered messaging mechanism. However it is also provide third party communication as well. So it supports two type of messaging patterns.
Azure Relay: The WCF Relay component of Azure Relay is a centralized (but highly load-balanced) service that supports a variety of different transport protocols and Web services standards. The relay service supports traditional one-way messaging, request/response messaging, and peer-to-peer messaging.
Azure Service Bus: Also called Brokered messaging. In this the messaging infrastructure reliably stores messages in a "broker" (such as a queue) until the consuming party is ready to receive them.
 Below are the basic components of Azure Service Bus.
Can be many receivers but one receiver can only receive a message at a time. No two receivers can receive a single message simultaneously.
Each message is processed by a single consumer.

ReceiveAndDelete: remove message and immediately deletes it. If exception then message will be lost.
PeekLock: Rather than delete, it locks the message and wait for three events.
1.       If the receiver processes the message successfully, it calls Complete (), and the queue deletes the message.

2.       If the receiver decides that it can't process the message successfully, it calls Abandon (). The queue then removes the lock from the message and makes it available to other receivers.

3.        If the receiver calls neither of these within a configurable period of time (by default, 60 seconds), the queue assumes the receiver has failed. In this case, it behaves as if the receiver had called Abandon, making              the message available to other receivers.

Support publish/subscribe messaging communication model.
"one-to-many" form of communication.
When a message is sent to a topic, it is then made available to each subscription to handle/process independently.

Can apply filter when subscribe.
// Create a "HighMessages" filtered subscription.
SqlFilter highMessagesFilter =
   new SqlFilter("MessageId > 3");


Supports traditional one-way, request/response, and peer-to-peer traffic.

Enabling you to securely expose services that reside within a corporate enterprise network to the public cloud, without having to open a firewall connection, or require intrusive changes to a corporate network infrastructure.

Event Hubs are also part of service bus that are also work on Publisher/subscriber model. When events are stored in the Hub, it will stay in the hub until the retention period expires. so you can read messages if needed, even after other subscribers are already read that event/message.

3. What is App Service?

It is an Azure PaaS offerings to create web and mobile applications and provides supports to integrate your apps with on premise applications.
·         It support multiple languages like, Node.js, PHP, Java, Python etc.
·         Also you can run PS scripts inside app service VMs.
·         Support of scale up and out.
·         Connections to SaaS platforms and on-premises data - Choose from more than 50 connectors for enterprise systems (such as SAP, Siebel, and Oracle), SaaS services (such as Salesforce and Office 365), and internet services (such as Facebook and Twitter). Access on-premises data using Hybrid Connections and Azure Virtual Networks.

App Service offers several app types, each of which is intended to host a specific workload:
·         Web Apps - For hosting websites and web applications.
·         Mobile Apps -For hosting mobile app back ends.
·         API Apps - For hosting RESTful APIs.
·         Logic Apps - For automating business processes and integrating systems and data across clouds without writing code.

4. Difference between Azure Web Role vs Azure Web Apps (Azure websites)?

Web role provides the ability to run elevated startup scripts, edit registries, install third party exe, and optimize IIS.
It provides the full control over IIS and web server. You can RDP the VM.
With Windows Azure Web Apps, you don’t have control over IIS or web Server. But it provides fast deployment than Web roles.

5. Brief about Azure API management.

AAPIM is a solution for publishing your APIs to external and internal customers. You have to create an API gateway for your existing backend services hosted anywhere. You can apply security, rules on these services and get how the developers and other users are consuming your services.

·         Secure your APIs using a key, token and IP filtering.
·         Enforce flexible and fine-grained quotas and rate limits, modify the shape and behavior of your APIs using policies and improve latency and scale your APIs with response caching.
·         Get near real-time analytics reports and identify trends that might affect your business. Plus, log request and response data for more online and offline analysis.
·         Expose all APIs behind a single static IP and domain.

6. How to manage your data in Azure.

Azure provides various ways to store and manage the data. Like
·         SQL Database: if data is relational then it would be good option.
·         Blob Storage: store collection of unstructured bytes like backups, videos, mp3, pdf, documents etc.
·         Table Storage: provides NoSQL like storage that work on key-value pairs.

7. Brief state management in azure.

For state management you can use
·         Table Storage
·         Sql Azure
·         Azure Caching
You can provide the session state provide for each as below.
Table Storage:
<sessionState mode="Custom" customProvider="TableStorageSessionStateProvider">
    <add name="TableStorageSessionStateProvider"
        type="Microsoft.Samples.ServiceHosting.AspProviders.TableStorageSessionStateProvider" />
TableStorageSessionStateProvider created by Azure Product development team.

Sql Azure:
<sessionState mode="SQLServer"
sqlConnectionString="Server=tcp:[serverName];Database=myDataBase;User ID=[LoginForDb]@[serverName];Password=[password];Trusted_Connection=False;Encrypt=True;"
cookieless="false" timeout="20" allowCustomSqlDatabase="true" />

Azure Caching:
<sessionState mode="Custom" customProvider="AzureCacheSessionStoreProvider">
    <add name="AzureCacheSessionStoreProvider"
          type="Microsoft.Web.DistributedCache.DistributedCacheSessionStateStoreProvider, Microsoft.Web.DistributedCache"
          cacheName="default" useBlobMode="true" dataCacheClientName="default" />

8. What is VIP swap?

VIP swap is just a virtual IP swap. VIP swap is the standard way to move your staging deployment to prod and vice versa. This feature is intended to high availability.

9. How to replace URL from custom domain name?

Custom DNS is not supported in free tier. You have to access control over DNS settings.
·         Create a CNAME record with your domain provider. Provide name as “www”.
·         Enable CNAME record mapping in your app in azure portal.
·         Add hostname
·         Create A and TXT record inside domain provider
For A record provide IP address of your app from azure portal.
For TXT record provide URL of your app.
·         Add these record type also by add hostname in azure portal.

10. What is NoSQL Db. List some example of those.

·         DocumentDb
·         CosmosDb

Wednesday, 7 June 2017

Random Advance C# FAQs

  1.  Difference between const, readlonly and static readonly?
  2.  const: const variable value is set as constant value at compile time. it can not be changed.
     readonly: readonly value can be changed at run time using constructor. 
     static readonly: static readonly variables value only can be changed inside static  constructor at run time.

  3. Difference between Binary and XML Serialization?

  4. Binary Serialization: In binary serialization, all  members whether these are pubic, private or readonly are serialized. This is faster than XML serialization. 
    XML Serialization: It serialize only public members.

Tuesday, 30 May 2017

Angular 2 FAQs

1. What is angular module?

NgModule helps to organize an application into organized blocks of functionality. @NgModule decorator takes metadata that tells angular how to compile and run the module code. A typical NgModule looks like.

Each application in angular 2 must have at least one NgModule that you need to bootstrap to launch your application.

Components of NgModule:
Declarations Array: this includes application’s components only.
Imports Array: this includes modules.
Providers Array: this includes services.
Bootstrap Array: include components to bootstrap, generally one component used  but you can provide multiple components as well if required.

2. Explain Routing in angular 2?

Router package is used for angular 2 routing. And this router comes with many features for routing based on paths and loading specific components.
To define route we can create routes constants in your modules like

const routes=[
  {Path:'',component: HomeComponent},

Then you have to import these routes in NgModule.
  declarations: [
  imports: [
    HttpModule, RouterModule.forRoot(routes)
  providers: [],
  bootstrap: [AppComponent]

Also you have to use router-outlet inside your component.

  selector: 'app-root',
  template: '<nav>
             <a routerLink=””>Home</a>
          <a routerLink=”contact”></a>

But this approach can be optimized by putting out routes in separate file.
We can create separate app.route.ts file to define our route.

import { HomeComponent } from './app.component';
import { ContactsComponent } from './app.component';
import { RouterModule } from '@angular/router';
const routes=[
  {Path:'',component: HomeComponent},

export default RouterModule.forRoot(routes);

And then we does not need to import RouterModule.forRoot(routes) inside our module but we simply import this app.rotes that we have created.

import appRoutes from './app.route';

  declarations: [
  imports: [
  providers: [],
  bootstrap: [AppComponent]

You can have separate route for each component as below. This is called lazy loading of modules using angular 2 router.

a.       Create a separate home.route.ts

import { HomeComponent } from "app/home/home.component";
import { RouterModule } from "@angular/router";

const routes = [
{ path: '', component:HomeComponent}

export default RouterModule.forRoot(routes);

b.      Configure route into module.

import { NgModule } from "@angular/core";
import { CommonModule } from "@angular/common";
import { HomeComponent } from "app/home/home.component";
import { RouterModule } from "@angular/router";
import homeRoutes from 'app/home/home.routes';

imports :[CommonModule, homeRoutes],

export default class HomeModule{


c.       Configure individual routes to app.route.ts that we have created earlier. See the difference on above app.route.ts and this.

import { HomeComponent } from './app.component';
import { ContactsComponent } from './app.component';
import { RouterModule } from '@angular/router';
import {CommonModule} from '@angular/common'
const routes=[
  {Path:'',loadChildren: 'app/home/home.module'},

export default RouterModule.forRoot(routes);   

Saturday, 27 May 2017

Web API 2 Interview FAQs



1.       What are the return types of Action methods in Web API?

a. Void:
     If the return type is void, Web API simply returns an empty HTTP response with  status code 204 (No Content).

b. HttpResponseMessage
Web API converts the return value into HttpResponseMessage.
This option also provides the control over response message.
Like you can use server side caching using CacheControlHeaderValue.
response.Headers.CacheControl = new CacheControlHeaderValue()
            MaxAge = TimeSpan.FromMinutes(20)

Also you can use Request.CreateResponse() method to pass a domain model that will serialized using media formmatter based on Content Negotiation.

public HttpResponseMessage Get()
    // Get a list of products from a database.
    IEnumerable<Product> products = GetProductsFromDB();

    // Write the list to the response body.
    HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, products);
    return response;

c. IHttpActionResult

Introduce in Web API2.
It has one method called ExecuteAsync().
public interface IHttpActionResult
    Task<HttpResponseMessageExecuteAsync(CancellationToken cancellationToken);
It is used to create a factory of HttpResponseMessage . Basically   you can put your logic for HttpResponse in separate classes.
public class TextResult : IHttpActionResult
    string _value;
    HttpRequestMessage _request;

    public TextResult(string valueHttpRequestMessage request)
        _value = value;
        _request = request;
    public Task<HttpResponseMessageExecuteAsync(CancellationToken cancellationToken)
        var response = new HttpResponseMessage()
            Content = new StringContent(_value),
            RequestMessage = _request
        return Task.FromResult(response);
Example controller
public class ValuesController : ApiController
    public IHttpActionResult Get()
        return new TextResult("hello", Request);
HTTP/1.1 200 OK
Content-Length: 5
Content-Type: text/plain; charset=utf-8
Server: Microsoft-IIS/8.0
Date: Mon, 27 Jan 2014 08:53:35 GMT


public IHttpActionResult Get (int id)
    Product product = _repository.Get (id);
    if (product == null)
        return NotFound(); // Returns a NotFoundResult
    return Ok(product);  // Returns an OkNegotiatedContentResult

d. Some other type
              For other types Web API uses Media formatter and serialize the                         response return with 200 OK.
               A disadvantage of this approach is that you cannot directly return an                  error code, such as 404. 

2. What is content negotiation?

Content Negotiation is the process of selecting content representation based request headers. As there are multiple representations/formatter available.
Accept: Which media types are acceptable for the response, such as "application/json," "application/xml," or a custom media type such as "application/vnd.example+xml"
Accept-Charset: Which character sets are acceptable, such as UTF-8 or ISO 8859-1.
Accept-Encoding: Which content encodings are acceptable, such as gzip.
Accept-Language: The preferred natural language, such as "en-us".

The object that serializes the resource is called a media formatter. Media formatters derive from the MediaTypeFormatter class. Web API provides media formatters for XML and JSON, and you can create custom formatters to support other media types.

3. How to create custom media type formatter?

First you have to create your custom formatter class that should be implement/inherit BufferedMediaTypeFormater class of System.Net.Http.Formatting namespace.
Then use CanReadType and ReadFromStream methods to deserialize data and CanWritetype and WriteToStream methods to serialize data.

4. What is the difference between ASP.Net MVC routing and Web API routing?

In ASP.Net MVC, action methods selected based on URI, but in Web API action methods are selected based on HTTP Methods. However it is also possible to do MVC based routing in Web API. Each entry in the routing table contains a route template. The default route template for Web API is "api/{controller}/{id}".
When the Web API framework receives an HTTP request, it tries to match the URI against one of the route templates in the routing table. If no route matches, the client receives a 404 error. For example, the following URIs match the default route:
However, the following URI does not match, because it lacks the "api" segment:

Once a matching route is found, Web API selects the controller and the action:
·  To find the controller, Web API adds "Controller" to the value of the {controller} variable.
·  To find the action, Web API looks at the HTTP method, and then looks for an action whose name begins with that HTTP method name. For example, with a GET request, Web API looks for an action that starts with "Get...", such as "GetContact" or "GetAllContacts". This convention applies only to GET, POST, PUT, and DELETES methods. You can enable other HTTP methods by using attributes on your controller.
·  Other placeholder variables in the route template, such as {id}, are mapped to action parameters.

1.You can specify the HTTP method with an attribute: AcceptVerbsHttpDeleteHttpGetHttpHeadHttpOptionsHttpPatchHttpPost, or HttpPut.
2. Otherwise, if the name of the controller method starts with "Get", "Post", "Put", "Delete", "Head", "Options", or "Patch", then by convention the action supports that HTTP method.
3. If none of the above, the method supports POST.

5. What is attribute routing?

Attribute routing uses attributes to define route, it has more control over URI then conventional based routing, however you can use both routing in same project. If you will not provide attribute on actions then it will use conventional based routing.

6. What is the advantage of conventional routing?

In this, routing templates are defined at single place and the routing rules are applies consistently across all controllers. But conventional routing does not support certain type of URI. Like
Suppose you want orders details of customers whose id is 1. 
Then URL looks like /customers/1/orders

7. Why Attribute routing?

You can handle above type of situation easily with attribute routing.
public IEnumerable<Order> GetOrdersByCustomer(int customerId{ ... }
Other Benefits are
·   API versioning
You can have multiple versions of your APIs.

·    Overloaded URI segments
In this example, "1" is an order number, but "pending" maps to a collection.

·    Multiple Parameters types
In this example, "1" is an order number, but "2013/06/16" specifies a date.
[Route ("orders/{orderId}/Customer/{customerId}")]

8. How to enable Attribute routing?

Use config.MapHttpAttributeRoutes(); in WebApiConfig.cs.

9. How to migrate Web API  1 to 2.

Replace WebApiConfig.Register(GlobalConfiguration.Configuration); by 
GlobalConfiguration.Configure(WebApiConfig.Register);  in Application_Start method of Global.asax.

10. How to apply constraints in routing?

Web API 1:
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new {id = RouteParameter.Optional},
        constraints: new {id = @"\d+"}
Web API 2:
public User GetUserById(int id) { ... }

Some other examples:

11. How to create custom route constraints?

By implementing IsMatch method of IHttpRouteConstraint in your custom class.
Then you have to register in WebApiConfig.cs like
public static class WebApiConfig
    public static void Register(HttpConfiguration config)
        var constraintResolver = new DefaultInlineConstraintResolver();

          You can use like
public HttpResponseMessage GetNonZero(int id) { ... }

12. How to make route parameter optional?

Assign some value to that parameter.
     public class BooksController : ApiController
         public IEnumerable<Book> GetBooksByLocale(int lcid{ ... }

13. What is the use of Route Name?

Route name are helpful to generate links.
public class BooksController : ApiController
    [Route("api/books/{id}", Name="GetBookById")]
    public BookDto GetBook(int id)
        // Implementation not shown...
    public HttpResponseMessage Post(Book book)
        // Validate and add book to database (not shown)
        var response = Request.CreateResponse(HttpStatusCode.Created);

        // Generate a link to the new book and set the Location header in the response.
        string uri = Url.Link("GetBookById"new { id = book.BookId });
        response.Headers.Location = new Uri(uri);
        return response;

14. What is the route order?

When request comes, It searches for action in the route order.
Look at each URI segment in the route template. For each segment, order as follows:
· Literal segments. [Route("details")]
· Route parameters with constraints. [Route("{id:int}")]
· Route parameters without constraints. [Route("{customerName}")]
· Wildcard parameter segments with constraints. [Route("{*date:datetime}")]
· Wildcard parameter segments without constraints. 
   [Route ("pending"RouteOrder = 1)] due to route order 1 is after details.
· In the case of a tie, routes are ordered by a case-insensitive ordinal string comparison (OrdinalIgnoreCase) of the route template.

15. What are the Message Handlers in web API?

     Message handles are classes that can manipulate the incoming requests. There are various inbuilt message handlers.
  • HttpServer : It is used to retrieve the request message from Host (IIS/ Self-Host).
  • HttpRoutingDispatcher used to dispatch the request based on route configured.
  • HttpControllerDispatcher : used to send the request to respective controller. 
      All message handlers are inherited by HttpMessageHandler.

16. What is DelegatingHandler in web API?

          It is a class that is used to create custom message handlers in web API. It has the SendAsyc() method that pass the    request to inner handler. You can return response without calling any controller on some condition or manipulate   the request and pass to another handler. You can better understand by below example.

     public class CustomeHandler : DelegatingHandler
        protected override async Task<HttpResponseMessage>          SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
//1. If request does not meet your criteria like authorization/authentication or any other information that you want to compare.
return request.CreateResponse(HttpStatusCode.Unauthorized, “Error message”);
//2. You can modify headers of request
//3. You can logs the incoming request
//4. Then pass the request to next inner handler using base.SendAsync()
return await base.SendAsync(request, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);

           You also have to add this handler in your WebApiConfig.cs as
           GlobalConfiguration.Configuration.MessageHandlers.Add(new CustomeHandler());

    17. Explain Web API 2 life cycle.

      You can see complete life cycle here.
      I have made a short diagram for this to easily memorize the steps.

18. How to use Model validation in Web API 2?

      Web API support Data annotation same as in MVC. You can apply these data annotations attributes to your models and use ModelState.IsValid property to validate the Model.
using System.ComponentModel.DataAnnotations;

namespace MyApi.Models
    public class Product
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
        [Range(0, 999)]
        public double Weight { get; set; }
And create controllers like
public class ProductsController : ApiController
        public HttpResponseMessage Post(Product product)
            if (ModelState.IsValid)
                return new HttpResponseMessage(HttpStatusCode.OK);
  return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);

19. How to use Authentication in Web API 2?

      You can use Authentication in Web API2 in many ways.
      By default it assumes authentication happens in the host means on domain level. It uses HttpModule.
      When the host authenticates the user, it creates a principal, which is an IPrincipal object that represents the security context under which code is running. The host attaches the principal to the current thread by setting Thread.CurrentPrincipal. The principal contains an associated Identity object that contains information about the user. If the user is authenticated, the Identity.IsAuthenticated property returns true. For anonymous requests, IsAuthenticated returns false.

      As you see an HttpModule take care of all requests that go through the pipeline. But if you only want the security when requests are routed to your Web API then there is another approach called authentication using HttpMessageHandler.
      HttpMessageHandlers are more useful for Self-host Web API scenarios.

     You also can use Authentication filters that are introduced in Web API 2. Authentication filter also can applied at controller level or action level of globally like other filters.
[IdentityBasicAuthentication] // Enable Basic authentication for this controller.
[Authorize] // Require authenticated requests.
public class HomeController : ApiController
    public IHttpActionResult Get() { . . . }
    public IHttpActionResult Post() { . . . }

To create custom authentication filter, you can implement IAuthenticationFilter in your class.

20. How to use Authorization in Web API 2?

Authorization happens after authentication.

HttpModule=> HttpMessageHandler=>AuthorizationFilter=>Controller

You can use Authorize attribute to provide authorization at controller level or action level.

// only allowed users can access this controller:
public class ValuesController : ApiController
// only users with role Administrators can access this controller:
public class ValuesController : ApiController
      You can also create custom authentication filter by inheriting any of AuthorizeAttribute,   AuthorizationFilterAttribute, or IAuthorizationFilter.
      To disable host-level authentication inside the Web API pipeline, call config.SuppressHostPrincipal() in your configuration. This causes Web API to remove the IPrincipal from any request that enters the Web API pipeline. Effectively, it "un-authenticates" the request.

21. How can you restrict to the consumer/client of Web API 2 to use SSL?

You can write your own MessageHandler or Authorization filter.
Using MessageHandler: this will be applicable at global level.
public class HttpsSchemeAuthenticationHandler : DelegatingHandler
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
            if (request.RequestUri.Scheme != Uri.UriSchemeHttps)
      return request.CreateResponse(HttpStatusCode.Unauthorized, "Required  Https");

   Using Authorization: This can be applied on controller or action level.
public class RequireHttpsAttribute : AuthorizationFilterAttribute
    public override void OnAuthorization(HttpActionContext actionContext)
        if (actionContext.Request.RequestUri.Scheme != Uri.UriSchemeHttps)
            actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
                ReasonPhrase = " Required  Https "