C# Interview Questions



Does C# support multiple-inheritance?
No.

Who is a protected class-level variable available to?
It is available to any sub-class (a class inheriting this class).

 Are private class-level variables inherited?

Yes, but they are not accessible. Although they are not visible or accessible via the class interface, they are inherited.

 Describe the accessibility modifier “protected internal”.
It is available to classes that are within the same assembly and derived from the specified base class.

 What’s the top .NET class that everything is derived from?
System.Object.

 What does the term immutable mean?
The data value may not be changed. Note: The variable value may be changed, but the original immutable data value was discarded and a new data value was created in memory.



 What’s the difference between System.String and System.Text.StringBuilder classes?
System.String is immutable. System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.

 What’s the advantage of using System.Text.StringBuilder over System.String?
StringBuilder is more efficient in cases where there is a large amount of string manipulation. Strings are immutable, so each time a string is changed, a new instance in memory is created.

 Can you store multiple data types in System.Array?
No.
 


 What’s the difference between the System.Array.CopyTo() and System.Array.Clone() ?
The Clone() method returns a new array (a shallow copy) object containing all the elements in the original array. The CopyTo() method copies the elements into another existing array. Both perform a shallow copy. A shallow copy means the contents (each array element) contains references to the same object as the elements in the original array. A deep copy (which neither of these methods performs) would create a new instance of each element's object, resulting in a different, yet identacle object.


 How can you sort the elements of the array in descending order?
By calling Sort() and then Reverse() methods.


 What’s the .NET collection class that allows an element to be accessed using a unique key?
HashTable.


What class is underneath the SortedList class?
A sorted HashTable.


 Will the finally block get executed if an exception has not occurred?
Yes.


 What’s the C# syntax to catch any possible exception?
A catch block that catches the exception of type System.Exception. You can also omit the parameter data type in this case and just write catch {}.


 Can multiple catch blocks be executed for a single try statement?
No. Once the proper catch block processed, control is transferred to the finally block (if there are any).


 Explain the three services model commonly know as a three-tier application.
Presentation (UI), Business (logic and underlying code) and Data (from storage or other sources).


What is the difference between login controls and Forms authentication?

  • Forms authentication can be easily implemented using login controls without writing any code.
  • Login control performs functions like prompting for user credentials, validating them and issuing authentication just as the FormsAuthentication class.
  • However, all that’s needs to be dne is to drag and drop the use control from the tool box to have these checks performed implicitly. 
  • The FormsAuthentication class is used in the background for the authentication ticket and ASP.NET membership is used to validate the user credentials. 

What is Fragment Caching in ASP.NET?

  • Fragment caching refers to the caching of individual user controls within a Web Form. 
  • Each user control can have independent cache durations and implementations of how the caching behavior is to be applied.
  • Fragment caching is useful when you need to cache only a subset of a page. 
  • Navigation bars, header, and footers are good candidates for fragment caching. 
Fragment caching allows to cache specific portions of the page rather than the whole page. It is done by implementing the page in different parts by creating everything in form of user controls and caching each user control individually.


What is partial classess in .net?

When there is a need to keep the business logic separate from the User Interface or when there is some class which is big enough to have multiple number of developers implement the methods in it, the class can be separated and written in different files as partial class.
The keyword partial must appear in each class.
//syntax for C#
Public partial class MyPartialClass1
{
         //code
}
// this code could be in file1
Public partial class MyPartialClass1
{
         //code
}
// this code could be in file2
Partial classes allow us to divide the class definition into multiple files (physically). Logically, all the partial classes are treated as a single file by the compiler.

Explain how to pass a querystring from an .asp page to aspx page.

Consider the following URL:
http:// localhost/form.aspx?param1=career&param2=ride
This html addresses use QueryString property to pass values between pages.
From the URL above the information obtained is:
form.aspx: which is the destination page for your browser.
Param1 is the first parameter, the value of which is set to career
Param2 is the first parameter, the value of which is set to ride
The ‘?’ marks the beginning of the QueryString
‘&’ is used as a separator between parameters.
private void formButtonSubmit_Click(object sender, System.EventArgs e)
{
Response.Redirect("form.aspx?Param1=" +
this.formTextfieldParam1.Text + "&Param2=" +
this. formTextfieldParam2.Text);
}
The above code is a submit button event handler and it sends the values of the query string to the second page.
The following code demonstrates how to retrieve these valus on the second page:
private void Page_Load(object sender, System.EventArgs e)
{
      this.form2TextField1.Text = Request.QueryString["Param1"];
      this. form2TextField2.Text = Request.QueryString["Param2"];
}

You can also use the following method to retrieve the parameters in the string:

for (int i =0;i < Request.QueryString.Count;i++)
{
        Response.Write(Request.QueryString[i]);
}
From HTML in asp page: <ahref="abc.aspx?qstring1=test">Test Query String</a>
From server side code: <%response.redirect "webform1.aspx?id=11"%>


Difference between src and Code-Behind

With the ‘src’ attribute, the source code files are deployed and are compiled by the JIT as needed.
Though the code is available to everyone with an access to the server (NOT anyone on the web), this method is preferred as it does away with the compilation of the DLLs.
‘CodeBehind’ attribute just has the VS.NET associate the code file with the aspx file. This is necessary since VS.NET automates the pre-compiling that is harder by hand.
Due to this the ‘Src’ attribute is done away with having only a DLL to be deployed enhancing the protection level even though it can be decompiled.
Src: is a way mention the name of the code-behind class to dynamically compile on the request for a page.
Code-behind: is the logic written behind the UI design file. It specifies the name of the compiled file that contains the class. Code-behind attribute is only used for.Net.

What is the difference between URL and URI?

A URL (Uniform Resource Locator) is the address of some resource on the Web. A resource is nothing but a page of a site. There are other type of resources than Web pages, but that's the easiest conceptually.
A URI is a unique identifier to usually a namespace.
Though it looks like a URL but it doesn’t have to necessarily locate any resource on the web.
URI is a generic term. URL is a type of URI.
URI - Uniform Resource Identifier: it’s a string and its responsibility is to identify a resource by meta-information. It gives information about only one resource.
URL - Uniform Resource Locator: identifies the resource on the net and tells it is obtainable using what protocols.

What is the Pre-Compilation feature of ASP.NET 2.0?

Previously, in ASP.NET, the pages and the code used to be compiled dynamically and then cached so as to make the requests to access the page extremely efficient. In ASP.NET 2.0, the pre-compilation feature is used with which an entire site is precompiled before it is made available to users.
 There is a pre-defined folder structure for enabling the pre-compilation feature:
  • App_Code: stores classes
  • App_Themes: stores CSS files, Images, etc.
  • App_Data: stores XML files, Text Files, etc.
  • App_GlobalResources: stores all the resources at global level E.g. resx files, etc
  • App_LocalResources: stores all the resources at local/Page level
It is a process where things that can be handled before compilation are prepared in order to reduce the deployment time, response time, increase safety. It’s main aim to boost performance.
It also helps in informing about the compilation failures.
During development, it allows you to make changes to the web pages and reuse it using the same web browser to validate the changes without compiling the entire website.
During deployment, it generates the entire website folder structure in the destination. All the static files are copied to the folder and bin directory would later on contain the compiled dll.

What are ILDASM and Obfuscator in NET?

  • ILDASM (Intermediate Language Disassembler)
    De-Compilation is the process of getting the source code from the assembly.
    ILDASM is a de-compiler provided by Microsoft.
    This ILDASM converts an assembly to instructions from which source code can be obtained.
  • Obfuscated code is source code or intermediate language that is very hard to read and understand.
    An obfuscator is a medium of making a program difficult to understand.
    The way the code runs remains unaffected although the obfuscator makes it harder to hack the code and hijack the program.
ILDASM is MSIL Disassmbler. This take a portable executable (PE), which consists of MSIL code, and creates a text file which can then be used as an input for ILASM.exe, which is MSIL assembler. ILDASM can parse any .Net dll or exe and shows information in human readable form. It displays MSIL, namespaces, types and interfaces. It's normally used to examine assemblies and understand what the assembly is capable of.
Obfuscator is a tool to protect .Net assemblies and exe files. The tool renames all possible symbols, types, interfaces, namespaces etc into meaningless values and removes all unnecessary information. This reduces the size of the assemblies and also helps in protecting the code. It's normally used to protect the assemblies from exposing information for reverse engineering.

What is the GAC? What problem does it solve?

Global Assembly Cache (GAC):
Any system that has the CLR (common language runtime) installed, has a machine-wide code cache known as GAC.
Assemblies deployed in the global assembly cache need to have a strong name.
The Global Assembly Cache tool (Gacutil.exe), provided by the .NET Framework SDK can be used to deploy assemblies to GAC.

What is a Windows Service and how does its lifecycle differ from a "standard" EXE?

A service opens before one log in. However, a standard exe can be opened after a log in only.
Windows Service applications are long-running applications that do not have a user interface. They do not even produce any visual output.
The user messages are written to the Windows Event Log.
Services can run under the context of any user or a system. They are controlled by the Service Control Manager by which they can be stopped, paused, and started.

What is serialization in .NET? What are the ways to control serialization?

Serialization is a process of taking an object and converting into a form so that it can be transported across the network.
The serialized data can also be stored at a location using de-serialization.
The data contains the state of the object by which it can be reconstructed.
Binary Serialization is a light and compact format.
SOAP Serialization is used in web Services.
XML Serialization provides custom serialization.

Describe the difference between Interface-oriented, Object-oriented and Aspect-oriented programming.

Interface oriented approach compels to develop the software based on the contract.
Object oriented approach emphasizes on its aspects like:
Abstraction
Encapsulation
Inheritance
Polymorphism
Cross cutting concerns cannot be implemented in object oriented programming.
That’s not the case with aspect-oriented. However, there is a risk of system failure in this situation.

What is the difference between XML Web Services using ASMX and .NET Remoting using SOAP?

  • XML Web services are more restricted than objects exposed over .NET Remoting.
  • XML Web services support open standards that target cross-platform use.
  • XML Web services are generally easier to create and due to the restricted nature of XML Web services, the design issues are simplified.
  • XML Web services support only SOAP message formatting, which uses larger XML text messages.
  • Communication with .NET Remoting can be faster than XML Web service communication with a binary formatter.
  • XML Web services are designed for use between companies and organizations.
  • XML Web services don't require a dedicated hosting program because they are always hosted by ASP.NET.
  • Consumers can use XML Web services just as easily as they can download HTML pages from the Internet. Thus there's no need for an administrator to open additional ports on a firewall as they work through MS-IIS and ASP.NET

What is the JIT? What is NGEN? What are limitations and benefits of each?

Just In Time Compiler compiles the code just before it is run.
Due to this the code takes longer time to start however it is more efficient compilation since the compiler has more information about the target system.

NGen is used to pre-just in time code which yields faster startup time but the compiler produces less efficient code because it has less information.

What is the difference between Finalize() and Dispose()?

Dispose() is called by as an indication for an object to release any unmanaged resources it has held.
Finalize() is used for the same purpose as dispose however finalize doesn’t assure the garbage collection of an object.
Dispose() operates determinalistically due to which it is generally preferred.

How does the XmlSerializer work? What ACL permissions does a process using it require?

The XmlSerializer constructor generates a pair of classes derived from XmlSerializationReader and XmlSerializationWriter by analysis of the classes using reflection.
Temporary C# files are created and compiled into a temporary assembly and then loaded into a process.
The XmlSerializer caches the temporary assemblies on a per-type basis as the code generated like this is expensive. This cached assembly is used after a class is created
Therefore the XmlSerialize requires full permissions on the temporary directory which is a user profile temp directory for windows applications.

How does the XmlSerializer work? What ACL permissions does a process using it require?

The XmlSerializer constructor generates a pair of classes derived from XmlSerializationReader and XmlSerializationWriter by analysis of the classes using reflection.
Temporary C# files are created and compiled into a temporary assembly and then loaded into a process.
The XmlSerializer caches the temporary assemblies on a per-type basis as the code generated like this is expensive. This cached assembly is used after a class is created
Therefore the XmlSerialize requires full permissions on the temporary directory which is a user profile temp directory for windows applications.

Explain how to add controls dynamically to the form using C#.NET.

The following code can be called on some event like page load or onload of some image or even a user action like onclick
protected void add_button(Button button)
{
   try
   {
        panel1.Controls.Add(button); // Add the control to the container on a page
   }
   catch (Exception ex)
   {
         label1.Text += ex.Message.ToString();
   }
}

What are Extender provider components? Explain how to use an extender provider in the project.

An extender provider is a component that provides properties to other components.
Implementing an extender provider:
  • Use the ProvidePropertyAttribute, which specifies the name of the property that an implementer of IExtenderProvider provides to other components, attribute to specify the property provided by your extender provider.
  • Implement the provided property.
  • Track which controls receive your provided property.
  • Implement the IExtenderProvider, which defines the interface for extending properties to other components in a containe, interface.

Describe the configuration files in .Net. What are different types of configuration files in .Net framework?

The Machine.Config file, which specifies the settings that are global to a particular machine.
This file is located at the following path:
\WINNT\Microsoft.NET\Framework\[Framework Version]\CONFIG\machine.config
The simplest way to add application-specific settings into an application configuration file is to use an application configuration file.
The file is an XML file and contains add elements with key and value attributes.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
      <add key="ApplicationTitle" value="Sample Console Application" />
     <add key="ConnectionString"value="Server=localhost;Database=Northwind;Integrated Security= false;UserId=sa;Password=;" />
</appSettings>
</configuration>
<authentication> The authentication section controls the type of authentication used within your Web application Windows, Forms or Passport type of authentication can be defined.
Eg: <authentication mode="Windows" />
<allow> or <deny> tags can be used with authorization to allow or deny access to your web application to certain users or roles,
<authorization>
      <allow roles="Administrators,Users" />
      <deny users="*" />
</authorization>

Describe the accessibility modifier "protected internal" in C#.

The Protected Internal access modifier can be accessed by:
Members of the Assembly
The inheriting class
The class itself
Its access is limited to the types derived from the defining class in the current assembly or the assembly itself.

What is the difference between Debug.Write and Trace.Write? When should each be used?

Debug.Write: Debug Mode, Release Mode (used while debuging a project)
Trace.write: Release Mode (used in Released verion of Applications)

Explain the use of virtual, sealed, override, and abstract.

The virtual keyword enables a class to be overridden. If it has to be prevented from being overridden, then the sealed keyword needs to be used. If the keyword virtual is not used, members of the class can even then be overridden. However, its usage is advised for making the code meaningful.
The override keyword is used to override the virtual method in the base class. Abstract keyword is used to modify a class, method or property declaration. You cannot instantiate an abstract class or make calls to an abstract method directly.
An abstract virtual method means that the definition of the method needs to be given in the derived class.

What benefit do you get from using a Primary Interop Assembly (PIA)?

A primary interop assembly contains type definitions (as metadata) of types implemented with COM.
Only a single PIA can exist, which needs to be signed with a strong name by the publisher of the COM type library.
One PIA can wrap multiple versions of the same type library.
A COM type library imported as an assembly can be a PIA only if it has been signed and published by the same publisher.
Therefore, only the publisher of a type library can produce a true PIA, that can be considered as the unit of an official type definition for interoperating with the underlying COM types.

Explain the use of static members with example using C#.NET.

Static members are not associated with a particular instance of any class.
They need to be qualified with the class name to be called.
Since they are not associated with object instances, they do not have access to non-static members.
i.e.: "this" cannot be used, which represents the current object instance.

How to achieve polymorphism in C#.NET?

Polymorphism is when a class can be used as more than one type through inheritance. It can be used as its own type, any base types, or any interface type if it implements interfaces.
It can be achieved in the following ways:
Derived class inherits from a base class and it gains all the methods, fields, properties and events of the base class.
To completely take over a class member from a base class, the base class has to declare that member as virtual.

What are implementation inheritance and interface inheritance?

Implementation inheritance is achieved when a class is derived from another class in such a way that it inherits all its members.
Interface inheritance is when a class inherits only the signatures of the functions from another class.

How to add a ReadOnly property in C#.NET?

Properties can be made read-only by having only a get accessor in the implementation.
public class X
{
          public X(int id)
          {
               x_id = id;
          }
          public int ID
          {
              get
              {
                   return x_id;
              }
          }
}

How to prevent a class from being inherited in C#.NET?

The sealed modifier is used to prevent derivation from a class. An error occurs if a sealed class is specified as the base class of another class. A sealed class cannot also be an abstract class.

What are generics in C#.NET?

Generic types to maximize code reuse, type safety, and performance.
They can be used to create collection classes.
Generic collection classes in the System.Collections.Generic namespace should be used instead of classes such as ArrayList in the System.Collections namespace.

What is C#.NET Generics?

The classes and the methods can treat the values of different types uniformly with the use if generics.
The usage of generics is advantageous as:
  • They facilitate type safety
  • They facilitate improved performance
  • They facilitate reduced code
  • They promote the usage of parameterized types
  • The CLR compiles and stores information related to the generic types when they are instantiated. (The generic type instance refers to the location in memory of the reference type to which it is bound for all the instances of the generic type.)
Generics allow you to define type-safe data structures, without committing to actual data types. It allows writing less but more effective code. Generic provides flexibility and power but the developer needs to be responsible while using it.

What is the use of GetCommandLineArgs() method in C#.NET?

With GetCommandLineArgs() method, the command line arguments can be accessed.
The value returned is an array of strings.

What is the use of System.Environment class in C#.NET?

The System.Environment class can be used to retrieve information like:
command-line arguments
the exit code
environment variable settings
contents of the call stack
time since last system boot
the version of the common language runtime.
What is the difference between const and readonly in C#.NET? The read only can be modified by the class it is contained in. However, the const cannot

Advantages of CLR procedure over T-SQL procedure

  • The use of the CLR procedure makes it possible to do the complex database operations without having an in-depth knowledge of T-SQL.
  • It also enables focusing the business layer towards the database in orderto increase the server performance by avoiding unnecessary server trips.
  • Also, with the help of the .NET Base Class Libraries, the complex logical operations can be effectively performed.
  • It deals with automatic garbage collection, memory management, exception handling, etc. due to which it is known as Managed Procedure.
  • The concepts of the OOP can also be applied.
  • It provides the ability to leverage the features of .NET Code Access Security (CAS) to prevent assemblies from performing certain operations.
CLR (common language runtime): is the core of the .NET Framework and it provides the environment for all managed code. The CLR provides all the services that are needed for the code to execute, JIT compilation, exception handling etc.
  • .NET Framework allows solving complex logic operations for e.g. string manipulations, threading operations, encoding/decoding using cryptography.
  • CLR supports garbage collection, memory management, exception handling. This makes it more effective over T-SQL.
  • CLR allows the code to be more secure through code access security (CAS) to prevent assemblies from performing few processes.

How does C#.NET Generics and C++ Templates compare?

C# generics and templates in C++ are more or less similar syntactically.
  • C# Generic types are strong typed. C++ Templates are loosely typed.
  • C# Generic types are instantiated at the runtime. C++ templates are instantiated at the compile time.
  • C# Generic types do not permit the type parameters to have default values. C++ templates do.

How does C# Generics and C++ Templates compare?

C# generics are a simpler approach to parameterized types without the complexity of C++ templates In addition, C# does not attempt to provide all of the functionality that C++ templates provide.
a. C# generics are more flexible than c++ templates.
b. C# does not allow type parameters to have default types.
c. Partial specialization is not supported by C# generics
d. C# generics are simpler that C++ templates

What is an object pool in .NET?

An object pool is a container of objects that holds a list of other objects that are ready to be used.
It keeps track of:
  • Objects that are currently in use
  • The number of objects the pool holds
  • Whether this number should be increased
The request for the creation of an object is served by allocating an object from the pool.
This reduces the overhead of creating and re-creating objects each time an object creation is required.
It is a list of ready to use objects. Whenever a new request comes in for creating an object, then the application is served from this pool. This reduces the overhead of creating an object over and over again.

Why is an Object Pool required?

The request for the creation of an object is served by allocating an object from the pool.
This reduces the overhead of creating and re-creating objects each time an object creation is required.
To enhance performance and reduce the load of creating new objects, instead re using existing objects stored in memory pool. Object Pool is a container of objects that are for use and have already been created. Whenever an object creation request occurs, the pool manager serves the request by allocating an object from the pool. This minimizes the memory consumption and system's resources by recycling and re-using objects. When the task of an object is done, it is sent to the pool rather than being destroyed. This reduces the work for garbage collector and fewer memory allocations occur.

How does object pooling and connection pooling differ?

In Object pooling, you can control the number of connections.
In connection pooling, you can control the maximum number reached.
When using connection pooling, if there is nothing in the pool, a connection is created since the creation is on the same thread.
In object pooling, the pool decides the creation of an object depending on whether the maximum is reached which in case if it is, the next available object is returned. However, this could increase the time complexity if the object is heavy.
Object pooling allows you to control the number of connections being used, whereas connection pooling allows the control of maximum number reached.

Explain how to Implement an Object Pool in C#.NET.

using System;
using System.Collections;
namespace ObjectPool
{
      class ObjQueue
      {
           private static int maxSize = 2;
           private static readonly Queue objPool = new Queue(maxSize);
           public MyClass GetMyClass()
           {
              MyClass oMyClass;
              if (MyClass.Counter >= maxSize && objPool.Count>0)
                   oMyClass = RetrieveFromPool();
              else
                   oMyClass = GetNewMyClass();
                   return oMyClass;
           }
           private MyClass GetNewMyClass()
           {
               MyClass myObj = new MyClass();
               objPool.Enqueue(myObj);
               return myObj;
           }
           protected MyClass RetrieveFromPool()
           {
               MyClass myObj;
               if (objPool.Count>0)
               {
                   myObj = (MyClass)objPool.Dequeue();
                   MyClass.Counter--;
              }
              else
                   myObj = new MyClass();
                   return myObj;
          }
}
class MyClass
{
          public static int Counter = 0;
          public MyClass() { ++Counter; }
          private string _Firstname;
          public string Firstname
          {
               get { return _Firstname; }
               set { _Firstname = value; }
          }
}}

Explain how to Implement an Object Pool in C#.NET.

Creating pool manager.
public sealed class MyPoolManager
{
       private Queue poolQ = new Queue();
       private Hashtable tblPool = new Hashtable();
       private static readonly object objLock = new object();
       private const int PoolSize = 10;
       private int count = 0;
       private static MyPoolManager poolManager = null;
       /// <summary>
       /// Private constructor to prevent instantiation
       /// </summary>
       private MyPoolManager()
       {
       }
    static MyPoolManager()
     {
          poolManager = new MyPoolManager();
     }
      public static MyPoolManager Instance
      {
           get
           {
                if (poolManager != null)
                {
                     return poolManager;
                }
                      return null;
            }
       }
      public void CreatePoolObjects(object obj)
      {
             object _obj = obj;
             count = 0;
             poolQ.Clear();
             tblPool.Clear();
             for (int objCounter = 0; objCounter < PoolSize; objCounter++)
             {
                  _obj = new object();
                  lock (objLock)
                  {
                        tblPool.Add(_obj.GetHashCode(), _obj);
                        poolQ.Enqueue(_obj);
                        count++;
                   }
              }
       }
       public bool AddObjectToPool(object obj)
       {
            if (count == PoolSize)
                 return false;
             lock (objLock)
             {
                   tblPool.Add(obj.GetHashCode(), obj);
                   poolQ.Enqueue(obj);
                   count++;
             }
                    return true;
         }
       public object ReleaseObjectFromPool()
       {
            if (count == 0)
                  return null;

             lock (objLock)
             {
                   tblPool.Remove(poolQ.Dequeue().GetHashCode());
                   count--;
                   if (poolQ.Count > 0)
                           return poolQ.Dequeue();
              }
                    return null;
         }
       public object ReleaseObjectFromPool(object obj)
       {
                if (count == 0)
                        return null;
                lock (objLock)
                {
                        tblPool.Remove(obj.GetHashCode());
                        count--;
                        PutInPoolAgain();
                        return obj;
               }
       }
       private void PutInPoolAgain()
       {
               if (poolQ.Count > 0)
                         poolQ.Clear();

               foreach (int key in tblPool.Keys)
               {
                      poolQ.Enqueue(tblPool[key]);
               }
       }
        public int CurrentObjectsInPool
        {
               get
               {
                    return count;
               }
         }
        public int MaxObjectsInPool
        {
                  get
                  {
                          return PoolSize;
                  }
         }
}
using MyPoolManager
object obj1 = new object();
object obj2 = new object();
MyPoolManager poolManager = MyPoolManager.Instance;
poolManager.AddObjectToPool(obj1);
poolManager.AddObjectToPool(obj2);
MessageBox.Show(poolManager.CurrentObjectsInPool.ToString());
poolManager.ReleaseObjectFromPool(obj1);
MessageBox.Show(poolManager.CurrentObjectsInPool.ToString());
object obj = null;
for(;;)
{
       obj = poolManager.ReleaseObjectFromPool();
       if(obj != null)
            MessageBox.Show(obj.GetHashCode().ToString());
       else
       {
            MessageBox.Show("No more objects in the pool");
            break;
       }
}

Describe the three major components that make up a Web Service.

  • SOAP (Simple Object Access Protocol)
  • UDDI (Universal Description, Discovery and Integration)
  • WSDL (Web Services Description Language)
  • XML – provides a standard way to interact and provide language neutral format exchanging data.
  • WSDL – it describes the web service
  • UDDI – Universal Description Discovery and Integration- Interface to fetch web service data.

Explain with code sample how to Implement a Web Service in .NET

Following is a VBScript example
"WebMethod()" converts the functions in your application into web services
Example:
<%@ WebService Language="VBScript" Class="KmToMConvert" %>
Imports System
Imports System.Web.Services
Public Class KmToMConvert :Inherits WebService
   <WebMethod()> Public Function KilometerToMeter(ByVal Kilometer As String) As String
         return (Kilometer * 1000)
         end function
end class
[WebService(Namespace = http://tempuri.org/)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
     [WebMethod]
     public string HelloWorld()
     {
            return "Hello World";
     }
}

What are ILDASM and Obfuscator in NET?

  • ILDASM (Intermediate Language Disassembler)
    De-Compilation is the process of getting the source code from the assembly.
    ILDASM is a de-compiler provided by Microsoft.
    This ILDASM converts an assembly to instructions from which source code can be obtained.
  • Obfuscated code is source code or intermediate language that is very hard to read and understand.
    An obfuscator is a medium of making a program difficult to understand.
    The way the code runs remains unaffected although the obfuscator makes it harder to hack the code and hijack the program.
ILDASM is MSIL Disassmbler. This take a portable executable (PE), which consists of MSIL code, and creates a text file which can then be used as an input for ILASM.exe, which is MSIL assembler. ILDASM can parse any .Net dll or exe and shows information in human readable form. It displays MSIL, namespaces, types and interfaces. It's normally used to examine assemblies and understand what the assembly is capable of.
Obfuscator is a tool to protect .Net assemblies and exe files. The tool renames all possible symbols, types, interfaces, namespaces etc into meaningless values and removes all unnecessary information. This reduces the size of the assemblies and also helps in protecting the code. It's normally used to protect the assemblies from exposing information for reverse engineering.

Explain how Obfuscator works.

  • Obfuscators protect the source code from being hacked. Encryption and Decryption are processes from where you can get the data back.
  • However these differ from what obfuscation is. In obfuscation, a program become out of the reach of hackers although it functions the same way it is supposed to.
  • Optimizations too get applied to the process of obfuscation in order to make the program fast.
Obfuscator simply renames all types and namespace etc to meaningless code making it non human readable. This diminishes the possibility of reverse engineering.
e.g.:
private void AddEmp(Employee employee)
{
   {
      this.EmpList.Add(employee);
   }
}
gets converted to
private void a(a b)
{
    {
      a.a.Add(b);
    }
}

 

What are delegates and why are they required?

The delegates in .NET are like the pointers to the functions in C/C++. The difference is that these are type safe unlike the once in C/C++.
There are situations where in a programmer or an application needs to perform an action on a particular event. Eg: Some user action like click, text change, etc. So when these actions are performed by the user, the delegates invoke the respective functions.
Delegates are like type safe function pointers. We need delegates as they can be used to write much more generic functions which are type safe also.
It encapsulates the memory address of a function in the code. Events are created using delegates in .Net. When an event is published/thrown, the framework examines the delegate behind the event and then calls the function that is referred to by the delegate.

Explain how to implement Delegates in C#.NET

Here is an implementation of a very simple delegate that accepts no parameters.
public delegate void MyDelegate();// Declaration
class MyClass
{
     public static void MyFunc()
     {
         Console.WriteLine("MyFunc Called from a Delegate");
     }
     public static void Main()
     {
            MyDelegate myDel = new MyDelegate(MyFunc);
            myDel();
      }
}
namespace Delegates
{
         public delegate int DelegateToMethod(int x, int y);

         public class Math
         {
                public static int Add(int a, int b)
                {
                      return a + b;
                }
          public static int Multiply(int a, int b)
          {
               return a * b;
          }
          public static int Divide(int a, int b)
          {
                 return a / b;
          }
       }
       public class DelegateApp
       {
            public static void Main()
            {
                   DelegateToMethod aDelegate = new DelegateToMethod(Math.Add);
                   DelegateToMethod mDelegate = new DelegateToMethod(Math.Multiply);
                   DelegateToMethod mDelegate = new DelegateToMethod(Math.Multiply);
                   DelegateToMethod dDelegate = new DelegateToMethod(Math.Divide);
                   Console.WriteLine("Calling the method Math.Add() through the aDelegate object");
                   Console.WriteLine(aDelegate(5, 5));
                   Console.WriteLine("Calling the method Math.Multiply() through the mDelegate object");
                   Console.WriteLine(mDelegate(5, 5));
                   Console.WriteLine("Calling the method Math.Divide() through the dDelegate object");
                   Console.WriteLine(dDelegate(5, 5));
                   Console.ReadLine();
            }
       }
}

CLR Triggers

A CLR trigger could be a Date Definition or Date Manipulation Language trigger or could be an AFTER or INSTEAD OF trigger.
Methods written in managed codes that are members of an assembly need to be executed provided the assembly is deployed in SQL 2005 using the CREATE assembly statement.
The Microsoft.SqlServer.Server Namespace contains the required classes and enumerations for this objective.
One can create a database object inside SQL Server that is developed in an assembly created in .Net CLR - it’s a special type of stored procedure that executes on an event. CLR triggers can reference data in the inserted and deleted tables, know about modified columns after an update statement, and access information about objects affected in the database as a result of DDL statements.

Steps for creating CLR Trigger

Follow these steps to create a CLR trigger of DML (after) type to perform an insert action:
  • Create a .NET class of triggering action
  • Make an assembly (.DLL) from that Class
  • Enable CLR environment in that database.
  • Register the assembly in SQL Server
  • Create CLR Trigger using that assembly
Steps:
  • Define the trigger as a class and build the assembly
  • Register assembly in SQL Server using CREATE ASSEMBLY.
  • Create the trigger that reference the created assembly.


1 comment:

  1. Hi

    I like this post:

    You create good material for community.

    Please keep posting.

    Let me introduce other material that may be good for net community.

    Source: Student teacher interview questions

    Best rgs
    Peter

    ReplyDelete