Sunday, April 21, 2013

UML & Design Patterns & Architecture

Versioning in the Web.API?

https://dzone.com/articles/api-versioning-in-net-core


What is design principles?
SOLID Principles 
Single Responsibility
Open close
 Liskov Substitution.
Interface Segregation
Dependency Inversion


why single page application?

Single Page Application is good for making Responsive Websites, Support mobile, Tablet & Desktop. No extra queries to the server to download pages. Performance improvement, Single Page Application can improve performance in many ways,Single time file load each of HTML, CSS, JS.

Client side Routing + Client side Rendering = Single page application

What is High Level Design?

HLD -- High Level Design (HLD) is the overall systemdesign - covering the system architecture and databasedesign. It describes the relation between various modules and functions of the system. 

What is anti corruption layer design pattern ?
Implement a façade or adapter layer between a modern application and a legacy system

What are the architecture styles?
There are many recognized architectural patterns and styles, among them:

What is agnular Directive?
AngularJS directives are extended HTML attributes with the prefix ng- . The ng-app directive initializes an AngularJS application. The ng-model directive binds the value of HTML controls (input, select, textarea) to application data. Read about all AngularJS directives in our AngularJS directive reference.

Is there any difference between AWS Iaas and Azure IaaS?


If you are considering IaaS and looking at AWS and Azure, you really can’t go wrong with either one. Ultimately it is going to depend on the type of workload and the IT infrastructure that you want to operate.
If you’re a large shop, geared mostly to open source, and you’re also operating Windows, then AWS is more than a safe bet. If your bias is to move away from on-premises and to go 100% public cloud then AWS again would be an excellent option.
AWS has always been about providing elastic cloud resources in a highly configurable and reliable environment.
If you’re a Windows shop, and you need to operate a combination of on-premises cloud and public cloud, then Azure Stack is the only realistic option.  If your competency is almost exclusively Windows-centric and you want to leverage a close relationship with Microsoft, again you can’t go wrong with Azure.
In the end if your IaaS requirements are “lowest common denominator”, you can’t make a bad decision here. It is largely a matter of taste, as the two juggernauts are slowly inching towards functional parity. There are differences that can sway organizations, but the majority of IaaS needs can be met by either provider.

What is difference static and singleton.

static is a keyword and singleton is design pattern
static class contains only static members
singleton object can be passed as reference but static not.
singleton supports object dispose where static not.
singleton object stored in the heap, static class stored in stack.


The big difference between a singleton and a bunch of static methods is that singletons can implement interfaces.
we can implement interface with Singleton class but not with Static class.

Double checking lock in singleton gives performance problem

Singleton:-Creational
Ensure a class only has one instance, and provide a global point of access to it.

1.What is Docker?

Docker is an open-source engine that automates the deployment of any application as a lightweight.



1.What is software architecture?

Software architecture defined to be the rules and patterns.
  • Partitioning the problem and system to be built into discrete pieces.
  • Techniques are used to create interfaces between the discrete pieces.
  • Appropriate use of development and delivery approaches, techniques and tools.
2.Why architecture is important?

The primary goal of the architecture is to define the non-functional requirements of the system.And how to deliver the functional behavior within the architectural rules. Architecture is important because:
  • Control the complexity
  • Enforces the best practices.
  • Gives the consistency and Uniformarty
  • Increase predictability
  • Enable re-use

https://msdn.microsoft.com/en-us/library/dd129906.aspx

3.Architecture review?
https://msdn.microsoft.com/en-us/library/ff647464.aspx

4.What is content Negotiation?
Client send the request with accept header, client can specify the response want xml or json.

In Web APIcontent negotiation is performed by the runtime (at the server side) to determine the media type formatter to be used based to return the response for an incoming request from the client side.Content negotiation is centered on Media type and Media type formatter.

5What is concrete class?

Concrete class is nothing but normal class, we can use as a base class or may not.Not compulsory, it can't contain abstract methods.we can create object and work with this class. A concrete class is used to define a useful object that can be instantiated as an automatic variable on the program stack.

6.What is Micro services?

Essentially, micro-service architecture is a method of developing software applications as a suite of independently deplorable, small, modular services in which each service runs a unique process and communicates through a well-defined, lightweight mechanism to serve a business goal.

Microservices is a software development technique—a variant of the service-oriented architecture (SOA) architectural style that structures an application as a collection of loosely coupled services. In a microservices architecture, services are fine-grained and the protocols are lightweight. The benefit of decomposing an application into different smaller services is that it improves modularity and makes the application easier to understand, develop, test, and more resilient to architecture erosion.[1] It also parallelizes development by enabling small autonomous teams to develop, deploy and scale their respective services independently.[2] It also allows the architecture of an individual service to emerge through continuous refactoring.[3] Microservices-based architectures enable continuous delivery and deployment.[1][4]

7.Is docker is micro services?

The portability of containers also makes deployment of microservices a breeze. To push out a new version of a service running on a given host, the running container can simply be stopped and a new container started that is based on a Docker image using the latest version of the service code.

8. What is enterprise service bus?

An enterprise service bus (ESB) implements a communication system between mutually interacting software applications in a service-oriented architecture (SOA). It implements a software architecture as depicted in the picture. As it implements a distributed computing architecture, it implements a special variant of the more general client-server model, wherein, in general, any application using ESB can behave as server or client in turns.

9. Abstract Factory Design Patterns:

Abstract factory is the super factory which creates other factories. This factory also called factory of factories.

An interface for creates the families of related objects without specifying this concrete classes.

To create families of related objects, to be used interchangeably to configure your application

Client uses a factory creates objects.

using System;
class Program
{
    abstract class Position
    {
      public abstract string Title { get; }
    }
    class Manager : Position
    {
     public override string Title
    {
      get
         {
          return "Manager";
         }
    }
  }
    class Clerk : Position
    {
     public override string Title
    {
      get
         {
          return "Clerk";
         }
     }
    }
    class Programmer : Position
    {
      public override string Title
     {
      get
         {
          return "Programmer";
         }
     }
    }
    static class Factory
    {
///
/// Decides which class to instantiate.
///
public static Position Get(int id)
{
   switch (id)
   {
    case 0:
      return new Manager();
    case 1:
    case 2:
       return new Clerk();
    case 3:
   default:
        return new Programmer();
   }
}
 }

    static void Main()
    {
for (int i = 0; i <= 3; i++)
{
   var position = Factory.Get(i);
   Console.WriteLine("Where id = {0}, position = {1} ", i, position.Title);
}
    }
}

Output

Where id = 0, position = Manager
Where id = 1, position = Clerk
Where id = 2, position = Clerk
Where id = 3, position = Programmer
When to use it?
We use it when we have a requirement to create a set of related objects, or dependent objects which must be used together as families of objects. Concrete classes should be decoupled from clients.
  • Creates object through composition
  • Produce families of products
  • Concrete factories implements factory method to create product
2.Factory Method design pattern?

Creates objects without exposing the instantiation logic to the client and refers to the newly created object through common interface.

The client uses the factory creates a product.
  • Creates object through inheritance
  • Produce only one product
  • Implements code in the abstract creator that makes use of the concrete type that sub class produces
3. What is the difference between Abstract factory and factory method?
The main difference between a "factory method" and an "abstract factory" is that the factory method is a single method, and an abstract factory is an object.

 with the Abstract Factory pattern, a class delegates the responsibility of object instantiation to another object via composition .

In this pattern we define an interface which will expose a method which will create objects for us. Return type of that method is never be a concrete type rather it will be some interface

http://www.codeproject.com/Articles/716413/Factory-Method-Pattern-vs-Abstract-Factory-Pattern

4. Why we go for abstract factory?
depend on abstractions not concrete classes

Factory Method:-Creational
Define an interface for creating an object, but let subclasses decide which class to instantiate Factory Method lets a class Factory Method instantiate. Factory Method lets a class defer instantiation to subclasses.

3.Activity diagram?

The activity can be described as an operation of the system.It captures the dynamic behavior of the system.Other four diagrams are used to show the message flow from one object to another, but activity diagram is used to show message flow from one activity to another.


 



8.proxy pattern?


•Simplifying the API of complex objects. The proxy can provide a simple API so that the client code does not have to deal with the complexity of the object of interest

•Providing interface for remote resources such as web service or REST resources.

The proxy will determine if the client can access the object of interest.

Lazy loading through proxy

Surrogate pattern is proxy design pattern



10. Command design pattern?


Encapsulates a request in an object.



11.What is generalization and specialization?


Generalization

---------------

If many similar existing objects are combined to form a super class to do the job of its subclass', then it is known as Generalization



specialization

--------------

if some new subclasses are created from an existing super class to do specific job of the super class, then it is known as specialization.



12. What is Facade design pattern?

http://www.dotnet-tricks.com/Tutorial/designpatterns/1N4c140713-Facade-Design-Pattern---C#.html

Only access the HttpSessionState from within one single static class in your application is called façade.



13. What is the purpose of Host file?


The short answer is that the Hosts file is like an address book. When you type an address like www.yahoo.com into your browser, the Hosts file is consulted to see if you have the IP address, or "telephone number," for that site. If you do, then your computer will "call it" and the site will open. If not, your computer will ask your ISP's (internet service provider) computer for the phone number before it can "call" that site. Most of the time, you do not have addresses in your "address book," because you have not put any there. Therefore, most of the time your computer asks for the IP address from your ISP to find sites.



14. Dependency Injection?

http://www.dotnet-tricks.com/Tutorial/dependencyinjection/67LX120413-Implementation-of-Dependency-Injection-Pattern-in-C
Key points about DI

  1. Reduces class coupling

  1. Increases code reusing

  1. Improves code maintainability

  1. Improves application testing

15.Which service we have to run for distributed transaction ?

Distributed transaction coordinator.

16. Web Garden and Web form?

This is the case where you have only one web server and multiple clients requesting for resources from the same server. But when are is huge amount of incoming traffic for your web sites, one standalone server is not sufficient to process the request. You may need to use multiple servers to host the application and divide the traffic among them. This is called “Web Farm”. So when you are hosting your single web site on multiple web servers over load balancer is called “Web Farm”

Now, by default, each and every Application pool contains a single worker process. Application which contains the multiple worker process is called “Web Garden”.

http://mahedee.net/web-gardening-in-iis-7-configure-step-by-step/

Web farm is better than web garden.

17. One lakh records how to handle?
partition the table


18.What is cluster?


Clustering has a formal meaning. A cluster is a group of resources that are trying to achieve a common objective, and are aware of one another. Clustering usually involves setting up the resources (servers usually) to exchange details on a particular channel (port) and keep exchanging their states, so a resource’s state is replicated at other places as well. It usually also includes load balancing, wherein, the request is routed to one of the resources in the cluster as per the load balancing policy.

http://technet.microsoft.com/en-in/library/cc785197%28v=ws.10%29.aspx





19. What is load balancing?

Load balancing can also happen without clustering when we have multiple independent servers that have same setup, but other than that, are unaware of each other. Then, we can use a load balancer to forward requests to either one server or other, but one server does not use the other server’s resources. Also, one resource does not share its state with other resources.

To avoid session loss due to server failure in a load balancing group, there are two approaches: centralized state management and asynchronous session state management.

http://msdn.microsoft.com/en-us/library/ff648960.aspx


20.How will choose the technology?

1.Understanding the requirements
2, Break down the requirements
3.Identify the type of solution you are providing
  • Once requirements are gathered and logical design in place, identify your core modules that solution is most dependant on.
  • Now abstract away those components and try to describe them in a single word
  • This will help you choose the solution type that best suits your requirements:
    • If your requirements is predominantly a marketplace or Product transactions, then clearly its a Ecommerce project
    • If the requirements focus on content delivery, then its a CMS solution.
    • If the requirements involve data processing/computing, and various inputs taken from different sources (live or otherwise) or if the requirements are a collection of different unrelated components interacting in a unique fashion, then clearly the solution has to be some basic framework. This is the choice if there are no solutions available in the market meeting your core requirements.
4.Research
  • This is the most critical part of your design decision. Most mistakes and technical debts are made here at this point.
  • As in previous step, once the core modules are identified, research about them on the Internet. Find out the most popular technology or solution in that field
  • Ask on Stackoverflow and Programmer stack regarding any doubts you have.
  • Choose the technology/solution that handles most of your requirements out of the box.
  • Once a technology is chosen, we now try to handle the remainder of the requirements. For example, try to search for plugins or extensions that handle your special case.
  • If no extensions are available, estimate the complexity of implementing your requirement in the above technology/solution. Chances are your requirements can be easily implemented with little effort. Most solutions are designed to make your life easy.
  • In the unlikely case, that the coding complexity is too much, you need to rethink your choice of platform.
    • Choose another platform that covers most of your core requirements (the slightly less than ideal case).
    • Search for plugins/extensions to handle the remaining requirements.
    • It is possible that the complexity of your coding the remainder requirements would be lesser with this new choice.


1.Budget for license.
2.Experience-most technology choices are based on experience. "Go with what you know." You build highest quality most quickly with familiar tools.

21. Security in web services?

Transport security uses the security mechanism of transport protocol.

Message security, security implemented inside data itself example message is encrypted using X 509.
TCP is more complex protocol, due to its state full design incorporating reliable transmission and data stream services.

WCF uses transport protocols like TCP,HTTP,MSMQ,etc, each of these protocols have their own security mechanisms.

We will be using ‘makecert.exe’ which is a free tool given by Microsoft to enable HTTPS for testing purposes. MakeCert (Makecert.exe) is a command-line tool that creates an X.509 certificate that is signed by a system test root key or by another specified key. The certificate binds a certificate name to the public part of the key pair. The certificate is saved to a file, a system certificate store, or both.

https://msdn.microsoft.com/en-us/library/ff647370.aspx

http://msdn.microsoft.com/en-us/library/ff648318.aspx

1.WCF security features related to 1.auditing and 2.logging, 3.authentication, 4.authorization, 5.confidentiality, and 6.integrity.
2.transport security and message security
3.WCF supports a variety of authentication options including username, Windows, and certificate authentication.
4.basichttpbinding-no security
5.wshttpbinding-message secutiry with windows authentication
6.nettcpbinding-transport security with windows authentication

Transport security modes:
1.Transportcredentialonly-mutual authentication provided transport level.no message protection -basichttpbinding
2.Transportwithmessagecredential-client authentication provided at message level
3.Both-mutual autnetication provided at both transport level and message level
4.Message-mutual authentication and message protection at the message level
5.Transport -mutual authentication and message protection at transport level
6.None

Transport security authentication options
1.None
2.basic
3.ntlm
4.windows
5.certificates

Message security authentication options

1.None
2.windows
3.username
4.certificates
5.issue token

Authorization in wcf
1.Role based
2.Identity based
3.resource based

Role based
1.windows group
2.asp.net roles
3.custom roles


WS-Security Standards / Web Services Security Concepts
The WS-* architecture is a set of standards-based protocols designed to secure Web service communication. The WS-* security standards include:

1.WS-Policy. WS-Policy allows Web services to define policy requirements for endpoints. These requirements include privacy rules, encryption rules, and security tokens.

2.WS-Security. WS-Security allows Web services to apply security to Simple Object Access Protocol (SOAP) messages through encryption and integrity checks on all or part of the message.

3.WS-Trust. WS-Trust allows Web services to use security tokens to establish trust in a brokered security environment.

4.WS-SecureConversation. WS-SecureConversation builds on top of WS-Policy, WS-Security, and WS-Trust to enable secure communications between client and service.

5.WS-ReliableMessaging. WS-ReliableMessaging allows Web services and clients to trust that when a message is sent, it will be delivered to the intended party.

6.WS-AtomicTransactions. WS-AtomicTransactions allows transaction-based Web services in which transactions can be rolled back in the event of a failure

22.Managed Eextensiblity Framework?

https://msdn.microsoft.com/en-us/library/vstudio/dd460648(v=vs.100).aspx

http://www.codeproject.com/Articles/106328/NET-MEF-FAQ-Socket-Plug-and-extension

23.Preventing user other session?

http://geekswithblogs.net/Frez/archive/2010/05/17/preventing-a-user-from-having-multiple-concurrent-sessions.aspx

24. Linq to SQL is not suitable for high volume web applications

25. http://www.slideshare.net/oazabir/scaling-aspnet-websites-to-millions-of-users

26.Payment system architecture?
27.Security of card number?
SSL encryption
Format-preserving encryption
28. SQL injection ?

The only proven way to protect a web site from SQL injection attacks, is to use SQL parameters.
SQL parameters are values that are added to an SQL query at execution time, in a controlled manner.

txtUserId = getRequestString("UserId");
txtSQL = "SELECT * FROM Users WHERE UserId = @0";
db.Execute(txtSQL,txtUserId);

txtNam = getRequestString("CustomerName");
txtAdd = getRequestString("Address");
txtCit = getRequestString("City");
txtSQL = "INSERT INTO Customers (CustomerName,Address,City) Values(@0,@1,@2)";
db.Execute(txtSQL,txtNam,txtAdd,txtCit);

29. Payment architecture?

http://www.jatit.org/volumes/research-papers/Vol26No2/3Vol26No2.pdf



There are three basic elements of any payment gateway. Secure storage of credit card number as per the PCI DSS, AUTH and Settlement (capture).
  1. Have a service to securely store the card number and return a token or a hash as handle for credit card.

  1. You need rule engine or a service to Identify the CARD TYPE (VISA, MC, DISC, AMEX etc.) from BIN .

  1. An ESB or content based router to send the request to appropriate acquirer based on CARD TYPE or BIN.

  1. A service with high SLA to perform a real-time AUTH

  1. A service or batch job for settlement (CAPTURE)



30. What is SOA Architecture?
 A service-oriented architecture is essentially a collection of services. These services communicate with each other. The communication can involve either simple data passing or it could involve two or more services coordinating some activity.



31. Why JSON?
  • JSON parsing is generally faster than XML parsing.
  • Formatted JSON is generally easier to read than formatted XML.

32.What is architecture you will MVC or MVVM?


http://www.codeproject.com/Articles/560798/ASP-NET-MVC-Controller-Dependency-Injection-for-Be


. Scale up ?


  • Vertical Scaling (Scale-up): Generally refers to adding more processors and RAM, buying a more expensive and robust server.

    • Pros

      • Less power consumption than running multiple servers

      • Cooling costs are less than scaling horizontally

      • Generally less challenging to implement

      • Less licensing costs

      • (sometimes) uses less network hardware than scaling horizontally (this is a whole different topic that we can discuss later)

    • Cons

      • PRICE, PRICE, PRICE

      • Greater risk of hardware failure causing bigger outages

      • generally severe vendor lock-in and limited upgradeability in the futur


  • Horizontal Scaling (Scale-out): Generally refers to adding more servers with less processors and RAM. This is usually cheaper overall and can literally scale infinitely (although we know that there are usually limits imposed by software or other attributes of an environment’s infrastructure)

    • Pros

      • Much cheaper than scaling vertically

      • Easier to run fault-tolerance

      • Easy to upgrade

    • Cons

      • More licensing fees

      • Bigger footprint in the Data Center

      • Higher utility cost (Electricity and cooling)

      • Possible need for more networking equipment (switches/routers)


33. How you will do architect the application?
  • What are the non-functional requirements to the system and how the architecture reflects them,
  • What are the stakeholders development plans for the application and why the architecture do not hinder this development in the future,
  • What components are in the system and what are their responsibilities,
  • What are the interfaces and available connections between components,
  • What kind of technologies, standards and limitations are used to create the application.
34 How you will test different layers?

35. Javascript is statically type language?
 javascript is not a statically typed language.javascript is dynamically typed language.
36. can you assign the object to dynamic keyword?
yes.
37. What is dynamic keyword?
The dynamic type enables the operations in which it occurs to bypass compile-time type checking. Instead, these operations are resolved at run time. The dynamic type simplifies access to COM APIs such as the Office Automation APIs, and also to dynamic APIs such as IronPython libraries, and to the HTML Document Object Model (DOM).

dynamic is a new static type that acts like a placeholder for a type not known until runtime

38. When to use dyanamic keyword?
If you are dealing with an unknown or dynamic type, it is often necessary to communicate with it through Reflection. Reflective code is not easy to read, and has all the pitfalls of the dynamic type above. In this context, dynamic makes a lot of sense.

39.how to call derived function using base class object

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace Test

{



class Program

{

static void Main(string[] args)

{

Parent p = new Child();

((Child)p).GetNo();

Console.ReadLine();

}

}

class Parent

{

public void GetNo()

{

Console.WriteLine("1");

}

}

class Child : Parent

{

public Child()

{

}

public void GetNo()

{

Console.WriteLine(" 2");

}

}

}

40.Enterprise Architectural Patterns ?

Dependency Injection
Object Relational Mapper
Aspect Oriented Programming

41.Design Pattern for data import of various source types and to various destination types?
strategy or adapter

42. restricts the different classes creation?
43. 4+ 1 view model?
Logical view-end user, Physical view- system engineer , deployment view- developer, process view-integrator and scenario

44. Http context availability?

45. UI security and business layer security?

46.Where the session object will store normal scenario?
http://www.codeproject.com/Articles/32545/Exploring-Session-in-ASP-Net#11

47.App fabric ?

The Challenge

Setting up a hosting environment for an application that includes WCF- and WF-based services can be complex and time-consuming. While IIS/WAS provides a robust hosting environment for such applications, taking advantage of its features can require a considerable development effort, custom deployment solutions, and manual configuration procedures. Once a solution is deployed and configured, managing services can be a challenge.

The Solution

AppFabric Hosting Services enable you to get your WCF- and WF-based services up and running easily. You can take advantage of AppFabric’s hosting capabilities without developing additional hosting features. The Hosting Services extend the hosting capabilities of WAS by providing a default configuration of the WAS hosting environment. Hosting Services includes features provided by the Workflow Management Service, including lock/retry, auto-start, durable timers, and a command queue.
AppFabric Hosting Administration provides tools to manage your running workflow instances much more easily, with control, monitoring, and query capabilities. You can also configure WAS and the applications hosted within WAS in a standard way. The Hosting Administration tools enable you to configure the address of service endpoints, manage auto-start activation, and configure security and performance settings.
For more information on the hosting capabilities of AppFabric, see Hosting Concepts.

http://www.devtrends.co.uk/blog/asp.net-mvc-output-caching-with-windows-appfabric-cache

48.1000 users to  increase 5000 users concurrent users?
Ram need to increase.

49 Asp.net session object or your own sessions?

50. Dependency injunction?

You can inject class's of dependencies  into it, through a constructor or setter property. rather instance them in the class.

A dependency is an object that can be used a service. An injection is a passing of a dependency to dependent object(a client) that would use it.

Key points about DI

  1. Reduces class coupling
  2. Increases code reusing
  3. Improves code maintainability
  4. Improves application testing

http://www.dotnet-tricks.com/Tutorial/dependencyinjection/67LX120413-Implementation-of-Dependency-Injection-Pattern-in-C

  1. public interface IService
  2. {
  3. void Serve();
  4. }
  5.  
  6. public class Service : IService
  7. {
  8. public void Serve()
  9. {
  10. Console.WriteLine("Service Called");
  11. //To Do: Some Stuff
  12. }
  13. }
  14.  
  15. public class Client
  16. {
  17. private IService _service;
  18.  
  19. public void Start(IService service)
  20. {
  21. this._service = service;
  22. Console.WriteLine("Service Started");
  23. this._service.Serve();
  24. //To Do: Some Stuff
  25. }
  26. }
  27. class Program
  28. {
  29. static void Main(string[] args)
  30. {
  31. Client client = new Client();
  32. client.Start(new Service());
  33.  
  34. Console.ReadKey();
  35. }
  36. }
51 code first and database first differences?
https://www.simple-talk.com/dotnet/.net-framework/different-approaches-of-entity-framework/

Model First:

  • Good support with EDMX designer
  • We can visually create the database model
  • EF generates the Code and database script
  • Extensible through partial classes
  • We can modify the model and update the generated database.

Database First:

  • An existing database can be used
  • Code can be auto-generated.
  • Extensible using partial classes/ T4 templates
  • The developer can update the database manually
  • There is a very good designer, which sync with the underlining database

Code First:

  • There is full control of the model from the Code; no EDMX/designer
  • No manual intervention to DB is required
  • The database is used for data only


46. I want increase concurrent users 1000 to 5000 users , what i need to do?

Increase the RAM size if it same box.


47. when we will go for WEB API and WCF?


When to use WCF and when Web API
  1. If you want want to expose a service to the public and the same service you want to work on various protocols like Messaging Queue, TCP, Named Pipes or duplex communication go for WCF.
  2. If you want to create a service that supports HTTP and SOAP-based messaging, go for WCF.
  3. If you want to create a resource-oriented service over HTTP and use the full features of the HTTP protocol then go for the ASP.NET WEBAPI.
  4. If you want to access services based on URI and get a non-SOAP response like XML or JSON then go for ASP.NET WEBAPI.
  5. If you have an application developed in MVC and want to have a service to be exposed then go for the WEBAPI. Automated Testing of business logic will also be easy for services since controller is separated from the UI and Model.

  1. Unlike WCF Rest service, it use the full featues of HTTP (like URIs, request/response headers, caching, versioning, various content formats).
ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.

ROA (REST Oriented Architecture) is just a fancy name for a SOA (Service Based Architecture) using REST services.




48. What is signal R?
Real-time web functionality is the ability to have server code push content to connected clients instantly as it becomes available, rather than having the server wait for a client to request new data.

49. What is the difference between bridge and adaptor?
Adapter pattern is useful when you have existing code.

MemoryMappedFile and DirectReadFile types of file objects. Let's say you want to be able to read files from various sources (Maybe Linux vs. Windows implementations, etc.). Bridge helps you avoid winding up with:

Adapter starts from letter 'A' - map with After and Bridge starts from letter 'B' map with Before. Now when its Adapter its always to deal with the situation when some implementation is already in place and but some kind of hack or patch or connector to put between two separate functional elements to make it work, like the real (electric) adapter. Where in bridge - its before hand - design should be such that interface and implementation both are independent so abstraction is covered at interface level but actual implementation differs based on specific condition or need.

Simple example for Adapter its like middle-man between Person1 and Person2, where Person1 delivers data in xml format but Person2 accepts data in Json format, now middle-man adapter is responsible for converting data from xml to json. Hope its much clearer now.

The Adapter pattern is used so that two unrelated interfaces can work together. The joining between them is called an Adapter. This is something like we convert interface of one class into interface expected by the client. We do that using an Adapter.
----
Bridge pattern has nearly the same structure as the Adapter Pattern. But it is used when designing new systems instead of the Adapter pattern which is used with already existing systems.
Bridge-Structural
This pattern is used for decoupling an abstraction from its implementation so that the two can vary independently

http://www.c-sharpcorner.com/UploadFile/rajeshvs/BridgePatternsinCS11142005010604AM/BridgePatternsinCS.aspx



http://csharp-video-tutorials.blogspot.in/2018/01/bridge-design-pattern.html

Adapter:-Structural
Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible Adapter interfaces.

connecting to different data sources used adapter design patterns

51. What is checked?
The checked keyword is used to explicitly enable overflow checking for integral-type arithmetic operations and conversions
52 What is Unsafe?
The unsafe keyword denotes an unsafe context, which is required for any operation involving pointers.
53 What is Func?
Func in short is parameterized delegate. In C#, a delegate instance points towards a method. When a caller invokes the delegate, it calls its target method. This way, the caller is not invoking the target method rather invoking the delegate which can call the target method.
Action delegate?
Encapsulates a method that has no parameters and does not return a value.

Func is parameterized delegate
action delegate has no parameters and does not return a value.

https://msdn.microsoft.com/en-us/library/system.action(v=vs.110).aspx

54 What is action delegates?
They will not return any value.

55.How to remove the element from array?
delete array[2]

56. Can we write the javascript with out declaring the variables?
Yes

57. Eval safe or not in javascript?
Not safe

58.javascript asnycronous or syncrounous?
syncronous

59. voltile?
The volatile modifier is usually used for a field that is accessed by multiple threads without using the lock statement to serialize access.

https://msdn.microsoft.com/en-us/library/x13ttww7.aspx


60 code first or database first approach?

Existing database and existing classes go for Code first.
No Existing classes and exiting database then go for Database first.
No Existing database then go for Model first.

61.Finalizer method?
we can't call the finalize method directly.
we write the code for distractor, it will create the finalize method in the finalize queue.

62.Garbage collector life cycle?

once object is created that is generation one.
next Garbage collect will collected not used object. Reference objects moved to generation 1.
after some time again garbage collector will collect the not used objects and remaining objects moved to generation 2

https://www.youtube.com/watch?v=cZtgIwHLJmc

63. Can use the variable without using var keyword?
yes we can use those are global variables.

64. How the web request works?

1.Browser lookup ip address for domain name.
2.Browser sends http get request to web server
Route the request to the proper server
3.The facebook server responds with permanent redirect
4.Browser follow the redirect
5.The server handles the request
6.The server sends back to the html response
7.The server begins redering the html
8.The browser send the request for objects embeded in the html.
9.The browser sends forther async request

http://igoro.com/archive/what-really-happens-when-you-navigate-to-a-url/

65. What is data architecture?


to integrate data from different unrelated Data Sources.

66. What are the key points for architecture?
1.Identify arch objectives
2.identify key scnarios
3.create application overview.
4.identify key issues
5.define the solution


67. How you will find out session object is expires or not?

68. WCF service security?
TransportWithMessageCredential. Message protection and authorization occur at the transport level and credentials are passed with the message. You will use this in the sample application that demonstrates the third scenario (public Web-hosted service).

https://msdn.microsoft.com/en-us/library/ff406125.aspx

69. SSL and https?

http://www.codeproject.com/Articles/36732/WCF-FAQ-Part-security-related-FAQ

70.wcf binding?
By default, the wsHttpBinding binding provides HTTP communication.

71. Design patterns?


Creational Patterns
These design patterns provide a way to create objects while hiding the creation logic, rather than instantiating objects directly using new opreator. This gives program more flexibility in deciding which objects need to be created for a given use case.

Structural Patterns
These design patterns concern class and object composition. Concept of inheritance is used to compose interfaces and define ways to compose objects to obtain new functionalities.
(relationship)

Behavioral Patterns
These design patterns are specifically concerned with communication between objects.


72. What are the parameters to see to assign the design patterns?
Creational Patterns
Creational design patterns describe ways to create objects using methods that are appropriate for different situations. For example, the "Singleton" pattern is used to create a basic class that will only have one instance. A common example is a global variable defined in the source code of a program. An "Object Pool" pattern is used to create a class with a "pool" of objects that can be retrieved as needed instead of being recreated. This is often used for caching purposes.
2. Structural Patterns
Structural design patterns define the relationships between objects. For example, the "Private Class Data" pattern is used to limit access to a specific class. This can prevent unwanted modification of an object. The "Decorator" class, on the other hand, allows behaviors and states to be added to an object at runtime. This provides programmers with the flexibility to add as many classes to an object as needed. One example is an avatar in a video game that accumulates weapons, armor, and items throughout the game. The appropriately named "Decorator" class would provide a good framework for this process.
3. Behavioral Patterns
Behavioral design patterns describe the behavior of objects, such as the way they communicate with each other. One example is the "Command" pattern, which describes objects that execute commands. The "Memento" pattern records the state of an object so it can be restored to its saved stated. These two patterns can be used together to perform Undo and Redo operations in a program.
73. What are the architectural aspects you are doing?
74.Why web response is slow database query taking only 2 sec?
1. To many processes and connections
2.Memory leaks
3.External resource delays
4.Insufficient server resources

75. What is bundling?
76. What is yield?

You use a yield return statement to return each element one at a time.
You consume an iterator method by using a foreach statement or LINQ query. Each iteration of the foreach loop calls the iterator method. When a yield return statement is reached in the iterator method, expression is returned, and the current location in code is retained. Execution is restarted from that location the next time that the iterator function is called.

static IEnumerable
mylist contains 1,2,3,4,5
output 4,5



78. Web API security?
OWIN,OAUTH.

79. Action filters?
1.authorization filter
2.action filter
3.Result filter
4.Exception filter

80 Geo code architecture?
web service
based on IP distributed architecure

82.What are different web servers available for .net?

83. What is Tuple?
To return multiple values without using out parameter
To pass multiple values to a method through a single parameter.

Tuple is a generic static class that was added to C# 4 and it can hold any amount of elements, and they can be any type you want. To hold more than 8 elements you will need to nest tuple objects.



85. Multi cast delegate?
Multicast delegates provide functionality to execute more than one method.

Multicast delegate is a delegate that has references more than one function.
https://www.youtube.com/watch?v=7uJYp9NIhfQ


.
86.What are the architecture activities you will do?
1.Understanding the Business case
2.Creating or selecting the architecture
3.Documenting the architecture.

87.What is assembly? and types of assemblies?
An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality.
1.private assembly
2.Shared assembly

88. Context instances in WCF?
http://www.codeproject.com/Articles/86007/ways-to-do-WCF-instance-management-Per-call-Per

per call
per session
single





























































































  • Create a new WCF service instance on every WCF client method call.
  • Only one WCF service instance should be created for every WCF client session.
  • Only one global WCF service instance should be created for all WCF clients.

  • Per call

    • You want a stateless services.
    • Your service holds intensive resources like connection objects and huge memory objects.
    • Scalability is a prime requirement. You would like to have a scaled out architecture.
    • Your WCF functions are called in a single threaded model.

    Per session

    • You want to maintain states between WCF calls.
    • You a scaled up architecture.
    • Light resource references.

    Single

    • You want share global data through your WCF service.
    • Scalability is not a concern.

    89. IDisposable?
    to destroy unmanaged objects

    90. employee resign from the company intimate the vendor?
    wcf service msmq send the message in queue

    91. When we will go for transport and Message security?
    Use transport security in the following scenarios:
    • You are sending a message directly from your application to a WCF service and the message will not be routed through intermediate systems.
    • Both the service and the client are located in an intranet.
    Message Security
    Use message security in the following scenarios:
    • You are sending a message to a WCF service, and the message is likely to be forwarded to other WCF services or may be routed through intermediate systems.
    • Your WCF clients are accessing the WCF service over the Internet and messages may be routed through intermediate systems.

    Intranet Scenarios

    The following are the authentication types and bindings that can be used in a typical intranet scenario:
    • Windows authentication with netTcpBinding. By default, netTcpBinding uses Windows authentication and transport security. It uses the service account’s Windows identity token to provide message protection. The credentials are negotiated with the Security Support Provider Interface (SSPI).
    • Certificate authentication with netTcpBinding. By default, netTcpBinding uses transport security, which means you will have to configure the client credentials to use a certificate. To provide message protection at the transport level, you will have to configure a service certificate as service credentials. The certificate will negotiate a session key and service public key during the handshake, which will allow you to encrypt the content with the service certificate public key and sign the content with the private session key.

    Internet Scenarios

    The following are the authentication types and bindings that can be used in a typical Internet scenario:
    • Basic authentication with basicHttpBinding. By default, basicHttpBinding does not support any security, so you will need to configure the binding to use transport security. This is a good option when you want to support interoperability with non-WCF or non-Windows clients. In this scenario, you need to install a SSL certificate on IIS and then configure the virtual directory to require SSL. SSL will then negotiate a session key and service public key during the handshake, which will allow you to encrypt the content with the service certificate public key and sign the content with the private session key.
    • Certificate authentication with wsHttpBinding. By default, wsHttpBinding uses message security and Windows authentication, so you will have to configure the binding to use transport security and configure the client credentials to use the certificate. To provide message protection at the transport level, install an SSL certificate on IIS and configure the virtual directory to require SSL.


    93. What is app domain?

    Application domains provide a flexible and secure method of isolating running applications.
    Application domains are usually created and manipulated by run-time hosts. Occasionally, you may want your application to programmatically interact with your application domains, for example, to unload a component without having to stop your application from running.

    93. Selecting the design patterns?



    Builder-Creational
    Separate the construction of a complex object from its representation so that the same construction process can create Builder same construction process can create different representations.

    https://www.codeproject.com/Articles/470476/Understanding-and-Implementing-Builder-Pattern-in
    Domain driven approach

    Proxy-structural
    Provide a surrogate or placeholder for another object to control access to it.
    Proxy design patterns are 3 types
    1.Remote
    2.Virtual-it is like Cache
    3.Protaction




    Composete-Structural
    Compose objects into tree structures to represent part‐whole hierarchies. Composite lets clients treat individual Composite objects and compositions of objects uniformly.

    Decorator-Structural
    Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

    Assign more functionality to an object without sub classing.

    For sealed class we need to use decorator.

    Legacy systems not implemented the validation, we can use decorator pattern implement validation.
    open-closed principle followed 

    Facade-structural
    Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher‐level interface that makes the Façade subsystem easier to use.

    Chain of responsibility-Behavioral
    Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the Chain of Responsibility request along the chain until an object handles it.

    Command-Behavioral
    Encapsulate a request as an object, Command thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.



    Flyweight-structural
    Pattern Use sharing to support large numbers of Flyweight.Use sharing to support large numbers of fine‐grained objects efficiently.

    Interpreter-Behavioral
    Given a language, define a representation for its grammar along with an interpreter Interpreter that uses the representation to interpret sentences in the language.

    Iterator-Behavioral
     Provide a way to access the elements of Iterator an aggregate object sequentially without exposing its underlying representation.

    Medaitor-Behavioral
     Define an object that encapsulates how a Mediator set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.

    Memento:-Behavioral
    Pattern Without violating encapsulation capture Memento.Without violating encapsulation, capture and externalize an object's internal state so that the object can be restored to this state later.

    Observer-Behavioral
     Define a one‐to‐many dependency between objects so that when one object changes state, all its dependents are  Observer notified and updated automatically.




    State-Behavioral
    Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.


    Strategy-Behavioral


    • defines a family of algorithms,
    • encapsulates each algorithm, and
    • makes the algorithms interchangeable within that family.


    Template-Behavioral
    Define the skeleton of an algorithm in an operation, deferring some steps to subclasses Template Method lets Template Method subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.

    Visitor-Behavioral
    Pattern Represent an operation to be performed VisitorRepresent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the Visitor elements on which it operates.

    94. what are the dlls are required for MEF?
    system.componetmodel.composition;
    system.componetmodel.composition.hosting;

    95.What are the dlls required for run time loading the assembly?
    system.reflection

    96. SOAP vs REST?
    REST follows stateless model. SOAP has specifications for stateful implementation as well.

    97.What is OAUTH?
    OAuth is an open standard for authorization

    SOAP uses interfaces and named operations to expose business logic. REST uses (generally) URI and methods like (GET, PUT, POST, DELETE) to expose resources.

    98. Advantages of SOA?
    service reuse
    99. when we will go for JSON?

    JSON as an alternative to XML for conveying data.
    The advantage is that it is more compact.
    The disadvantages are that it is less verbose and you can't validate the data set with a schema (XSD/DTD)

    So I would prefer it where the size of the message being sent is of critical importance to the end-user, like:
    - mobile apps getting data from servers . The internet traffic on GSM networks is still quite expensive.
    - sending data to embedded systems via wireless networks (remotely controlled robots)
    - improve web based application's response time (although there are a lot of other methods to achieve that)

    100 What is solid? and Interface segregation principle?
    S-Single responsibility
    O-Open for extension closed for modification
    L-Liskov substituion principle.-Derived classes must be substituable for their base classes
    • Bank bank = new Bank();
    • Account acc = new Account(1);//bse class
    • bank.Withdraw(acc, 100);

    • Account saving = new SavingAccount(2);//derived class
    • bank.Withdraw(saving, 100);
    I-Interface segregation principle
    D-Dependecy Inversion Principle.

    http://javiernavarromachuca.blogspot.hk/2011/07/interface-segregation-principle.html
     101. Smart meter data who the .net read the data?
    Radio frequency
    102.How to configure the SSL in IIS?

    103. MEF How it will work, if you remove the dll from reference?

    104.Architectural principles?
    Stability
    General Scope
    Comprehensibility
    Coherence
    105. What are the tools we can use before start of the project?
    106. if you given requirement what are the parameters you look?
    select the refrence model, view points and tools
    define the scope
    Identify the risks
    resolve the impacts
    Finalize application architecture
    Create architecture document
    identify the key drivers
    define the archectural principles
    define framework to be used
    defining relationshipt between managements framework
    Impact assessment
    GAP Analysis
    Determin applicaiton type.
    Architecutre vision,Business Architecture,Technology architecture,

      107. Nonfunctional requirements how will change based on application?
      108.Performance how will  improve?
      connection pooling
      load balancing
      caching
      replication of data

      1.Make fewer http requests
      2.Use content delivery network(Akamai-nearest server)
      3.Add an expires header
      4. Gzip component
      5.put css on the top
      6.Move javascript to the bottom
      7.Avoid css expressions
      8.Make javascripts and css external
      9.Reduce DNS lookups
      10.Minify javascripts
      11.Avoid redirects
      12.Remove duplicate scripts
      13.Configure Etags.



      109.Review the existing architecture?What are parameters you look?
      functional requirements and non functional requirements.
      performace
      relability
      availbility
      security
      extensibility
      scalbility
      interability








      110. interface vs abstract?
      When creating a class library which will be widely distributed or reused—especially to clients, use an abstract class in preference to an interface;
      111.Abstract factory design pattern where/when u implemented?
      The object needs to be extended to sub classes.
      The classes doesn't know what exact sub classes it has to create.
      The Product implementation tend to change over the period of time and client remains unchanged.
      112. What is the current application architecture?
      113.What integration do you have done?
      114.What solution you are provided?
      115. How to check duplicate content from idea posted?
      116. Load test 3000 users?
      117. Login sequence diagram?
      118. Top 5 valunearbility?
      Cross site scripting:if you are using html.raw XSS possiable. Anti xss library default added in .net 4.5
      Cross site request forgery:to mitigate this risk, we can add randomness vis CSRF token
      Security misconfiguration
      Insecure Direct object reference
      Injection:Use ORMs (Like Entity framework)
      LDAP injection
      Xpath injection
      Dynamic Linq injection
      Http session and cookies
      119.Http is stateless or stateful?
      Http is stateless protocol.
      120.Auxiliary items in sequence diagram of login?
      121.Performace through put how to check for 3000 users?
      122 Performace optimization?

      Code optimization
      Cache strategy
      Load balancing

      Hardware,Design,Database and application areas
      External Service responses
      3rd party dlls
      avoid

      foreach instead of for
      resource clean close->close connections
      string management->string builder

      Boxing

      Caching
      Load balancing

      123.Isolate the problem where it is?
      web.config file configure for production environment.
      124.Concurrency?
      Transactions,locks,Threading,Queuing
      125,Factory Method Class diagram?
      126.What are the tools used?
      127.Metrics tool what is difference exiting tool my tool?
      128.What is the standard response for web page?
      5 secs
      129. Top 5 code reviews?
      Closing database connections
      inline query or stored procedures

      130.Troughput?
      Throughput is the number of requests that can be served by your application per unit time

      The no of quieres that can be run in any time peroid.
      e.g.queries for second
      131. Upto what normalization we have to do?
      up to 3NF
      132. Two stake holders they are havind differenct views how to resolve?
        A process called rethinking the requirements – by going back the sources of the conflicting requirements and tries to understand and address it differently.
      - Getting all the stakeholders in one place and make them discuss and analyzing the trade-offs among the conflicting requirements and come up with prioritization process in terms of, value to the project, cost, time, etc.
      - The best technique I know for working with functional requirements for software systems is known from Rational Unified Process and is named use-case workshop. You can invite stakeholders for this kind of meeting and create use-case diagram for the whole system, introduce short use-case descriptions and then detail the use-case descriptions. This is an iterative process, so you need several meetings of this kind. You can share your desktop in case of distributed team. I used this technique several times - always successfuly.
      133. When to use Entity framework?
      small application
      134. How do measure the performace?
      Response Time,Troughput,Resource utilization,Work load Performace objectives.
      135. Dynamic metrics?
      136.Advantages and disadvantages of Entity framework?
      performace impact when u r using EF.
      137.Architectural patterns?
      • Client server architectural pattern/style->deployment
      • Domain driven architural pattern/style-->domain
      An object-oriented architectural style focused on modeling a business domain and defining business objects based on entities within the business domain.
      • Layered Architectural pattern/style->structure
      • N tier architectural pattern/style-->depolyment
      • Service oriented architetural pattern/style-->Communication
      Refers to applications that expose and consume functionality as a service using contracts and messages.

      138. MVP and MVC?
      http://architects.dzone.com/articles/how-not-fall-trap-using-mvc-or

      139.Automatic deployment?

      using TFS

      http://www.asp.net/web-forms/overview/deployment/configuring-team-foundation-server-for-web-deployment/deploying-a-specific-build

      140. Have you done any reference model architecture?
      http://razsoftcanada.com/architecture.html#prettyPhoto

      141. Multi server deployment what are the measures taken care?
      142. Have you done any framework ?
      143 performance measurements?
      Response Time, Throughput, Resource utilization
      Resource utilization: CUP, Memory, network I/O, disk
      144.Database tuning?
      1.Indexing
      2.Query optimization
      3.Table Partition
      4. De-normalization
      5.Query caching

      145. What is the advantage calling the external application from business layer?


      • Support for interaoperability.
      • Application façade. This optional component typically provides a simplified interface to the business logic components, often by combining multiple business operations into a single operation that makes it easier to use the business logic. It reduces dependencies because external callers do not need to know details of the business components and the relationships between them. 
      146. I have external application reporting application is there what are ways we can call the external application?
      In this scenario, users can access the application through the presentation layer, which communicates either directly with the components in the business layer; or through an application façade in the business layer if the communication methods require composition of functionality. Meanwhile, external clients and other systems can access the application and make use of its functionality by communicating with the business layer through service interfaces. This allows the application to better support multiple client types, and promotes re-use and higher level composition of functionality across applications.

      147.Pen having multiple properties how you will creates tables based on what?
      frequently used
      148.Code first migration history purpose?
      149. I have modifed the column how can I change the changes in production database in EF?
      update-database

      150 Multiple databases temp variable will it work?
      151. Publish and Subscriber pattern?

      You have an integration architecture consisting of several applications. A communication infrastructure connects these applications in a bus, broker, or point-to-point topology. Some applications send multiple message types. Other applications are interested in different combinations of these types.

      For example, consider a financial system where several applications maintain customer information. A Customer Relationship Management (CRM) application holds the master customer information. However, a typical situation for integration scenarios exists—customer information also resides in other systems that perform their own customer information management functions. A customer-facing application generates update messages for changes to customer information, such as changes to customer addresses. The messages must reach the CRM application as well as the other applications that manage customer information. However, this message type is meaningless to the integrated applications that do not manage customer information.

      152.Brokerage service in database?

      153.MCV architecture and 3 tier architecture difference?

      At first glance, the three tiers may seem similar to the model-view-controller (MVC) concept; however, topologically they are different. A fundamental rule in a three tier architecture is the client tier never communicates directly with the data tier; in a three-tier model all communication must pass through the middle tier. Conceptually the three-tier architecture is linear. However, the [model-view-controller] MVC architecture is triangular: the view sends updates to the controller, the controller updates the model, and the view gets updated directly from the model

      154. Types of caching? use?
      1.Output caching and Application caching.


      • Page output caching should be used when we want to cache complete web pages based on some criteria and for some specific time.
      • Application caching should be used when we want to cache custom objects to use later.
      • Application caching provides a lot of parameters to customize its behavior to have more fine grained control. 
      155.Page life cycle?
      Page request ,Start,Initialization,Load, Postback event handling,redering, Unload.
      156. Page life cycle events?
      preinit,init,init complete,
      preload,load,control events,Load completed
      prerender,savestatecomplete,render
      unload.
      157. Integration architecture?
      158. WSDL structure?
      159.C# architecture?

      160. Lift ,building and people UML relationships?

      161. ecommerece in between payment failure?
      162. In between configuration change?
      163. Tenent Architecture?

      Multi-tenancy is an architecture in which a single instance of a software application serves multiple customers. Each customer is called a tenant.
      164. OWIN & Katana Service?
      OWIN-Open web interface for .Net. OWIN defines a standard interface between .Net web servers and web applications.The goal of the OWIN interface is to decouple the server and applications, encourage the development of simple modules for .NET web development and, by being an open standard, stimulate the open source ecosystem of .NET web development tools.


      Let's try to understand what this definition is trying to convey here. Until now the developers have mainly focused on decoupled application code by creating multiple layers in the applications that interact with the use of interfaces, use design patterns, S.O.L.I.D. principles and so on. But O.W.I.N. is a step above the code decoupling. It is aimed at decoupling the application and the web-server, that hosts the application. Using such kinds of decoupled architecture allows:
      1. Creating middleware components that can be replaced in or added into the application without affecting the other components in the application
      2. Remove the dependency of the web server to host a component, by promoting the use of self-hosting
      OWIN is a specification and Katana is Microsoft's open source project that uses these specifications.

      http://www.c-sharpcorner.com/UploadFile/b1df45/owin-and-katana-interfaces-of-Asp-Net/


      165.Identity service?

      166. What is sticky session?

      When you load balance your ASP.Net application(or any web application), the sticky session ensures that all the subsequent request will be send to the server who handled the first request corresponding to that request.

      StateServer mode stores session state in a process, referred to as the ASP.NET state service, that is separate from the ASP.NET worker process or IIS application pool. Using this mode ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm. To use StateServer mode, you must first be sure the ASP.NET state service is running on the server used for the session store. The ASP.NET state service is installed as a service when ASP.NET and the .NET Framework are installed.


      
        
           mode="StateServer"
            stateConnectionString="tcpip=SampleStateServer:42424"
            cookieless="false"
            timeout="20"/>
        

      167. What is non sticky session?

      In a non-sticky session configuration, each request is independent of previous requests and may be routed to any of the servers in the pool for processing.

      168. Software load balancing?

      Network Load Balancing
      Hardware Load Balance using F5

      169.Windows server 2008 fail over cluster?

      https://www.youtube.com/watch?v=dONG4NWcgpE

      170. When to use Prototype design pattern?
      http://www.dotnettricks.com/learn/designpatterns/prototype-design-pattern-dotnet

      An object is to be created after a costly database operation. We can cache the object, returns its clone on next request and update the database as and when needed thus reducing database calls.

      Prototype-- clone

      Design Patterns in .Net. It is used to used to create a duplicate object or clone of the current object. It provides an interface for creating parts of a product.

      171. What is application pool identity?

      create the application pool associate with web application.

      Application pools are used to separate sets of IISworker processes that share the same configuration and application boundaries. Application pools used to isolate our web application for better security, reliability, and availability and performance and keep running without impacting each other .

      https://www.youtube.com/watch?v=O-ATIKcu0ME&list=PL6n9fhu94yhXQS_p1i-HLIftB9Y7Vnxlo&index=84















































                Saturday, March 30, 2013

                SQL Server & Oracle Interview questions

                1.Do you know Boyce Code normal form?

                2.What is global temp table?


                Local temporary tables are visible only to their creators during the same connection to an instance of SQL Server as when the tables were first created or referenced. Local temporary tables are deleted after the user disconnects from the instance of SQL Server.

                 Global temporary tables are visible to any user and any connection after they are created and are deleted when all users that are referencing the table disconnect from the instance of SQL Server

                3.Identity and scope identity?

                identity
                It returns the last identity value generated for any table in the current session, across all scopes.
                scope identity
                It returns the last identity value generated for any table in the current session and the current scope.

                The Sales.Customer table has a maximum identity value of 29483. If you insert a row into the table, @@IDENTITY and SCOPE_IDENTITY() return different values.

                SCOPE_IDENTITY() returns the value from the insert into the user table, whereas @@IDENTITY returns the value from the insert into the replication system table.

                 Use SCOPE_IDENTITY() for applications that require access to the inserted identity value.

                4.What is Merge in SQL server?

                MERGE Production.ProductInventory AS target
                USING (SELECT ProductID, SUM(OrderQty) FROM Sales.SalesOrderDetail AS sod
                    JOIN Sales.SalesOrderHeader AS soh
                    ON sod.SalesOrderID = soh.SalesOrderID
                    AND soh.OrderDate = @OrderDate
                    GROUP BY ProductID) AS source (ProductID, OrderQty)
                ON (target.ProductID = source.ProductID)
                WHEN MATCHED AND target.Quantity - source.OrderQty <= 0
                    THEN DELETE
                WHEN MATCHED
                    THEN UPDATE SET target.Quantity = target.Quantity - source.OrderQty,
                                    target.ModifiedDate = GETDATE()

                5 Can we update the views?

                6. Table types?

                1.Temporary Tables
                2.Table Variables
                3.Derived Table


                7. Full outer join and cross join?


                8. Why only one cluster index?

                A clustered index sorts and stores the data rows in the
                table based on the index key values. Therefore only one
                clustered index can be created on each table because the
                data rows themselves can only be sorted in one order.

                9 Increase the performance in stored procedure?

                1. Keep database object name short, meaningful and easy to remember ( useful for easy maintenance).

                2. Normalize data at least up to 3rd form but not at the cost of query performance. Denormalization up to small extent can boost query performance.

                (e.g. Suppose you have 3 columns ItemID, Quantity, Rate in a table (let us call it as ItemStock table). While generating a report with the total, we need to multiply Quantity with Rate. Instead, we can add a total column in the table and store the total over there.

                3. Do not use that column in the select statement which are not required. Never user select * statement.

                4. Use SP to fetch data and try to avoid program logic in SP. Logic has to be written at the application level and not at the database level. Always use 'set-based approach' instead of a 'procedural approach' for accessing and manipulating data.

                5. Use the primary key in the table to filter the data in where clause. Use execution plans to analyze the query. Make sure your queries do an "Index seek" instead of an "Index scan" or a "Table scan." A table scan or an index scan costs more and takes more time for execution. Choose the right indexes on the right columns.

                6. Use SET NOCOUNT ON at the beginning of your stored procedures, as this suppresses messages like '(1 row(s) affected)' after executing INSERT, UPDATE, DELETE, and SELECT statements. This improves the performance of stored procedures by reducing network traffic.

                7. Also, avoid searching using not equals operators (<> and NOT) as they result in table and index scans.

                8. Use table variables instead of temporary tables.

                9. 'Derived tables' as they perform better than subqueries

                Select Max(Quantity)
                From ItemStock
                Where ItemID in
                (
                Select
                Top 2 ItemID
                From ItemStock
                Order By Quantity Desc
                )
                Same can be written using derived table

                Select Max(Quantity)
                From
                (
                Select
                Top 2 Quantity
                From ItemStock
                Order by Quantity Desc

                ) as A

                10.Don't use Having clause.
                11.Try to minimize no of sub queries.

                http://beginner-sql-tutorial.com/sql-query-tuning.htm


                10.Advantages Stored procedure?

                11 Merge

                Though Execution Plan Retention and Reuse


                •Conditionally insert or update rows in a target table.

                If the row exists in the target table, update one or more columns; otherwise, insert the data into a new row.

                •Synchronize two tables.

                Insert, update, or delete rows in a target table based on differences with the source data.

                MERGE dbo.Departments AS d
                USING dbo.Departments_delta AS dd
                ON (d.DeptID = dd.DeptID)
                WHEN MATCHED AND d.Manager <> dd.Manager OR d.DeptName <> dd.DeptName
                    THEN UPDATE SET d.Manager = dd.Manager, d.DeptName = dd.DeptName
                WHEN NOT MATCHED THEN
                    INSERT (DeptID, DeptName, Manager)
                        VALUES (dd.DeptID, dd.DeptName, dd.Manager)
                WHEN NOT MATCHED BY SOURCE THEN
                    DELETE
                OUTPUT $action,
                       inserted.DeptID AS SourceDeptID, inserted.DeptName AS SourceDeptName,
                       inserted.Manager AS SourceManager,
                       deleted.DeptID AS TargetDeptID, deleted.DeptName AS TargetDeptName,
                       deleted.Manager AS TargetManager;

                12. Rank?
                SELECT a1.Name, a1.Sales, COUNT(a2.sales) Sales_Rank


                FROM Total_Sales a1, Total_Sales a2

                WHERE a1.Sales <= a2.Sales or (a1.Sales=a2.Sales and a1.Name = a2.Name)

                GROUP BY a1.Name, a1.Sales

                ORDER BY a1.Sales DESC, a1.Name DESC;

                13. 2nd lowest value?




                select top 1 * from tbl_Customer touter where touter.Amount > (SELECT

                min(tinner.Amount) FROM [Customer].[dbo].[tbl_Customer] as

                tinner) order by touter.Amount asc

                14.Nth salary

                3rd highest salary

                    SELECT Salary,EmpName FROM
                   ( SELECT Salary,EmpName,ROW_NUMBER() OVER(ORDER BY Salary) As RowNum
                      FROM EMPLOYEE ) As A
                    WHERE A.RowNum IN (3)

                SELECT *

                FROM Employee Emp1

                WHERE N-1 = (

                SELECT COUNT(DISTINCT(Emp2.Salary))

                FROM Employee Emp2

                WHERE Emp2.Salary > Emp1.Salary)

                15. How big the database you are working?
                16. How critical is the database?
                Cluster, Database Recovery
                17. What is the company standard on virtual?
                18. Why a virtual Server?
                19. Error handling in SQL Server?
                20. Integration of a .net compliant language such as C#, ASP.Net?
                21. Encryption in SQL Server 2000?
                No option built-in expensive third party options.
                22. What is join?
                Joins combine records from two or more table in a database.
                23. Types of joins?
                Inner join, left outer join, right outer join, full outer join and self join.
                24.What is Inner Join?
                An Inner join creates a new result table by combining column values of two tables (A and B) based upon the join predicate. The query compare each row of A with each row of b to find all pair of rows which satisfy the join predicate. When join predicate is satisfied column value of each matched pair of rows of A and B are combined into a result row. Intersection.
                25. What is Left Outer Join?
                All the records of the left Table(A) even if the join condition  does not find any match record in the right table(B). This means that of on clause matches '0' record in B, the join will still return 0 row in the result but with null in each column of B.

                26. What is the cursor?

                Cursors (Transact-SQL) Microsoft SQL Server statements produce a complete result set, but there are times when the results are best processed one row at a time. Opening a cursor on a result set allows processing the result set one row at a time.

                27.Execute and executeSQL difference?

                Use SP_EXECUTESQL rather than EXEC(), it has better performance and improved security.

                sp_executesql gives you the possibility to use parameterised statements,

                28.Dynamic Columns?

                29.What is Unique key?
                A unique key must uniquely identify all possible rows that exist in a table. Uniquely identify each row in a table. Unique key column may or may not be null.

                30.Active employees query?
                select empid from employee1 where resignationdate < '2012-07-02' or resignationdate is NULL

                31. Inactive employees query?
                select empid from employee1 where resignationdate > '2012-07-02' or resignationdate <> NULL

                32.dept wise emp strength?

                select deptno, COUNT(*) from emp where to_date is null or to_date < '2004-02-21'  group by deptno33.

                33.Less designation employees?

                select deptno, COUNT(emp.deptno) from emp where to_date is null or to_date < '2004-02-21'  group by deptno having COUNT(emp.deptno) <3 br="">

                34.Performance?

                http://msdn.microsoft.com/en-us/magazine/cc163854.aspx

                Performance on the Data Tier
                Tip 1—Return Multiple Resultsets
                Tip 2—Paged Data Access
                Tip 3—Connection Pooling
                Tip 4—ASP.NET Cache API
                Tip 5—Per-Request Caching
                Tip 6—Background Processing
                Tip 7—Page Output Caching and Proxy Servers
                Tip 8—Run IIS 6.0 (If Only for Kernel Caching)
                Tip 9—Use Gzip Compression
                Tip 10—Server Control View State


                35.Query optimization?

                http://www.toptal.com/sql/sql-database-tuning-for-developers

                36.Cluster index structure?























              • Clustered
                • Clustered indexes sort and store the data rows in the table or view based on their key values. These are the columns included in the index definition. There can be only one clustered index per table because the data rows themselves can be sorted in only one order.
                • The only time the data rows in a table are stored in sorted order is when the table contains a clustered index. When a table has a clustered index, the table is called a clustered table. If a table has no clustered index, its data rows are stored in an unordered structure called a heap.
              • Nonclustered
                • Nonclustered indexes have a structure separate from the data rows. A nonclustered index contains the nonclustered index key values and each key value entry has a pointer to the data row that contains the key value.
                • The pointer from an index row in a nonclustered index to a data row is called a row locator. The structure of the row locator depends on whether the data pages are stored in a heap or a clustered table. For a heap, a row locator is a pointer to the row. For a clustered table, the row locator is the clustered index key.
                • You can add non-key columns to the leaf level of the nonclustered index to by-pass existing index key limits, 900 bytes, and 16 key columns, and execute fully covered, indexed, queries. For more information, see Create Indexes with Included Columns.

              • 37. What is B-Tree?
                38. Correlated queries?

                In an SQL database query, a correlated subquery (also known as a synchronized subquery) is a subquery (a query nested inside another query) that uses values from the outer query. The subquery is evaluated once for each row processed by the outer query.
                Here is an example for a typical correlated subquery. In this example, we are finding the list of all employees whose salary is above average for their departments.

                 SELECT employee_number, name
                   FROM employees AS Bob
                   WHERE salary > (
                     SELECT AVG(salary)
                       FROM employees
                       WHERE department = Bob.department);
                39.Self Join?
                A table can be joined to itself in a self-join.

                40 what is the deference where and having?

                41. Multiple databases how will maintain the transactions?

                the business layer we need to write the code.

                using (TransactionScope scope = new TransactionScope())
                  {
                     ... Do Stuff with Connection 1 using SqlDataReader
                     ... Do Stuff with Connection 2 using Entity Framework
                     ... Do Stuff with Connection 3 on another Oracle Database
                     ... And for good measure do some stuff in MSMQ or XA or DTC resource
                     scope.Complete(); // If you are happy
                  }

                42. Left JOIN and LEFT outer join difference?

                LEFT JOIN and LEFT OUTER JOIN ARE THE SAME
                RIGHT JOIN and RIGHT OUTER JOIN ARE THE SAME

                43. What is the difference between stored procedure and function?

                Basic Difference


                1. The function must return a value but in Stored Procedure it is optional( Procedure can return zero or n values).
                2. Functions can have only input parameters for it whereas Procedures can have input/output parameters.
                3. Functions can be called from Procedure whereas Procedures cannot be called from Function.

                Advance Difference


                1. The procedure allows SELECT as well as DML(INSERT/UPDATE/DELETE) statement in it whereas Function allows the only SELECT statement in it.
                2. Procedures can not be utilized in a SELECT statement whereas Function can be embedded in a SELECT statement.
                3. Stored Procedures cannot be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section whereas Function can be.
                4. The most important feature of stored procedures over function is to retention and reuse the execution plan while in case of the function it will be compiled every time.
                5. Functions that return tables can be treated as another row set. This can be used in JOINs with other tables.
                6. Inline Function can be though of as views that take parameters and can be used in JOINs and other Rowset operations.
                7. An exception can be handled by try-catch block in a Procedure whereas try-catch block cannot be used in a Function.
                8. We can go for Transaction Management in Procedure whereas we can't go in Function.
                44.Rename the database?
                1. In Object Explorer, connect to an instance of the SQL Server Database Engine, and then expand that instance.
                2. Make sure that no one is using the database, and then set the database to single-user mode.
                3. Expand Databases, right-click the database to rename, and then click Rename.
                4. Enter the new database name, and then click OK.
                45.Database tuning?


                1.Apply proper indexing in the table column in the database.
                2.Create appropriate covering index.

                create index salesProductidIndex on Sales(productid)
                include(salesdate,salesperson)

                10.Organize filegroups and files in the database.

                • The primary file group must be totally separate, and should be left to have only system objects, and no user defined object should be created on the primary file group. Also, the primary file group should not be set as the default filegroup. Separating the system objects from other user objects will increase performance and enhance the ability to access tables in cases of serious data failures.
                • If there are N physical disk drives available in the system, then try to create N files per file group and put each one in a separate disk. This will allow distributing disk I/O load over multiple disks, and will increase performance.
                • For frequently accessed tables containing indexes, put the tables and the indexes in separate file groups. This would enable reading the index and table data faster.
                • For frequently accessed table containing Text or Image columns, create a separate file group and put the text, next, and image columns in that filegroup on different physical disks, and put the tables in a different file group. This would enable faster data retrieval from the table with queries that don't contain text or image columns.
                • Put the transaction log file on a different physical disk that is not used by the data files. The logging operation (Transaction log writing operation) is more write-intensive, and hence it is important to have the log on the disk that has good I/O performance.
                • Consider assigning "Read only" tables into a file group that is marked as "Read only". This would enable faster data retrieval from these read-only tables. Similarly, assign "Write only" tables in a different file group to allow for faster updates.
                • Do not let SQL Server fire the "Auto grow" feature too often because it is a costly operation. Set an "Auto grow" increment value so that the database size is increased less frequently (say, once per week). Similarly, do not use the "Auto shrink" feature for the same reason. Disable it, and either shrink the database size manually or use a scheduled operation that runs in a timed interval (say, once a month).
                2.Apply partition for big fat tables.
                3.Defragment indexes if fragment occurs
                create maximum 5 indexes per table, if warehouse create 10 indexes per table.

                4.Move inline sql from application to database.
                5.optimize the sql.

                • don't use select *, avoid unnecessary table joins
                • Don't use count() aggregate function in a subquery to do an exitance check.
                • try to avoid joining two types of columns



                SELECT column_list FROM small_table, large_table WHERE
                smalltable.float_column = large_table.int_column .
                
                
                • try not to use Count(*)
                • try to avoid use of temp tables rather use table variables
                  • table variables reside in the memory
                  • temp table reside in tempdb
                • try not to use OR in the query, use union all
                • implement the user defined functions. do not call functions within stored procedures
                • Try to avoid use of triggers
                • Use schema name with object name
                  • SELECT FROM dbo.MyTable -- Preferred method -- Instead ofSELECT FROM MyTable -- Avoid this method
                • Don't use prefix SP_ in the stored procedures
                • Use if exists instead of select *
                  • if exists(select 1 from sysobjects where name='mytable'and type='U')
                • Use sp_executesql instead of exec
                  • DECLARE @Query VARCHAR(100)DECLARE @Age INT SET @Age 25SET @Query 'SELECT * FROM dbo.tblPerson WHERE Age = ' +CONVERT(VARCHAR(3),@Age)EXEC (@Query)
                  • DECLARE @Query NVARCHAR(100)SET @Query N'SELECT * FROM dbo.tblPerson WHERE Age = @Age'EXECUTE sp_executesql @QueryN'@Age int'@Age 25
                • Try avoid cursors
                • Use try catch for error handling
                • Avoid corelated subquires
                • SELECT c.Name, 
                         c.City,
                         (SELECT CompanyName FROM Company WHERE ID = c.CompanyID) AS CompanyName 
                  FROM Customer c
                • SELECT c.Name, 
                         c.City, 
                         co.CompanyName 
                  FROM Customer c 
                   LEFT JOIN Company co
                    ON c.CompanyID = co.CompanyID
                6.Apply denormalization

                OLTA-online transaction analytical system-->data ware housing
                OLTP-online transaction processing system

                46. difference between 2000,2005,2008?

                http://www.c-sharpcorner.com/Blogs/15967/differences-between-sql-server-2005-2008-2008r2-2012.aspx

                47. Table variable?

                As a rule of thumb, for small to medium volumes of data and simple usage scenarios you should use table variables.

                48. How to call the functions in stored procedures?
                Select @result=FunctionAdd(@a1,@b2)

                49.Common table expression?


                With T(Address, Name, Age)  --Column names for Temporary table
                AS
                (
                SELECT A.Address, E.Name, E.Age from Address A
                INNER JOIN EMP E ON E.EID = A.EID
                )
                SELECT * FROM T  --SELECT or USE CTE temporary Table
                WHERE T.Age > 50
                ORDER BY T.NAME
                
                

                50 Hit ration?


                51.In memory database when to use?



                  Oracle



                1.In which scenario used cluster index and non cluster index?
                If table have more insert, delete ,update we have to user cluster index.
                Cluster index can be user for frequent used queries.
                It can be used range queries like between , <=,>
                Used return large result set.
                Used join clause, typically these are foreign key column.
                Used order by or group by clause
                An unique or contain may distinct values
                Are accessed sequentially

                Non Cluster index 
                Table with low update requirements, but large values of data can benefit from may non cluster index used.
                Decision support system application that contain primarily read only data can be benefit from many non clustered index.
                Queries that don't return large result sets.
                Contain columns frequently involved in search condition of a query.


                2. I have two databases one database success another database fail how will you handle this scenario?
                The best way is to copy the data in a single place. Use a scheme which allows you to abort the copy and continue it at any time (for example, ignore data which you already have or order the select by ID and request only records > MAX(ID) of your copy). Protect this with a transaction. This is not a problem since you're only reading data from the source, so when the transaction fails for any reason, you can ignore the source database. Therefore, this is a plain old single source transaction.
                After you have copied the data, process it locally.

                3.Which Authentication used?

                4.Table lock which isolation Level user?

                SERIALIZABLE - lock on full table(on which Select query is fired). This means, B reads the data and no other transaction can modify the data on the table. This is the most secure but slowest way to work with data. Also, since a simple read operation locks the table, this can lead to heavy problems on production: imagine that T table is an Invoice table, user X wants to know the invoices of the day and user Y wants to create a new invoice, so while X executes the read of the invoices, Y can't add a new invoice (and when it's about money, people get really mad, specially the bosses).

                5. I lack of records How will retrieve from database?

                6.How to you increase the performance of stored procedure?
                Set Nocount on-> No of rows effected will not return to sql statement.

                7.Whar are advantages of stored procedure?

                Stored procedure reduced network traffic
                Procedure execution plans can be reused.
                stored procedure help promote code reuse
                procedure can encapsulate logic
                procedure provides better security to your data
                you can change stored procedure code without affecting clients

                8.sql query tuning?
                http://beginner-sql-tutorial.com/sql-query-tuning.htm