Thursday, July 30, 2015

ASP.Net Questions, C#.net and .net 4 interview Questions

1. Page life cycle in ASP.NET with explanations.

2. If there are multiple Master pages in any website and we want to apply those dynamically which 

3. What is server and client side validation.

4. What is state management, server side and client side validations.

Client Side: Cookie, Viewstate, Control states, QueryString, hidden fields

Server Side: Session, Application variables, Cache

5. Can viewstate be used for one page to another. (No)

6. Can we disable viewstate for Page. (Yes)

7. What is InProc, outProc and DB sessions 

8. How you can use QueryString in pages, what is HTML.Encode and HTML.Decode

9. Diff b/w Server.Transfer and Response.Redirect.

10. What is Interface. Where we can use interface why its import.

11. What is Abstract class. Diff b/w Abstract class and interface.

13. By default Class is public, private? (Private)

14. Diff b/w web.config and machine.config

16. Validation controls in asp.net (Required, Range, compare, regular, custom and validation 

18. Diff b/w User and Custom Control.

19. What are differences between system.stringbuilder and system.string?

20. Is it possible to set the session out time manually? Yes we can set the session out time manually 

23. Diff b/w Connected & Disconnected Archi

24. Try, catch & Finally block. Can we have multiple catch with one try if yes then which one will 

27. What is MVC. Explain MVC architecture

28. What is WCF. Explain ABC in WCF

29. What is Caching, types of caching.

30. New features of .net and which you used.

32. What is anonymous type .Var keyword vs dynamic

33. How to kill session. Session.Abandon

34. What is collection. Diff b/w HashTable & Dictionary..

35. What is globalization and Localization

36. Diff b/w Ref and output parameter

38. What is LINQ. Have you used linq (Yes) LINq to object

SQL Server Interview Questions
1. Diff b/w SP and Functions

2. What is index & Types of index.

3. How to find which index is used in table. Command name : sp_helpindex ‘TableName’

4. Diff b/w scode_identity and current_indentity

5. Diff b/w delete and truncate

6. Types of join with example (Cross join, inner join, right, left, self).

7. Find 3rd largest salary

8. Find Name and highest salary

9. What is trigger and types of trigger

10. Primary and unique key

11. Group by and having diff

12. What is Cursor

13. What is #temp and @Table type

14. Optimization SP

15. What is @@RowCount

16. What is cascade delete

17. Delete duplicate records.

18. What is merge


19. What is ROW_NUMBER ()?

Few InterView Answers:

Page Life cycle

1. PreInit()- First event that is fired, set master page and themes

2. Init():-once all control is initialized then this event is fired. We can change initialization for the controls.

3. InitComplete() :- this event is fired when all initializations of page and its control is done. Till the time viewstagte of page is not loaded. hence you can use this event to make changes to view state that you want to make sure are persisted after the next postback 

4. PreLoad():  this has two sub event

(i) LoadViewState: ViewState data are loaded to controls

(ii) Loads Postback data(): postback data are now handled in this event

5. OnPreLoad():- this event fires before the page load event

6. Page_Load()

7. LoadComplete()

8. PreRender() : -Allows final changes to the page or its control. This event takes place after all regular PostBack events have taken place. This event takes place before saving ViewState, so any changes made here are saved.For example : After this event, you cannot change any property of a button or change any viewstate value. Because, after this event, SaveStateComplete and Render events are called. 

9.Render This is a method of the page object and its controls (and not an event). At this point, ASP.NET calls this method on each of the page’s controls to get its output. The Render method generates the client-side HTML, Dynamic Hypertext Markup Language (DHTML), and script that are necessary to properly display a control at the browser.

10. UnLoad This event is used for cleanup code. After the page's HTML is rendered, the objects are disposed of. During this event, you should destroy any objects or references you have created in building the page. At this point, all processing has occurred and it is safe to dispose of any remaining objects, including the Page object. Cleanup can be performed on- 

     (a)Instances of classes i.e. objects

     (b)Closing opened files

     (c)Closing database connections. 


 Functions                                   |                  Proc

1. Must return a value 1. May or may not return a value
2. Functions can have only 2. Proc may have i/p or o/p parameter
 i/p parameter
3. Function can't call Proc 3. Proc can call functions
4. functions are not precompiled objects 4. Proc is precomplied objects
5. functions are slower in execution 5. Procs are faster in execution
6. Functions can perform only select statement 6. Proc allow dml as well as select statement
7. functions are used in select statement 7. we can call proc through Exec statement
8. functions can be used in WHERE/HAVING/SELECT 8. Proc can not be used in these statements
statements
9.functions can not use try and catch               9. we can use try and catch block in proc
10. we cant use transaction in function 10. can use transaction in Proc
11. We cant call funcations from .net code 11. Can call proc from .net code
Directly


SQL Views: View is virtual table which does not exists and acts as a table.It may be created from one or more than one table.
1. It acts as a layer b/w user and table.
2. For security reasone we may hide some columns from user.
3. If there are many columns. Views reduces the effort to write and find the query


Cursor: Cursor is a database objects to retrieve data from a result set one row at a time, instead of the T-SQL commands that operate on all the rows in the result set at one time. We use cursor when we need to update records in a database table in singleton fashion means row by row.


Primary Key | Unique key

1. It does not allw null values 1. It allows null values
2. by default it adds cluster index 2. by default non cluster index
3. A table can have only one PK in table 3. A table can have more than one unique key
4. PK can be referred as FK 4. UK can not be referred as FK

4.0 .NET NEW FEATURES:

1. clientIdMode : static
2. Optional Parameter
3. PLINQ
4. Named Parameter
5. Task
6. ZIP
7. RedirectToPermanent
8. Dynamic Parameter
9.


WCF (Window Communication Foundation):Windows Communication Foundation (WCF) is an SDK for developing and deploying services on Windows. WCF provides a runtime environment for services, enabling you to expose CLR types as services, and to consume other services as CLR types. 

1. What is service and client in perspective of data communication?

A service is a unit of functionality exposed to the world.

The client of a service is merely the party consuming the service.

2. What is address in WCF and how many types of transport schemas are there in WCF?

Address is a way of letting client know that where a service is located. In WCF, every service is associated with a unique address. This contains the location of the service and transport schemas.  

3. What are contracts in WCF?

In WCF, all services expose contracts. The contract is a platform-neutral and standard way of describing what the service does. 
Types of contracts

1. Service Contract: 

2. Operation Contract

3. Data contracts 

4.Fault contracts :Define which errors are raised by the service, and how the service handles and propagates errors to its clients.

5.Message contracts: Allow the service to interact directly with messages. Message contracts can be typed or untyped, and are useful in interoperability cases and when there is an existing message format we have to comply with.

Example: 

[ServiceContract]

interface IMyContract

{

   [OperationContract]

   string MyMethod( );

}

class MyService : IMyContract

{

   public string MyMethod( )

   {

      return "Hello World";

   }

}

[DataContract]

class Contact

{

   [DataMember]

   public string FirstName;



   [DataMember]

   public string LastName;

}

[ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [FaultContract(typeof(ServiceData))]
        ServiceData TestConnection(string strConnectionString);
    }

    // Use a data contract as illustrated in the sample
    // below to add composite types to service operations.
    [DataContract]
    public class ServiceData
    {
        [DataMember]
        public bool Result { get; set; }
        [DataMember]
        public string ErrorMessage { get; set; }
        [DataMember]
        public string ErrorDetails { get; set; }
    }
 [MessageContract]

    public class AutherRequest

    {

        [MessageHeader]

        public string AutherId;



    }





    [MessageContract]

    public class AuthorResponse

    {

        [MessageBodyMember]

        public Auther Obj;



    }


3. WCF Hosting:
(i) Self hosting
(II) IIS Hosting
(iii) Windows Activation service


4. What is binding and how many types of bindings are there in WCF?: A binding defines how an endpoint communicates to the world. A binding defines the transport (such as HTTP or TCP) and the encoding being used (such as text or binary). A binding can contain binding elements that specify details like the security mechanisms used to secure messages, or the message pattern used by an endpoint.

WCF supports 10 types of bindings. 

1. Basic binding (BasicHttpBinding)

Offered by the BasicHttpBinding class, this is designed to expose a WCF service as a legacy ASMX web service, so that old clients can work with new services. When used by the client, this binding enables new WCF clients to work with old ASMX services.

2. TCP binding(NetTcpBinding )

Offered by the NetTcpBinding class, this uses TCP for cross-machine communication on the intranet. It supports a variety of features, including reliability, transactions, and security, and is optimized for WCF-to-WCF communication. As a result, it requires both the client and the service to use WCF.


3. Peer network binding(NetPeerTcpBinding)

Offered by the NetPeerTcpBinding class, this uses peer networking as a transport. The peer network-enabled client and services all subscribe to the same grid and broadcast messages to it.


4. IPC binding(NetNamedPipeBinding)

Offered by the NetNamedPipeBinding class, this uses named pipes as a transport for same-machine communication. It is the most secure binding since it cannot accept calls from outside the machine and it supports a variety of features similar to the TCP binding.


5. Web Service (WS) binding(WSHttpBinding)

Offered by the WSHttpBinding class, this uses HTTP or HTTPS for transport, and is designed to offer a variety of features such as reliability, transactions, and security over the Internet.


6. Federated WS binding(WSFederationHttpBinding)

Offered by the WSFederationHttpBinding class, this is a specialization of the WS binding, offering support for federated security.

in configuration) provides a mechanism for exposing a federated service. That is, a service that requires clients to authenticate using a security token issued by a security token service. This topic shows how to set up a WSFederationHttpBinding in both code and configuration. Once the binding is created, you can set up an endpoint to use that binding.


7. Duplex WS binding(WSDualHttpBinding)

Offered by the WSDualHttpBinding class, this is similar to the WS binding except it also supports bidirectional communication from the service to the client.


8. MSMQ binding(WSDualHttpBinding)

Offered by the NetMsmqBinding class, this uses MSMQ for transport and is designed to offer support for disconnected queued calls.


9. MSMQ integration binding(MsmqIntegrationBinding )

Offered by the MsmqIntegrationBinding class, this converts WCF messages to and from MSMQ messages, and is designed to interoperate with legacy MSMQ clients.

10. Custom Binding:


5. What is endpoint in WCF?

Every service must have Address that defines where the service resides, Contract that defines what the service does and a Binding that defines how to communicate with the service. In WCF the relationship between Address, Contract and Binding is called Endpoint.

The Endpoint is the fusion of Address, Contract and Binding.

6. What is Proxy and how to generate proxy for WCF Services?

The proxy is a CLR class that exposes a single CLR interface representing the service contract. The proxy provides the same operations as service's contract, but also has additional methods for managing the proxy life cycle and the connection to the service. The proxy completely encapsulates every aspect of the service: its location, its implementation technology and runtime platform, and the communication transport.

1 The proxy can be generated using Visual Studio by right clicking Reference and clicking on Add Service Reference. This brings up the Add Service Reference dialog box, where you need to supply the base address of the service (or a base address and a MEX URI) and the namespace to contain the proxy.

2. Proxy can also be generated by using SvcUtil.exe command-line utility. We need to provide SvcUtil with the HTTP-GET address or the metadata exchange endpoint address and, optionally, with a proxy filename. The default proxy filename is output.cs but you can also use the /out switch to indicate a different name.

SvcUtil http://localhost/MyService/MyService.svc /out:Proxy.cs

When we are hosting in IIS and selecting a port other than port 80 (such as port 88), we must provide that port number as part of the base address:

SvcUtil http://localhost:88/MyService/MyService.svc /out:Proxy.cs

Question 7. What are different elements of WCF Srevices Client configuration file?

WCF Services client configuration file contains endpoint, address, binding and contract. A sample client config file looks like

<system.serviceModel>

   <client>

      <endpoint name = "MyEndpoint"

         address  = "http://localhost:8000/MyService/"

         binding  = "wsHttpBinding"

         contract = "IMyContract"

      />

   </client>

</system.serviceModel>

Question 8: How to configure Reliability while communicating with WCF Services?

Reliability can be configured in the client config file by adding reliableSession under binding tag.

<system.serviceModel>

   <services>

      <service name = "MyService">

         <endpoint

            address  = "net.tcp://localhost:8888/MyService"

            binding  = "netTcpBinding"

            bindingConfiguration = "ReliableCommunication" 

            contract = "IMyContract"

         />

      </service>

   </services>

   <bindings>

      <netTcpBinding>

         <binding name = "ReliableCommunication">

            <reliableSession enabled = "true"/> 

         </binding>

      </netTcpBinding>

   </bindings>

</system.serviceModel>



Reliability is supported by following bindings only

NetTcpBinding
WSHttpBinding
WSFederationHttpBinding
WSDualHttpBinding

Question 9: How to deal with operation overloading while exposing the WCF services?

By default overload operations (methods) are not supported in WSDL based operation. However by using Name property of OperationContract attribute, we can deal with operation overloading scenario.

[ServiceContract]

interface ICalculator

{

   [OperationContract(Name = "AddInt")]

   int Add(int arg1,int arg2);



   [OperationContract(Name = "AddDouble")]

   double Add(double arg1,double arg2);

}

Question 10: What is the use of ServiceBehavior attribute in WCF ?

ServiceBehaviour attribute is used to specify the InstanceContextMode for the WCF Service class (This can be used to maintained a state of the service or a client too)

There are three instance Context Mode in the WFC

PerSession : This is used to create a new instance for a service and the same instance is used for all method for a particular client. (eg: State can be maintained per session by declaring a variable)

PerCall : This is used to create a new instance for every call from the client whether same client or different. (eg: No state can be maintained as every time a new instance of the service is created)

Single : This is used to create only one instance of the service and the same instance is used for all the client request. (eg: Global state can be maintained but this will be applicable for all clients)


Question 11: What is the Messaging Pattern? Which Messaging Pattern WCF supports?

Messaging Pattern : Messaging patterns describes how client and server should exchange the message. There is a protocol between client and server for sending and receiving the message. These are also called Message Exchange Pattern.

WCF supports following 3 types of Message Exchange Patterns
1. request - reply (default message exchange pattern)
2. OneWay (Simplex / datagram)
3. Duplex(CallBack) 

Question 12 :What is .svc file in WCF?

.svc file is a text file. This file is similar to our .asmx file in web services.

This file contains the details required for WCF service to run it successfully.

This file contains following details :
1. Language (C# / VB)
2. Name of the service
3. Where the service code resides

Example of .svc file

<%@ ServiceHost Language="C#/VB" Debug="true/false" CodeBehind="Service code files path" Service="ServiceName" 

Question 13: What is DataContractSerializer in WCF?

DataContractSerializer is new WCF serializer.

This is serialization engine in WCF. DataContractSerializer translate the .NET framework objects into XML and vice-versa.

By default WCF uses DataContractSeriazer.

Question 13: What is Fault Contracts in WCF?

Fault Contracts is the way to handle exceptions in WCF. The problem with exceptions is that those are technology specific and therefore cannot be passed to other end because of interoperability issue. (Means either from Client to Server or vice-versa). There must be another way representing the exception to support the interoperability. And here the SOAP Faults comes into the picture.

Soap faults are not specific to any particular technology and they are based on industry standards.

To support SOAP Faults WCF provides FaultException class. This class has two forms:

a. FaultException : to send untyped fault back to consumer
b. FaultException<T>: to send typed fault data to the client

WCF service also provides FaultContract attribute so that developer can specify which fault can be sent by the operation (method). This attribute can be applied to operations only.

Question 14: The concurrency mode is specified using the ServiceBehavior attribute on the class that implements the service.
Ex.

[ServiceBehavior(ConcurrencyMode=ConcurrencyMode.Single)]
Public class ServiceClass : IServiceInterface{
//Implementation Code
}

There are 3 possible values of ConcurrencyMode enumeration
Single
Reentrant
Multipl

Question 15:Which bindings in WCF support the message streaming?

Hello,

Following bindings supports the streaming in WCF:

1. basicHttpBinding
2. netTcpBinding
3. netNamedPipeBinding 

Question 16: What is "Automatic activation" in WCF ?

Automatic Activation means that the service is not necessary to be running in advance. When any message is received by the service it then launches and fulfills the request. But in case of self hosting the service should always be running. 

Question 17 : What is a Throttling behavior in WCF?

Throttling behavior of the WCF service holds the configuration for three limitations that control the amount of resources that your service hosting can allocate to deal with the client request. Thus it enables to
1. Manages resource Usage
2. Balances performance load


Question 18: How can we specify the throttling behavior for a WCF service?

Throttling behavior is specified by the following three parameters.

1. MaxConcurrentCalls - Total no of concurrent calls service will accept
2. MaxConcurrentSessions - Total no of sessionful channels service will accept
3. MaxConcurrentInstances - Total no of service instances will be created for servicing requests.

It can be specifed either through code or configuration file. It requires the "System.SystemModel.Behavior" namespace to be included. 

Question 19 : ServiceContract, DataContract and MessageContract maps to which web services standard ?

(1) ServiceContracts maps to WSDL
(2) DataContracts maps to XSD
(3) MessageContracts maps to SOAP

Security Mode in WCF:

Across all service bindings there are five possible security modes:

    None. Turns security off.
    Transport. Uses transport security for mutual authentication and message protection.
    Message. Uses message security for mutual authentication and message protection.
    Both. Allows you to supply settings for transport and message-level security (only MSMQ supports this).
    TransportWithMessageCredential. Credentials are passed with the message and message protection and server authentication are provided by the transport layer.
    TransportCredentialOnly. Client credentials are passed with the transport layer and no message protection is applied. 

Client Credential Type

The choice of client credential type depends on the security mode in place. For transport security you can require a Windows credential or certificate-and there are variations on how Windows credentials are passed via TCP, HTTP and MSMQ. Message security supports any of the following settings for clientCredentialType:

    None
    Windows
    UserName
    Certificate
    IssuedToken

Question 20: What is delegate and types of Delegates
C# delegates are similar to pointers to functions, in C or C++. A delegate is a reference type variable that holds the reference to a method. The reference can be changed at runtime.

Delegates are especially used for implementing events and the call-back methods. All delegates are implicitly derived from the System.Delegate class.

Instantiating Delegates

Once a delegate type has been declared, a delegate object must be created with the new keyword and be associated with a particular method. When creating a delegate, the argument passed to the new expression is written like a method call, but without the arguments to the method. For example:

public delegate void printString(string s);
...
printString ps1 = new printString(WriteToScreen);
printString ps2 = new printString(WriteToFile);

Following example demonstrates declaration, instantiation and use of a delegate that can be used to reference methods that take an integer parameter and returns an integer value.

using System;

delegate int NumberChanger(int n);
namespace DelegateAppl
{
   class TestDelegate
   {
      static int num = 10;
      public static int AddNum(int p)
      {
         num += p;
         return num;
      }

      public static int MultNum(int q)
      {
         num *= q;
         return num;
      }
      public static int getNum()
      {
         return num;
      }

      static void Main(string[] args)
      {
         //create delegate instances
         NumberChanger nc1 = new NumberChanger(AddNum);
         NumberChanger nc2 = new NumberChanger(MultNum);
         //calling the methods using the delegate objects
         nc1(25);
         Console.WriteLine("Value of Num: {0}", getNum());
         nc2(5);
         Console.WriteLine("Value of Num: {0}", getNum());
         Console.ReadKey();
      }
   }
}


Qestion Dif b/w Interface and Abstract class

Interface             |         Abstract
1. A class may inherit several interfaces.                      1.  A class may inherit only one abstract class.

2. An interface cannot provide any code, just the signature.        2.  An abstract class can provide complete, default code and/or just the details that have to be overridden.

3. An interface cannot have access modifiers for the subs,                                   3. An abstract class can contain access modifiers for the subs,functions, properties.
functions, properties etc everything is assumed as public

4. Interfaces are used to define the peripheral abilities of a class.    4.  An abstract class defines the core identity of a class and there it is used for objects of the same type.
In other words both Human and Vehicle can inherit from a IMovable interface.

5. If various implementations only share method signatures                                5. If various implementations are of the same kind and use common behaviour or status then abstract class is then it is better to use Interfaces.         better to use.

6. Requires more time to find the actual method in the corresponding classes.  6. Fast

7. If we add a new method to an Interface then we have to track down                7. If we add a new method to an Interface then we have to track down all the implementations of the
    all the implementations of the interface and define implementation                     
    for the new method.

8. No fields can be defined in interfaces   8.  An abstract class can have fields and constrants defined


Question: Cachcing and types of caching

1. Page level catching : whole page will be cached e.g.  <%@ OutputCache Duration=5 VaryByParam="id" VaryByCustom="browser" %>
2. Fragement caching : 
3. Data Catching
4. AppFabric Caching


User control

1) Reusability web page
2) We can’t add to toolbox
3) Just drag and drop from solution explorer to page (aspx)
4) U can register user control to. Aspx page by Register tag
5) A separate copy of the control is required in each application
6) Good for static layout
7) Easier to create
8)Not complied into DLL
9) Here page (user page) can be converted as control then
We can use as control in aspx

Custom controls

1) Reusability of control (or extend functionalities of existing control)
2) We can add toolbox
3) Just drag and drop from toolbox
4) U can register user control to. Aspx page by Register tag
5) A single copy of the control is required in each application
6) Good for dynamics layout
7) Hard to create
8) Compiled in to dll


Reversing String:

string reverse= "Abhishek";
string result= string.Empty;
For (int i=1, i<=reverse.Lenght;i++)
{
   result += reverse[reverse.Lenght -1].ToString();

}
Console.WriteLine(result);


Factorial number

int fact=5;
for(int i = number-1; i>1;i--)
{
 fact = fact*i;
}


Validation Controls
1. Required
2. Range
3. Compare
4. Expression
5. Custom

6. Summary

No comments:

Post a Comment