Thursday, February 21, 2013

C# & ASP.Net


1. What is an abstract class?

An abstract class cannot be instantiated.

The abstract keyword enables you to create classes and class members that are incomplete and must be implemented in a derived class.

When we want to move common functionalities 2 or more classes into base class

The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share.

Abstract class can have constructor also. we can define the method inside constructor of the abstract class. It will call automatically when we create the instance of the derived class.

Parent class of constructor will call first.

Have the methods overridden in derived classes.

An abstract class can have protected, static methods.

Only public access modifier for abstract.

// compile with: /target:library
public class D
{
    public virtual void DoWork(int i)
    {
        // Original implementation.
    }
}
public abstract class E : D
{
    public abstract override void DoWork(int i);
}
public class F : E
{
    public override void DoWork(int i)
    {
        // New implementation.
    }
}

1.1 when will use abstract and interface?

If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.
Common functionalities use abstract class.

An interface has no implementation, it only has the definition of the method without body.
The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class.
When we create any implementation that must be overridden by implemented classes.

When we create an abstract class we are creating base class that might have one or more complete method but at least one or more methods are left uncompleted and declared abstract.

If all method of an abstract class are uncompleted then it is same as an interface.
If you anticipate creating multiple versions of your component, create an abstract class.

Abstract classes provide a simple and easy way to version your components.

By updating the base class, all inheriting classes are automatically updated with the change.

Interfaces, on the other hand, cannot be changed once created. If a new version of an interface is required, you must create a whole new interface.

If the functionality you are creating will be useful across a wide range of disparate objects, use an interface.

Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.


If you want to provide common, implemented functionality among all implementations of your component, use an abstract class.

Abstract classes allow you to partially implement your class, whereas interfaces contain no implementation for any members.


















  • Interface has no implementation, but they have to be implemented.
  • Abstract class’s methods can have their own default implementations and they may be extended. The Abstract class’s methods could run independant of the inherting class.
  • Interfaces can only have method declaration (implicitly public and abstract) and properties (implicitly public static)
  • Abstract class’s methods can’t have implementation only when declared abstract.
  • Interface can inherit more than one interfaces
  • class can implement more than one interfaces, but can inherit only one class
  • Abstract class must override all abstract method and may override virtual methods
  • Interface can be used when the implementation is changing
  • Abstract class can be used to provide some default behavior for a base class.
  • Interface makes implementation interchangeable
  • Interface increase security by hiding the implementation
  • Abstract class can be used when implementing framework
  • Abstract classes are an excellent way to create planned inheritance hierarchies and also to use as non-leaf classes in class hierarchies.
  • 2.What is the difference between struct and class?

    The struct is value type, class is reference type.
    Memory allocated in the heap for class.
    Memory allocated in the stack for struct.

    Class
    When an object of the class is created, the variable to which the object is assigned holds only a reference to that memory. 
    Struct.
    When a struct is created, the variable to which the struct is assigned holds the struct's actual data.


    3. What is a delegate?When will use the delegates?

    delegate is a reference type variable that holds the reference to a method with a particular parameter list and return type. The reference can be changed at run time. Delegates are especially used for implementing events and the call-back methods.

    When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type. You can invoke (or call) the method through the delegate instance.
    Delegates are used to pass methods as arguments to other methods. Event handlers are nothing more than methods that are invoked through delegates. You create a custom method and a class such as a windows control can call your method when a certain event occurs. The following example shows a delegate declaration:

    This ability to refer to a method as a parameter makes delegates ideal for defining callback methods.

    Delegates are like C++ function pointers but are type safe.


















  • Delegates allow methods to be passed as parameters.
  • Delegates can be used to define callback methods.
  • Delegates can be chained together; for example, multiple methods can be called on a single event.
  • Methods do not have to match the delegate type exactly. For more information, see Using Variance in Delegates (C# and Visual Basic).
  • C# version 2.0 introduced the concept of Anonymous Methods, which allow code blocks to be passed as parameters in place of a separately defined method. C# 3.0 introduced lambda expressions as a more concise way of writing inline code blocks. Both anonymous methods and lambda expressions (in certain contexts) are compiled to delegate types. Together, these features are now known as anonymous functions. For more information about lambda expressions, see Anonymous Functions (C# Programming Guide).
  • 3.1.Ananymous method?
  • Provide a technique to pass a code block as a delegate parameter. Anonymous methods are basically methods without a name, just the body.
  • 3.2. What is lamda expression?
    lambda expression is an anonymous function that you can use to create delegates.

    By using lambda expressions, you can write local functions that can be passed as arguments or returned as the value of function calls.
  • .3.3. Multicast delegate?

  • Multicast delegates provide functionality to execute more than one method.

    /// Declares the multicast delegate
    public delegate void myDel(); 
    
    static public void Main(string[] args)
    {
        /// Declares the single delegate that points to MethodA
        myDel myDelA = new myDel(MethodA);
        /// Declares the single delegate that points to MethodA
        myDel myDelB = new myDel(MethodB);
        /// Declares the multicast delegate combining both delegates A and B
        myDel myMultiCast = (myDel)Delegate.Combine(myDelA, myDelB);
        /// Invokes the multicast delegate
        myMultiCast.Invoke();
    }
    
    static void MethodA()
    {
        Console.WriteLine(“Executing method A.”);
    }
    
    static void MethodB()
    {
        Console.WriteLine(“Executing method B.”);
    }

  • Delegates used below scenarios:

    Event handlers (for GUI and more)
    Starting threads
    Callbacks (e.g. for async APIs)
    LINQ and similar (List.Find etc)
    Anywhere else where I want to effectively apply "template" code with some specialized logic inside (where the delegate provides the specialization)

    sample

    Delegates are very useful for many purposes.



    Here is a silly example - I am sure you can extrapolate something more useful out of this:

    1./*
    2. * C# Program to Use Delegate to Call 2 Methods within which First method Prints to Console and Second Method Prints to File
    3. */
    4.using System;
    5.using System.IO;
    6.namespace Program
    7.{
    8.    class PrintString
    9.    {
    10.        static FileStream fs;
    11.        static StreamWriter sw;
    12.        public delegate void printString(string s);
    13.        public static void Screen(string str)
    14.        {
    15.            Console.WriteLine("The String is: {0}", str);
    16.        }
    17.        public static void File(string s)
    18.        {
    19.            fs = new FileStream("c:\\sri\\Message.txt",
    20.            FileMode.Append, FileAccess.Write);
    21.            sw = new StreamWriter(fs);
    22.            sw.WriteLine(s);
    23.            sw.Flush();
    24.            sw.Close();
    25.            fs.Close();
    26.        }
    27.        public static void sendString(printString ps)
    28.        {
    29.            ps("C# Program to Use Delegate to Call 2 Methods within which First method Prints to Console and Second Method Prints to File");
    30.        }
    31.        static void Main(string[] args)
    32.        {
    33.            printString ps1 = new printString(Screen);
    34.            printString ps2 = new printString(File);
    35.            sendString(ps1);
    36.            sendString(ps2);
    37.            Console.ReadKey();
    38.        }
    39.    }
    40.}

    3.4. Ananmous Functions?
    An anonymous function is an "inline" statement or expression that can be used wherever a delegate type is expected. You can use it to initialize a named delegate or pass it instead of a named delegate type as a method parameter.
    There are two kinds of anonymous functions, which are discussed individually in the following topics:

    class Test
    {
        delegate void TestDelegate(string s);
        static void M(string s)
        {
            Console.WriteLine(s);
        }
        static void Main(string[] args)
        {
            // Original delegate syntax required
            // initialization with a named method.
            TestDelegate testDelA = new TestDelegate(M);
            // C# 2.0: A delegate can be initialized with
            // inline code, called an "anonymous method." This
            // method takes a string as an input parameter.
            TestDelegate testDelB = delegate(string s) { Console.WriteLine(s); };
            // C# 3.0. A delegate can be initialized with
            // a lambda expression. The lambda also takes a string
            // as an input parameter (x). The type of x is inferred by the compiler.
            TestDelegate testDelC = (x) => { Console.WriteLine(x); };
            // Invoke the delegates.
            testDelA("Hello. My name is M and I write lines.");
            testDelB("That's nothing. I'm anonymous and ");
            testDelC("I'm a famous author.");
            // Keep console window open in debug mode.
            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }
    }
    /* Output:
        Hello. My name is M and I write lines.
        That's nothing. I'm anonymous and
        I'm a famous author.
        Press any key to exit.
     */
    4.Forms authentication?
       
               protection="All"
               timeout="30"
               name=".ASPXAUTH"
               path="/"
               requireSSL="false"
               slidingExpiration="true"
               defaultUrl="default.aspx"
               cookieless="UseDeviceProfile"
               enableCrossAppRedirects="false" />
    1.      The user requests the Default.aspx file from your application's virtual directory. IIS allows the request because anonymous access is enabled in the IIS Metabase. ASP.NET confirms that the authorization element includes a
    2.      The server looks for an authentication cookie. If it fails to find the authentication cookie, the user is redirected to the configured logon page (Login.aspx), as specified by the LoginUrl attribute of the forms element. The user supplies and submits credentials through this form. Information about the originating page is placed in the query string using RETURNURL as the key. The server HTTP reply is as follows:
    3.  302 Found Location:
    5.      The browser requests the Login.aspx page and includes the RETURNURL parameter in the query string.
    6.      The server returns the logon page and the 200 OK HTTP status code.
    7.      The user enters credentials on the logon page and posts the page, including the RETURNURL parameter from the query string, back to the server.
    8.      The server validates user credentials against a store, such as an SQL Server database or an Active Directory user store. The code in the logon page creates a cookie that contains a forms authentication ticket that is set for the session.
    In ASP.NET 2.0, the validation of user credentials can be performed by the membership system. The Membership class provides the ValidateUser method for this purpose as shown here:
    if (Membership.ValidateUser(userName.Text, password.Text))
    {
        if (Request.QueryString["ReturnUrl"] != null)
        {
            FormsAuthentication.RedirectFromLoginPage(userName.Text, false);
        }
        else
        {
            FormsAuthentication.SetAuthCookie(userName.Text, false);
        }
    }
    else
    {
        Response.Write("Invalid UserID and Password");
    }
    Note   When using the Login Web server control, it automatically performs the following steps for you. The preceding code is provided for context.
    9.      For the authenticated user, the server redirects the browser to the original URL that was specified in the query string by the RETURNURL parameter. The server HTTP reply is as follows:
    10.302 Found Location:
    11.http://localhost/TestSample/default.aspx
    12.  Following the redirection, the browser requests the Default.aspx page again. This request includes the forms authentication cookie.
    13.  The FormsAuthenticationModule class detects the forms authentication cookie and authenticates the user. After successful authentication, the FormsAuthenticationModule class populates the current User property, which is exposed by the HttpContext object, with information about the authenticated user.
    14.  Since the server has verified the authentication cookie, it grants access and returns the Default.aspx page.
    5.Built-in authentication in web service?

    1.       Add a new domain account to the Active Directory.
    2.       Create a new SPN that refers to the new domain account.
    Setspn –a http://Servicename domainName\account
    3.       Add a new application pool on IIS, and map its identity to the new domain account.
    4.       Configure the web service virtual directory to use the new application pool.
    5.       Grant the new account all permission needed to access the web service virtual directory and to work as an IIS_WPG group.
    6.       Restart IIS.
    6.Wshttps and basic HTTP binding?
    Criteria
    BasicHttpBinding
    WsHttpBinding
    Security support
    This supports the old ASMX style, i.e. WS-BasicProfile 1.1.
    This exposes web services using WS-* specifications.
    Compatibility
    This is aimed for clients who do not have.NET 3.0 installed and it supports wider ranges of clients. Many of the clients like Windows 2000 still do not run .NET 3.0. So an older version of .NET can consume this service.
    As its built using WS-* specifications, it does not support wider ranges of client and it cannot be consumed by older.NET version less than 3 version.
    Soap version
    SOAP 1.1
    SOAP 1.2 and WS-Addressing specification.
    Reliable messaging
    Not supported. In other words, if a client fires two or three calls you really do not know if they will return back in the same order.
    Supported as it supports WS-* specifications.
    Default security options
    By default, there is no security provided for messages when the client calls happen. In other words, data is sent as plain text.
    As WsHttBinding supports WS-*, it has WS-Security enabled by default. So the data is not sent in plain text.
    Security options
    ·         None
    ·         Windows – default authentication
    ·         Basic
    ·         Certificate
    ·         None
    ·         Transport
    ·         Message
    ·         Transport with message credentials

    6.1.       How to configure the net.tcp binding in the IIS?


    Site bindings



    7.What is Generics? and difference between arraylist and generics?

    http://www.aspsnippets.com/Articles/Difference-between-ArrayList-and-Generic-List-in-C-Net-and-VBNet.aspx

    ArrayList belongs to System.Collections namespace

    Generics belongs to System.Collections.Generic namespace

    ArralyList doesn't have type restrictions to storing data.It is not type safe 

    GenericList it will store only specific types of objects based on what data type has been specified  while declaration . It is type safe.Thus if you have a generic  list of string you can only store string values anything else will give compilation error.

    ArrayList stores all the data as object thus to get it back you must remember what you stored where and correspondingly . Type cast it as per its original type when stored. 

    Generic List stores all data type it is declared thus to getting the data back is hassle free and no type conversions required.

    you can create a collection that is type-safe at compile-time.
    Generic classes have type parameters. 

    By creating a generic class, you can create a collection that is type-safe at compile-time.
    7.1 constraints in generics?

    When you define a generic class, you can apply restrictions to the kinds of types that client code can use for type arguments when it instantiates your class. If client code tries to instantiate your class by using a type that is not allowed by a constraint, the result is a compile-time error. These restrictions are called constraints. Constraints are specified by using the where contextual keyword. The following table lists the six types of constraints:


    where T : classThe type argument must be a reference type; this applies also to any class, interface, delegate, or array type.
    8 static class can have non-static members?
    no
    10 What are the ways transfer data one page to another?
    1.  <%@ PreviousPageType VirtualPath="~/SourcePage.aspx" %>
    1.  Label1.Text = PreviousPage.CurrentCity;
    2.
    3.  TextBox SourceTextBox =
    4.          (TextBox) PreviousPage.FindControl("TextBox1");
    11.       New modifier in c#?
    Hide a member inherited from base class. To hide inherited member, declare it in the derived class using the same name, and modify it with the new modifier.
    // cs_modifier_new.cs
    // The new modifier
    using System;
    public class MyBaseC
    {
       public static int x = 55;
       public static int y = 22;
    }
    public class MyDerivedC : MyBaseC
    {
       new public static int x = 100;   // Name hiding
       public static void Main()
       {
          // Display the overlapping value of x:
          Console.WriteLine(x);
          // Access the hidden value of x:
          Console.WriteLine(MyBaseC.x);
          // Display the unhidden member y:
          Console.WriteLine(y);
       }
    }
    out put 100,22,55
    12.       What is the advantages of properties?
    using properties we can assure that no invalid (or unacceptable) value is assigned to the fields.
    13         What is type safe?

    Typesafe code means that an application cannot indirectly harm surrounding memory through the usage of variables.
    14. Immutable?

    String is immutable means that you cannot change the object itself, but you can change the reference ofcourse.

    25. What is composition
    Has-a relationship called composition. Car has a engine.

















  • Dependency : class A uses class B
  • Aggregation : class A has a class B
  • Composition : class A owns a class B

  • 26. What is partial classes?

    It is possible to split the definition of a class or a struct, an interface or a method over two or more source files. Each source file contains a section of the type or method definition, and all parts are combined when the application is compiled.

    public partial class Employee
    {
        public void DoWork()
        {
        }
    }

    public partial class Employee
    {
        public void GoToLunch()
        {
        }
    }
    27.without catch block we can use try and finally block

    Yes, we can use it
    28 What to specify friend assembly?
    [assembly:InternalsVisibleToAttribute("assembly name",
                                          "optional key string")]
    Concreate class means derived class

    31.Why you are using LINQ?

    Product based application you can use LINQ.
    Heavy transactions go for Stored procedure dot not use LINQ
    LINQ can provide the type safety and compile time checking of query expression
    LINQ to SQL is an O/RM (object relational mapping) implementation
    LINQ retrieve and manipulate data as strongly typed objects

    31.1. Iquerable and Ienerable?

    IEnumerable is best to query data from in-memory collections like List, Array etc.
    IEnumerable exists in System.Collections Namespace.

    1. Queryable exists in System.Linq Namespace.
    1. IQueryable can move forward only over a collection, it can’t move backward and between the items.
    1. IQueryable is best to query data from out-memory (like remote database, service) collections.
    1. While query data from database, IQueryable execute select query on server side with all filters.
    1. IQueryable is suitable for LINQ to SQL queries.
    1. IQueryable supports deferred execution.
    1. IQueryable supports custom query using CreateQuery and Execute methods.
    1. IQueryable support lazy loading. Hence it is suitable for paging like scenarios.
    1. Extension methods supports by IQueryable takes expression objects means expression tree.
    IQueryable Example
    
    
    1. MyDataContext dc = new MyDataContext ();

    2. IQueryable<Employee> list = dc.Employees.Where(p => p.Name.StartsWith("S"));

    3. list = list.Take<Employee>(10); 

    4. IEnumerable

    1. IEnumerable exists in System.Collections Namespace.

    2. IEnumerable can move forward only over a collection, it can’t move backward and between the items.

    3. IEnumerable is best to query data from in-memory collections like List, Array etc.

    4. While query data from database, IEnumerable execute select query on server side, load data in-memory on client side and then filter data.

    5. IEnumerable is suitable for LINQ to Object and LINQ to XML queries.

    6. IEnumerable supports deferred execution.

    7. IEnumerable doesn’t supports custom query.

    8. IEnumerable doesn’t support lazy loading. Hence not suitable for paging like scenarios.

    9. Extension methods supports by IEnumerable takes functional objects.

    IEnumerable Example

    1. MyDataContext dc = new MyDataContext ();

    2. IEnumerable<Employee> list = dc.Employees.Where(p => p.Name.StartsWith("S"));

    3. list = list.Take<Employee>(10);

    4. IEnumerable IQueryable
      NamespaceSystem.Collections NamespaceSystem.Linq Namespace
      Derives fromNo base interfaceDerives from IEnumerable
      Deferred ExecutionSupportedSupported
      Lazy LoadingNot SupportedSupported
      How does it workWhile querying data from database, IEnumerable execute select query on server side, load data in-memory on client side and then filter data. Hence does more work and becomes slow.While querying data from database, IQueryable execute select query on server side with all filters. Hence does less work and becomes fast.
      Suitable forLINQ to Object and LINQ to XML queries.LINQ to SQL queries.
      Custom QueryDoesn’t supports.Supports using CreateQuery and Execute methods.
      Extension mehtod
      parameter
      Extension methods supported in IEnumerable takes functional objects.Extension methods supported in IEnumerable takes expression objects i.e. expression tree.
      When to usewhen querying data from in-memory collections like List, Array etc.when querying data from out-memory (like remote database, service) collections.
      Best UsesIn-memory traversalPaging
    32.What is the architecture?

    Software application architecture is the process of defining a structured solution that meets all of the technical and operational requirements, while optimizing common quality attributes such as performance, security, and manageability. It involves a series of decisions based on a wide range of factors, and each of these decisions can have considerable impact on the quality, performance, maintainability, and overall success of the application.

    33.How you will communicate one layer to another layer?
    one way using getter and setter properties.
    Entity classes
    DTO-Data Transfer objects.
    Hybrid-Entity + DTO



    35.Why you are using Entity Framework?

    ADO.Net Entity Framework is an object relational Mapping that enables developers to work with relational data as domain specific objects

    36.How to trigger the Auto build?

    37.How to deploy the code?
    38.Are you using any tool for deployment?
    VS 2010
    39.What purposes are you using Nget packages?
    NuGet is a Visual Studio 2010 extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects that use the .NET Framework.
    In detail, Nuget is a free, open-source package management system offered by the Microsoft ASP.Net team to the developer community to ease the process of integrating any 3rd party open source component into our project.
    40.In Xmal what changes you have made for auto build?


    41. Has a and IS A relationship in UML?
    Has a relationship is Aggregation.
    Person has address Is aggregation
    IS A relationship is Generalization(Inheritance)
    Person is a student generalization.
    42. Idisposal interface?

    To release unmanaged resource
    http://msdn.microsoft.com/en-us/library/system.idisposable(v=vs.110).aspx

    protected new virtual void Dispose(bool disposing)
       {
          if (disposed) return;
    
          // Release any managed resources here. 
          if (disposing)
             safeHandle.Dispose();
    
          disposed = true;
    
          // Release any unmanaged resources not wrapped by safe handles here. 
    
          // Call the base class implementation. 
          base.Dispose(true);
       }
    
    
    
    Use the Dispose method of this interface to explicitly release unmanaged resources in conjunction with the garbage collector. The consumer of an object can call this method when the object is no longer needed.
    
    
    
    
    43. Façade design pattern?
    Complex system splits into sub systems.
    45. How will increase the Performance?
    Load balancing
    watch application issues like memory leaks
    Design considerations
                    1.cache the data
                    2,Close dispose resources
                    3.Reduce round trips
                    4.Return only data you need
                    5.Use stored procedures
    Page level
                    1.Enable buffering
                    2.Use page.ispostback to minimize redundant processing
                    3.Ensure debug set false
                    4.consider using server.transfer instead of respose.redirect
                    5.use client side validations
    Architecture
                    1.use layered architecture

    46.Two classes how will declare the relations?
    Association, Composition, Aggregation, Generalization
    Association->Professor wrote a book.
    47.Advantages of Interfaces?
    without risk of breaking existing applications
    *   Interfaces are useful in cases where you cannot use class inheritance. For example, structures cannot inherit from classes, but they can implement interfaces.
    *   Interfaces are more flexible than base classes because you can define a single implementation that can implement multiple interfaces


    Interfaces allow to develop loosely coupled systems.
    Interfaces are useful for dependency injection.
    Interfaces make unit testing easier.

    48. Where we have to use using block?
    Class inherited from Idisposable
    Class:Idisposable
    {
    Using
    {
    }
    }
    49.How to compress the view state?
    GZipStream class for compress.
    50.What is the max size of view state?
    25% of your page size.
    51.How much data can we transfer in post?
    GET request has a limitation on its length. The good practice is never allow more than 255 characters.
    POST request has no major limitation.
    52.What is difference between cluster index and non cluster index? Usage?

    Cluster Index
    1. Can be used for frequently used queries.
    2. Provide a high degree of uniqueness.
    3. Can be used in range queries.
    The leaf nodes of a clustered index contain the data pages.
    Quicker for insert and update operations than a clustered index
    Faster to read than non clustered
    clustered index output is sorted one,we can index only one row,
    but we can index more than one row in nonclusterd indexing
    53 Extension methods

    Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.
    54 take and takewhile
    TakeWhile returns elements while a Predicate matches. The Predicate returns true or false. When it returns false, TakeWhile returns.


    Take returns the first specified number of elements
    55.What is sealed class and static classes difference?
     Sealed class:- A class with static members we can go for sealed class.
    Static Class:-
    ·         They only contain static members.
    ·         They cannot be instantiated.
    ·         They are sealed.
    ·         They cannot contain Instance Constructors <http://msdn.microsoft.com/en-us/library/k6sa6h87(v=vs.80).aspx>
    sealed classes:
    1)we can create their instances, but cannot inherit them
    ex:
    sealed class demo
    {
    }
    class abc:demo
    {
    --Wrong
    }
    2)They can contain static as well as nonstatic members.
    static classes:
    1)we can neither create their instances, nor inherit them
    ex:
    static class Program
    {
    }
    2)They can have static members only.
    56 How to load the Master page?
    public class DynamicPage : System.Web.UI.Page
    {
        protected override void OnPreInit(EventArgs e)
        {
            string masterfile = getMasterPageFromDatabase();
            if (!masterfile.Equals(string.Empty))
            {
                base.MasterPageFile = masterfile;
            }
            base.OnPreInit(e);
        }
    }
    57 what is http Handler and module?
    A handler can be invoked by any file extension that is mapped via the web.config and the IIS file extension mappings.



    60. How will provide security for  Wcf service?
    61. Inproc
    1. session data is stored in current application domain and so consumes memory of web server machine.
    2. if server restarts, all session data is lost.

    62. State Server?

    StateServer - session serialized and stored in memory in a separate process (aspnet_state.exe). State Server can run on another machine.

    State server mode used in load balancing scenario.
    63.What is the difference between throw and throw ex?
    •throw ex resets the stack trace (so your errors would appear to originate from HandleException)
    •throw doesn't - the original offender would be preserved.
    64. Master page loading
    public class DynamicPage : System.Web.UI.Page
    {
    protected override void OnPreInit(EventArgs e)
    {
    string masterfile = getMasterPageFromDatabase();
    if (!masterfile.Equals(string.Empty))
    {
    base.MasterPageFile = masterfile;
    }
    base.OnPreInit(e);
    }
    }
    65.cahr and varchar difference?
    Char:
    1.Fixed length memory storage
    2.CHAR takes up 1 byte per character
    3.Use Char when the data entries in a column are expected to be the same size
    5.Ex:
    Declare test Char(100);
    test="Test" -
    Then "test" occupies 100 bytes first four bytes with values and rest with blank data.
    VarChar:
    1.Variable length memory storage(Changeable)
    2.VARCHAR takes up 1 byte per character, + 2 bytes to hold length information
    3.varchar when the data entries in a column are expected to vary considerably in size.
    4.Ex:
    Declare test VarChar(100);
    test="Test" -
    Then "test" occupies only 4+2=6 bytes. first four bytes for value and other two bytes for variable length information.
    66 .Net 4.0 features?
    •Security Changes in the .NET Framework 4.
    •Application Compatibility and Deployment
    •Web
    •Client - Enhancements in WPF
    •Data
    •Communications and Workflow
    Features in Web:
    1.Web Forms controls, including a new Chart control.
    2.Microsoft Ajax, including additional support for client-based Ajax applications in the Microsoft Ajax Library.
    3.Multi-targeting, including better filtering for features that are not available in the target version of the .NET Framework.
    4.Web Forms, including more integrated support for ASP.NET routing, enhanced support for Web standards, updated browser support, new features for data controls, and new features for view state management.
    5.MVC, including new helper methods for views, support for partitioned MVC applications, and asynchronous controllers.
    6.Deployment, including new tools for automating typical deployment tasks.
    7.MVC, including new helper methods for views, support for partitioned MVC applications, and asynchronous controllers

    68.Finalizer
    The finalizer (which is what you're using here) is only called during the Finalization phase, which will happen during GC
    69.Why interfaces are required?
    1.Enables to write loosely coupled systems. With the help of interfaces, if required in future, we can simply change the implementation thus making it easy for our application to adapt to changes.
    2.Developers’ roles are segregated. Developers writing interface based components don’t have to worry about how it’s being implemented. They only need to know how to invoke functionalities available within it. UI developers can start working on the UI without a concrete implementation of the interface. At the same time, component developers can concentrate in implementing the agreed interface definition. This enables parallel development as one does not have to depend on another’s work during the development process.
    3.As long as the interface definitions are not changed, adding new features or re-implementing existing features for various reasons like changes in business rules will not break the existing system, rather makes it rich and efficient over a period of time.
    4.Generates maintainable and clean source code – UI related code is separated from other parts of the system like data access layer and business/domain related layer.
    5.Unit testing that every developer should embrace can be utilised. It can be performed independent of the UI or any other layer consuming functionalities of the interface based classes.
    Interfaces in C # provide a way to achieve runtime polymorphism
    70 Asp.net life cycle?
    The application life cycle has the following stages:
    •User makes a request for accessing application resource, a page. Browser sends this request to the web server.
    •A unified pipeline receives the first request and the following events take place:
    ◦An object of the ApplicationManager class is created.
    ◦An object of the HostingEnvironment class is created to provide information regarding the resources.
    ◦Top level items in the application are compiled.
    •Response objects are created . the application objects: HttpContext, HttpRequest and HttpResponse are created and initialized.
    •An instance of the HttpApplication object is created and assigned to the request. The request is processed by the HttpApplication class. Different events are raised by this class for processing the request.
    71.What is MSIL?
    MSIL : Microsoft Intermediate Language
    Definition:
    It is a set of CPU independent instructions that are generated by the language compiler when the project is compiled. MSIL code is not executable but further
    processed by CLR/other runtime environments before it becomes executable.
    MSIL is contained in the assembly of the .NET application.
    Features:
    MSIL instructions map to the code that is written in .NET Language and are used for loading, storing, initializing, and
    calling methods on objects, as well as for
    arithmetic and logical operations, control flow, direct
    memory access, exception handling, and other operations.
    CLS(Common language Specification) provides the infrastructure for MSIL.
    Benefits:
    1)MSIL provides language interoperability as the code in any .NET language is compiled into MSIL.
    2)Same performance for all the .NET Languages:
    3)Support for different runtime environments:
    CLR can understand MSIL.
    Non .NET environments also support MSIL.
    -----------------------------------------------------------
    The JIT Compiler in CLR converts the MSIL code into native machine code which is then executed by the OS
    72. What is the Linked List?
    Linked list is the most basic form of a data structure. A linked list is more or less similar to an array in that it can hold a list of values. But the similarity ceases here. The major difference between a linked list and array is that an array can hold values belonging to the same data type only whereas there is no such restriction on a linked list. For example, if an array is declared with type as int in C language, it can hold only integer values. Coming to a linked list, as it is a data structure, there is seldom any type associated with it.
    Apart from the above difference, there is one more difference that makes linked lists more versatile. It is not only possible to create linear linked lists but also circular linked lists i.e., the last element of the list can be made to point to the first. Another difference is that the memory to be allocated to a linked list can be specified dynamically i.e., we need not mention the number of elements in the linked list at the time of compilation. This facility may also be available for arrays in some languages but is not widely used.
    The most basic form of a linked list is created by creating a structure with one data element and a pointer to point to the next element in the data structure. The pointer of the last element is intialised to null to avoid it to point to some junk value if its a linear linked list. On the contrary, if it is a circular linked list, the pointer of the last element is made to point to the first element in the list.
    The above type of list allows traversing in only one direction. If we want bi-directional traversal, then we can create a structure with two pointers where one pointer is made to point to the previous element and the other point to the next element in the list. Modifications are made as stated above for a simple linked list to convert this to a circular list. Accordingly the above two types of lists are sometimes called single linked list and double linked list.
    Instead of using a single data element, we can use any number of data elements with several different data types within the structure. We may also use arrays as data elements of the linked list. An element in a linked list is often called a node. It is possible to add/delete nodes from any position within the linked list. According to the operation selected, the pointers need to be updated appropriately.
    73. How do you implement the thread synchronization?
    public class TestThreading { private System.Object lockThis = new System.Object(); public void Function() { lock (lockThis) { // Access thread-sensitive resources. } } }
                 private object _synchronizable = new object();
                  lock (this._synchronizable)
                    {
                       routingProxy.ProcessNextRoutedItem();
                    }
    74.View State?
    Web is Stateless. It means a new instance of the web page class is re-created each time the page is posted to the server. As we all know HTTP is a stateless protocol, its can't holds the client information on page. As for example , if we enter a text and client on submit button, text does not appear after post back , only because of page is recreated on its round trip.
    75. What is parent class for all results?
    action results
    76. View state and view bag?
    ViewState is within page life cycle while ViewData works in very different way. ViewData can be passed to the target .
    77. Garbage collector generations?

    • Generation 0. This is the youngest generation and contains short-lived objects. An example of a short-lived object is a temporary variable. Garbage collection occurs most frequently in this generation.
      Most objects are reclaimed for garbage collection in generation 0 and do not survive to the next generation.
    • Newly allocated objects form a new generation of objects and are implicitly generation 0 collections, unless they are large objects, in which case they go on the large object heap in a generation 2 collection.

    • Generation 1. This generation contains short-lived objects and serves as a buffer between short-lived objects and long-lived objects.

    • Generation 2. This generation contains long-lived objects. An example of a long-lived object is an object in a server application that contains static data that is live for the duration of the process.
    78. Headers in wcf?

    79.What is the difference between jquery and data annotations?

    80.Asynchronous design pattern?

    81.Connection object is mutable or immutable?

    Mutable, we can change the object values.

    82.Single sign on tokens?

    83. Message queue how will invoke?

    Message queues provide an asynchronous communications protocol, meaning that the sender and receiver of the message do not need to interact with the message queue at the same time. Messages placed onto the queue are stored until the recipient retrieves them. Message queues have implicit or explicit limits on the size of data that may be transmitted in a single message and the number of messages that may remain outstanding on the queue.

    84 SOA?

    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. Some means of connecting services to each other is needed.

    85 Can I use static members in non static classes?

    Yes
    86. Count no of characters and special characters and numbers in a string?

      public static string FindSpl(string loginid)
            {
                string str = "hello@123:*&^789'!@#$*()_+=";
                int count = 0;
                foreach (char c in str)
                {
                    if (!char.IsLetterOrDigit(c.ToString(), 0))
                    {
                        count++;
                    }
                }
                return(count.ToString());
            }
    87. How to prevent the dead lock in c#?

    88. Custom http Handlers?
    89.System.GC.SuppressFinalizer
    Requests that the system not call the finalizer for the specified object.
    90.HTTP Handlers and HTTP Modules
    91.How will you manage session in ASP.Net?
    Asp.Net provides the HttpSessionState class to store session state values. An instance of Http Session state class for each http request is accessible throughout your application using static httpcontext.current.session property.
    92..What is Auto Event wire up ?
    Asp.Net pages automatically bind page events to methods that have the name Page_events. This is automatically binding is configured by the Auto Event wireup attribute in the @ page directive, which is set to true by default in C#. If you set Auto event wire up to false the page doesn't automatically search for methods that use the page_events
    Auto Event wire up=false and c# auto event wire up=true.
    93. What is cookie less session?
    The session id will not be stored in the cookie instead, the runtime will insert the session id in the page URL so that it can extract that ID cookie that uses submit the page

    95. Log out code snippet?
    96. Master page having one control , How will I used in my page?
    97. What is the scope of Static?
    98. Session Modes? 





















  • InProc.
  • StateServer.
  • SQLServer.
  • Custom.
  • 99. What is web garden?
    When two or more worker process are configured as part of an application pool they form what is referred to as a web garden.
    A model in which multiple processes run on multiple CPUs in a single Server machine is know as a web garden.
    100. Http Handlers?
    These are used for handling Http Request with specified file type.
    101. Longest common substring?
    abbaaaa ans :aaaa
    using System;
    using System.Text;

    namespace Roshan
    {

    class Program
    {

    static void Main(string[] args)
    {

    Console.WriteLine("Longest repeated substring Problem");
    Console.WriteLine("———————————–");
    do
    {

    Console.WriteLine("Please enter input string");
    string input = Console.ReadLine();


    string result = LongestRepeatedSubstring(input);


    Console.WriteLine("length: " + result.Length + " substring:" +result.Substring(0,1));
    Console.WriteLine("");
    Console.WriteLine("Try another, Press any key. To exit, enter exit");
    }

    while (Console.ReadLine() != "exit");
    }



    //returns the longest repeated substring in input string
    private static string LongestRepeatedSubstring(string input)
    {

    if (string.IsNullOrEmpty(input))
    {

    return null;
    }



    int N = input.Length;
    string[] substrings = new string[N];


    //form an array of substring i to N
    for (int i = 0; i < N; i++)
    {

    substrings[i] = input.Substring(i);

    }



    //Sort the array
    Array.Sort(substrings);


    string result = "";
    for (int i = 1; i < N - 1; i++)
    {

    string lcp = LongestCommonString(substrings[i]);
    if (lcp.Length > result.Length)
    {

    result = lcp;

    }

    }

    return result;
    }



    //returns the longest common matching substring between two string
    private static string LongestCommonString(string a)
    {

    //int n = Math.Min(a.Length, b.Length);
    string result = "";
    char ch = a[0];
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < a.Length; i++)
    {

    if (ch == a[i])
    {

    result = result + a[i];

    }

    else
    {

    break;
    }

    }

    return result;
    }

    }

    }
    ------------------------------------------------------------------
    2nd approach
    Dictionary<char, int> dict = new Dictionary<char, int>();

    int max = 0;

    foreach (char c in "abbbbccccccd")

    {

    int i;

    dict.TryGetValue(c, out i);

    i++;

    if (i > max)

    {

    max = i;

    }

    dict[c] = i;

    }

    foreach (KeyValuePair<char, int> chars in dict)

    {

    if (chars.Value == max)

    {

    Console.WriteLine("{0}: {1}", chars.Key, chars.Value);

    }

    }

    Console.ReadLine();
    102.Asp.net Page life cycle?

    page request,start,page initialization,Load , validation,post back event handling, rendering and unload.

    Page request:Page request occurs before page life cycle begins.
    start:Page properties such as request and response are set.At this stage page also determined whether the request is post back or new request and sets the ispostback  property
    Page Initialization:During the page initialization controls on the page are available and each control's  uniqueID property is set.

     Load:During load if the current request is post back control properties are loaded with information recovered from view state and control state.
    Validation:During validation, the validate method all validate controls is called which sets the IsValid property of individual validator control and of the page

    Post back event handling:if the request is a post back any event handlers called.

    Rendering:Before rendering , view state is saved for the page and all controls. During the rendering phase, the page calls render method for each control, providing a text writer that writes its output to outputstream of the page response property.

    Unload:Unloaod is called after page has been fully rendered, sent to the client and is ready to be discarded. At this point, page properties such as response and request are unloaded and any cleanup is performed.
    103. Lazy loading in Entity framework?
    Lazy loading means delaying the loading of related data until you specifically request it. For example, Student class contains StudentAddress as complex property. So context first loads all the students from the database then it will load address of particular student when we access StudentAddress property as below.
    Rules for lazy loading:

    1. context.Configuration.ProxyCreationEnabled should be true.

    1. context.Configuration.LazyLoadingEnabled should be true.

    1. Complex property should be defined as virtual. Context will not do lazy loading if the property is not define as virtual.
    http://www.codeproject.com/Articles/652556/Can-you-explain-Lazy-Loading

    Remove the Order from consturctor.

    public List
      customer cust=new customer()
      foreach(Order o1 in orders)
      {
      console.writeline(o1.ordernumber);//lazy loading calls now
      }

    104. Hash Table and dictionary?

    Dictionary:
    • It returns error if we try to find a key which does not exist.
    • It is faster than a Hashtable because there is no boxing and unboxing.
    • Only public static members are thread safe.
    • Dictionary is a generic type which means we can use it with any data type.

    Hashtable:
    • It returns null if we try to find a key which does not exist.
    • It is slower than dictionary because it requires boxing and unboxing.
    • All the members in a Hashtable are thread safe,
    • Hashtable is not a generic type,


    106. cluster index and non cluster index?


    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 nonkey 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.


    107.Tuple?
    Tuples are commonly used in four ways:
    • To represent a single set of data. For example, a tuple can represent a database record, and its components can represent individual fields of the record.
    • To provide easy access to, and manipulation of, a data set.
    • To return multiple values from a method without using out parameters (in C#) or ByRef parameters (in Visual Basic).
    • To pass multiple values to a method through a single parameter. For example, the Thread.Start(Object) method has a single parameter that lets you supply one value to the method that the thread executes at startup time. If you supply a Tuple<T1, T2, T3> object as the method argument, you can supply the thread’s startup routine with three items of data.




    110. how to call Entity frame work procedure call?
    111.cross site scripting?
    http://technet.microsoft.com/es-es/dd565647(v=vs.71).aspx

    112.How to: Pass Values Between ASP.NET Web Pages


    query string
    session
    post data
    prperty
    priviouspagetype


     
    
    

    114.Difference between Web Service in ASP.NET & WCF Service

    WCF is a replacement for all earlier web service technologies from Microsoft. It also does a lot more than what is traditionally considered as "web services".
    WCF "web services" are part of a much broader spectrum of remote communication enabled through WCF. You will get a much higher degree of flexibility and portability doing things in WCF than through traditional ASMX because WCF is designed, from the ground up, to summarize all of the different distributed programming infrastructures offered by Microsoft. An endpoint in WCF can be communicated with just as easily over SOAP/XML as it can over TCP/binary and to change this medium is simply a configuration file mod. In theory, this reduces the amount of new code needed when porting or changing business needs, targets, etc.
    ASMX is older than WCF, and anything ASMX can do so can WCF (and more). Basically you can see WCF as trying to logically group together all the different ways of getting two apps to communicate in the world of Microsoft; ASMX was just one of these many ways and so is now grouped under the WCF umbrella of capabilities
    .
    Web Services can be accessed only over HTTP
     it works in stateless environment, where WCF is flexible because its services can be hosted in different types of applications. Common scenarios for hosting WCF services are IIS,WAS, Self-hosting, Managed Windows Service.

    The major difference is that Web Services Use XmlSerializer. But WCF Uses DataContractSerializer which is better in Performance as compared to XmlSerializer.





     

      
    117. custom HTTP handlers?

    To create a custom HTTP handler, you create a class that implements the IHttpHandler interface to create a synchronous handler. Alternatively, you can implement IHttpAsyncHandler to create an asynchronous handler. Both handler interfaces require that you implement the IsReusable property and the ProcessRequest method. The IsReusable property specifies whether the IHttpHandlerFactory object (the object that actually calls the appropriate handler) can put the handler in a pool and reuse it to increase performance. If the handler cannot be pooled, the factory must create a new instance of the handler every time that the handler is needed.

    The ProcessRequest method is responsible for processing individual HTTP requests. In this method, you write the code that produces the output for the handler.
    HTTP handlers have access to the application context. This includes the requesting user's identity (if known), application state, and session information. When an HTTP handler is requested, ASP.NET calls the ProcessRequest method of the appropriate handler. The code that you write in the handler's ProcessRequest method creates a response, which is sent back to the requesting browser.

     public class MyHttpHandler : IHttpHandler
       {
          // Override the ProcessRequest method.
          public void ProcessRequest(HttpContext context)
          {
             context.Response.Write("
    This is an HttpHandler Test.
    ");
             context.Response.Write("Your Browser:
    "
    );
             context.Response.Write("Type: " + context.Request.Browser.Type + "
    "
    );
             context.Response.Write("Version: " + context.Request.Browser.Version);
          }

          // Override the IsReusable property.
          public bool IsReusable
          {
             get { return true; }
          }
       }

    " +
                    "HelloWorldModule: Beginning of Request" +
                    "

    ");
            }
        }





    " +
                    "HelloWorldModule: End of Request
    ");
            }
        }



    
    
    120. How to handle UN managed code?
    The code, which is developed outside .NET, Framework is known as unmanaged code.
    COM Callable Wrapper

    121. Async and await feathre in .net 4.5?
    122. One lakh recores how to load?

    http://www.nullskull.com/a/1247/implementing-continuous-scrolling-ui-pattern-in-aspnet.aspx


    123.  what is the purpose of web.config file usage?

    The web.config file contains information that controls module loading, security configuration, session state configuration, and application language and compilation settings. Web.config files can also contain application specific items such as database connection strings.

    124.Master pages?

    Master pages allow you to create a consistent look and behavior for all the pages (or group of pages) in your web application.
    A master page provides a template for other pages, with shared layout and functionality. The master page defines placeholders for the content, which can be overridden by content pages. The output result is a combination of the master page and the content page.
    The content pages contain the content you want to display.
    When users request the content page, ASP.NET merges the pages to produce output that combines the layout of the master page with the content of the content page.

    125. string and string builder?

    String is immutable. Immutable means once we create string object we cannot modify. Any operation like insert, replace or append happened to change string simply it will discard the old value and it will create new instance in memory to hold the new value.

    string builder
    String builder is mutable it means once we create string builder object we can perform any operation like insert, replace or append without creating new instance for every time.

    126.Role based security?
    127. Boxing and unboxing?
    Boxing is the process of converting a value type to the type object 
    128. async web method call using jquery?

    $("#txbDepartureCity").bind("change paste keyup", function () { $.ajax({ type: "POST", url: "/Default.aspx/getAutoComplete", data: "{'Element':'" + $(this).val() + "'}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (response) { alert(response.d); } }); });
    129. How to find the display name from ladp?


    string ldapPath = "LDAP://corp.net:389/dc=corp,dc=net";
            DirectoryEntry de = new DirectoryEntry(ldapPath);
            DirectorySearcher s = new DirectorySearcher(de);
    
            string userName = User.Identity.Name;
            s.Filter = "(name=" + userName + ")";
            
            s.PropertiesToLoad.Add("displayName");
            SearchResult sr = s.FindOne();
            
            Label1.Text = "Name is " + sr.Properties["displayName"] + "";
    
    
    
    130. Constant?

    Constant

    Constant fields or local variables must be assigned a value at the time of declaration and after that they cannot be modified. By default constant are static, hence you cannot define a constant type as static.
    1. public const int X = 10;
    A const field is a compile-time constant. A constant field or local variable can be initialized with a constant expression which must be fully evaluated at compile time.
    1. void Calculate(int Z)
    2. {
    3. const int X = 10, X1 = 50;
    4. const int Y = X + X1; //no error, since its evaluated a compile time
    5. const int Y1 = X + Z; //gives error, since its evaluated at run time
    6. }
    131. Readonly and const?
    A readonly field can be initialized either at the time of declaration or with in the constructor of same class. Therefore, readonly fields can be used for run-time constants.

    the value of a const field is set to a compile time constant.
    1. class MyClass
    2. {
    3. readonly int X = 10; // initialized at the time of declaration
    4. readonly int X1;
    5.  
    6. public MyClass(int x1)
    7. {
    8. X1 = x1; // initialized at run time
    9. }
    10. }

    132.Static constructor?
    A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.


    • A static constructor does not take access modifiers or have parameters.
    • A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
    • A static constructor cannot be called directly.
    • The user has no control on when the static constructor is executed in the program.
    • A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
    • Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.
    • If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.
    133.Private constructor?

    We can not create the instance of class outside of the class if constructor is private.





    No comments:

    Post a Comment