Monday, 3 February 2014

Abstract, Sealed, Static, Partial - Classes

Class Types:
1) Abstract class
2) Sealed Class
3) Static Class
4) Partial Class
-----------------------------------------
A-- Abstract
S-- Sealed
S--Static
ASS is order by name
Keyword
Can be instantiated(object)
Can be inherited
Abstract
 NO
 YES
Sealed
YES
 NO
Static
NO
NO

Abstract Class
  1. It only represents the base class and thus has be inherited for its use.
  2. Object can NOT be created. can NOT be instantiated.
  3. Abstract class and methods can NOT be sealed ( class which can not be inherited).
  4. Abstract methods can NOT be private.
  5. Abstract methods can NOT be virtual ( by default they are virtual).
  6. Abstract class and methods can NOT be static.
  7. Abstract method definition can be given only inside a Abstract class. In non abstract class no abstract method can be defined.
  8. Can have either abstract method or non-abstract methods.
  9. Abstract method do not have any implementation of methods but has to be provided the same in the derived class.
  10. Abstract class may contain NO abstract method at all. 
  11. Abstract methods has to be override in derived class. 
  12. Derived class has to implement all abstract methods of abstract class.

abstract class absClass
{
   public abstract int abstractMethod(int Num1, int Num2);
}

 public override int abstractMethod(int Num1, int Num2)
{
    return Num1 * Num2;
 }

Sealed Class
  1. Restrict inheritance. can NOT be inherited. Its just to take away the inheritance feature.
  2. Structs are sealed in nature.
  3. NO restriction on object creation. sealed class can be instantiated.
  4. If you make a sealed a method / property that overrides a virtual method /property  it will get prevented from further overriding.
  5. Best use of sealed class is when your sealed class has static members (How?).
class X
{
  protected virtual void F() { Console.WriteLine("X.F"); }
  protected virtual void F2() { Console.WriteLine("X.F2"); }
}

class Y : X
{
 sealed protected override void F() { Console.WriteLine("Y.F"); }
 protected override void F2() { Console.WriteLine("X.F3"); }
}

class Z : Y
{
 // Attempting to override F causes compiler error CS0239.
 // protected override void F() { Console.WriteLine("C.F"); }
// Overriding F2 is allowed.
 protected override void F2() { Console.WriteLine("Z.F2"); }
}

Static Class
  1. Static class must have all methods and variables as static.
  2. Even in static class only static constructor can be called and NO instance constructor allowed.
  3. can NOT be instantiated.
  4. static class is Sealed(can not be inherited) by default.
  5. Static class can NOT be abstract class ( as it can not be inherited).
  6. Static class can only inherit system.object class as system.object class is the base class for every class.
  7. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.
  8. Use a static class to contain methods that are not associated with a particular object.
Partial Class
a special ability to implement the functionality of a single class into multiple files and all these files are combined into a single class file when the application is compiled. A partial class is created by using a partial keyword

SOAP and REST

SOAP
REST
Only XML format is allowed for data transfer.
Multiple format like Plain Text, XML, JSON HTML
Stateless by default, but it’s possible to make a SOAP API stateful.
Stateless (no server-side sessions).
While SOAP supports SSL (just like REST) it also supports WS-Security which adds some enterprise security features.
Less Secure
Requires more bandwidth and computing power
Requires fewer resources.



WCF and ASP.net Services















































Const
Read-only
A constant member is defined at compile time and cannot be changed at runtime.
read-only member can be initialized at runtime, in a constructor as well being able to be initialized as they are declared
They must be initialized as they are declared
Not implicitly static (only single object ) and has to explicitly made static



Monday, 21 October 2013

Encapsulation

Note: All this data has been copied from various sources for the purpose of knowledge sharing. Data content  can be either as it is or with little modification.
---------------------------------------------------------------------------------------------------------------------
Encapsulation prevents data from unwanted access by encapsulating data in a single object.

In a programming language, methods and properties that correspond to actions and attributes respectively are kept under a unit called object. The advantage of encapsulation is that the implementation is not accessible to the client. The user has to know only the functionality of encapsulated unit and information to be supplied to get the result.

Abstraction is supported using interface and abstract class while Encapsulation is supported using access modifiers e.g. public, private and protected.

Thursday, 3 October 2013

NIIT

1. Explain different type of identity? [SQL Server]
2. What is scope_identity? [SQL Server]
3. What is CodePage?[SQL Server]
4. What is an Assembly?
5. What are the benefits of MSIL?
6. Describe ASP.NET Page Life Cycle?
7. Write down ASP.NET Page events?
8. What is the use of Interface?
9. What are the differences between VB.NET and C#.NET?
10. what are soap headers and soap extensions ?
11. can we return a Person type object from a web method ? what will be the WSDL then of this webservice ?
12. which method we use in webservices to send the request ? Get or Post ? explian
13. what is WSDL in webservices ?
14. Can we return a dataset from w webservice 
15. how can u do authentication a webservice ? so that only the person that have writes able to hit our service ?

--------------------------------
(1, 2)
 In most of our application scenario, we need to get latest inserted row information through SQL query. And for that, we have multiple options like:


SELECT @@IDENTITY  -- 
SELECT SCOPE_IDENTITY()
SELECT IDENT_CURRENT('table name')

All three functions return last-generated identity values. However, the scope and session on which last is defined in each of these functions differ.

SELECT @@IDENTITY --
It returns the last IDENTITY value produced on a connection, regardless of the table that produced the value, and regardless of the scope of the statement that produced the value.
@@IDENTITY will return the last identity value entered into a table in your current session. While @@IDENTITY is limited to the current session, it is not limited to the current scope. If you have a trigger on a table that causes an identity to be created in another table, you will get the identity that was created last, even if it was the trigger that created it.

SELECT SCOPE_IDENTITY()--
It returns the last IDENTITY value produced on a connection and by a statement in the same scope, regardless of the table that produced the value.
SCOPE_IDENTITY(), like @@IDENTITY, will return the last identity value created in the current session, but it will also limit it to your current scope as well. In other words, it will return the last identity value that you explicitly created, rather than any identity that was created by a trigger or a user defined function.

SELECT IDENT_CURRENT('table name') --
It returns the last IDENTITY value produced in a table, regardless of the connection that created the value, and regardless of the scope of the statement that produced the value.
IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the identity value generated for a specific table in any session and any scope.
========================================================================
(4) Assembly is a pre compiled code of .net clr in form of DLL or self executing file .EXE. It is of two forms private assembly and public assembly
private assembly is kept in the local folder of the project while the public assembly is kept in GAC.
public assembly has 4 main parts (Face value, version, public key token, culture info). public assebly is also called strong name assembly.
========================================================================
(5) MSIL -- Microsoft intermediate language
C# code --> CLR --> MSIL(can be read by any language) --> JIT --> Machine language

Tuesday, 13 August 2013

Insight WCF (windows communication foundation)

Advantage

  1. WCF is interoperable with other services when compared to .Net Remoting,where the client and service have to be .Net.
  2. WCF services provide better reliability and security in compared to ASMX web services.
  3. In WCF, there is no need to make much change in code for implementing the security model and changing the binding. Small changes in the configuration will make your requirements.
  4. WCF has integrated logging mechanism, changing the configuration file settings will provide this functionality. In other technology developer has to write the code.

FeaturesWeb ServiceWCF
HostingIt can be hosted in IISIt can be hosted in IIS, windows activation service, Self-hosting, Windows service
Programming[WebService] attribute has to be added to the class[ServiceContraact] attribute has to be added to the class
Model[WebMethod] attribute represents the method exposed to client[OperationContract] attribute represents the method exposed to client
OperationOne-way, Request- Response are the different operations supported in web serviceOne-Way, Request-Response, Duplex are different type of operations supported in WCF
XMLSystem.Xml.serialization name space is used for serializationSystem.Runtime.Serialization namespace is used for serialization
EncodingXML 1.0, MTOM(Message Transmission Optimization Mechanism), DIME, CustomXML 1.0, MTOM, Binary, Custom
TransportsCan be accessed through HTTP, TCP, CustomCan be accessed through HTTP, TCP, Named pipes, MSMQ,P2P, Custom
ProtocolsSecuritySecurity, Reliable messaging, Transactions

Endpoints will be mentioned in the web.config file on the created service.

<system.serviceModel><services>
      <service name="MathService"
        behaviorConfiguration="MathServiceBehavior">
       <endpoint
         address="http://localhost:8090/MyService/MathService.svc" contract="IMathService"
          binding="wsHttpBinding"/> 
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="MathServiceBehavior">
          <serviceMetadata httpGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
  • There could be more than 1 end points in a webconfig. 
    • for example,  One of the client will access SOAP using http and other client will access Binary using TCP. How it can be done?
    • 
      
  • <system.serviceModel>
    
    
    <services>
      <service name="MathService"
        behaviorConfiguration="MathServiceBehavior">
      <endpoint address="http://localhost:8090/MyService/MathService.svc" 
        contract="IMathService"
          binding="wsHttpBinding"/><endpoint address="net.tcp://localhost:8080/MyService/MathService.svc" 
contract="IMathService"
          binding="netTcpBinding"/> 
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="MathServiceBehavior">
          <serviceMetadata httpGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
---------------------------------------------
>> Addresss contain the location of service and transport schema. 
   HTTP, TCP, MSMQ, Peer Network
>> example, http://localhost/service/callme
   net.tcp://localhost/service/callme
>> ABC (end points)
>> Contracts type
   Service Contract
   Data Contract
   Fault Contract
   Message contract
>> [ServiceContract] - defines which operation client can perform on services.
   sub types -
1) service contract - define interfaces.
2) operation contract - define methods inside interfaces. 

>> [servicecontract]
interface Icontract
{
 [operationcontract]
   string myMethod();
}

Class Myservice:Icontract
{
   public string myMethod()
   { return "hello"; }
}

Tuesday, 23 July 2013

Insight MVC interview question

Note: All this data has been copied from various sources for the purpose of knowledge sharing. Data content  can be either as it is or with little modification.
---------------------------------------------------------------------------------------------------------------------

Where are the routing rules defined in an asp.net MVC application?
In Application_Start event in Global.asax


 protected void Application_Start()
        {
            .....

            RegisterRoutes(RouteTable.Routes);
        }

public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
 
            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );
 
            routes.MapRoute(
                "TwoParameters", // Route name
                "{controller}/{action}/{parentId}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", parentId = "", id = UrlParameter.Optional } // Parameter defaults
            );
        }

What are the different return type controllers action method supports in ASP.NET MVC?

There are total nine return types we can use to return results from controller to view.  The base type of all these result types is ActionResult. 1. ViewResult (View) : This return type is used to return a webpage from an action method. 2. PartialviewResult (Partialview) : This return type is used to send a part of a view which will be rendered in another view. 3. RedirectResult (Redirect) : This return type is used to redirect to any other controller and action method depending on the URL. 4. RedirectToRouteResult (RedirectToAction, RedirectToRoute) : This return type is used when we want to redirect to any other action method. 5. ContentResult (Content) : This return type is used to return HTTP content type like text/plain as the result of the action 6. jsonResult (json) : This return type is used when we want to return a JSON message. 7. javascriptResult (javascript) : This return type is used to return JavaScript code that will run in browser. 8. FileResult (File) : This return type is used to send binary output in response. 9. EmptyResult : This return type is used to return nothing (void) in the result. 
Action Filtering in ASP.NET MVC Applications
Action Filters allow us to add pre-action and post-action behavior to controller action methods.n action filter is a .NET class that inherits from FilterAttribute or one of its subclasses, usually ActionFilterAttribute, which adds the OnActionExecuting, OnActionExecuted, OnResultExecuting, and OnResultExecuted methods, providing hooks for code to be executed both before and after the action and result are processed.ASP.NET MVC provides several action filters out of the box:
  • Authorize – checks to see whether the current user is logged in, and matches a provided username or role name (or names), and if not it returns a 401 status, which in turn invokes the configured authentication provider.
  • ChildActionOnly – used to indicate that the action method may only be called as part of a parent request, to render inline markup, rather then returning a full view template.
  • OutputCache – tells ASP.NET to cache the output of the requested action, and to serve the cached output based on the parameters provided.
  • HandleError – provides a mechanism for mapping exceptions to specific View templates, so that you can easily provide custom error pages to your users for specific exceptions (or simply have a generic error view template that handles all exceptions).
  • RequireHttps – forces a switch from http to https by redirecting GET requests to the https version of the requested URL, and rejects non-https POST requests.
  • ValidateAntiForgeryToken – checks to see whether the server request has been tampered with. Used in conjunction with the AntiForgeryToken HTML Helper, which injects a hidden input field and cookie for later verification (Here’s a post showing one way you can enable this across the board).
  • ValidateInput – when set to false, tells ASP.NET MVC to set ValidateRequest to false, allowing input with potentially dangerous values (i.e. markup and script). You should properly encode any values received before storing or displaying them, when request validation is disabled. Note that in ASP.NET 4.0, request validation occurs earlier in the processing pipeline, so in order to use this attribute, you must set the following value in your web.config file: 
    <httpRuntime requestValidationMode="2.0"/>