Wednesday, 3 August 2011

Delegate

What is a Delegate?

Delegate is a type which  holds the method(s) reference in an object. It is also referred to as a type safe function pointer.

Advantages

  • Encapsulating the method's call from caller
  • Effective use of delegate improves the performance of application
  • Used to call a method asynchronously

Declaration

public delegate type_of_delegate delegate_name()
Example:
public delegate int mydelegate(int delvar1,int delvar2)
 


Multicast Delegate

What is Multicast Delegate?

It is a delegate which holds the reference of more than one method.
Multicast delegates must contain only methods that return void, else there is a run-time exception.


Sample Program using Delegate

public delegate double Delegate_Prod(int a,int b);
class Class1
{
    static double fn_Prodvalues(int val1,int val2)
    {
        return val1*val2;
    }
    static void Main(string[] args)
    {
        //Creating the Delegate Instance
        Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);
        Console.Write("Please Enter Values");
        int v1 = Int32.Parse(Console.ReadLine());
        int v2 = Int32.Parse(Console.ReadLine());
        //use a delegate for processing
        double res = delObj(v1,v2);
        Console.WriteLine ("Result :"+res);
        Console.ReadLine();
    }
}

Simple Program using Multicast Delegate

delegate void Delegate_Multicast(int x, int y);
Class Class2
{
    static void Method1(int x, int y)
    {
        Console.WriteLine("You r in Method 1");
    }

    static void Method2(int x, int y)
    {
        Console.WriteLine("You r in Method 2");
    }

    public static void "on" />Main()
    {
        Delegate_Multicast func = new Delegate_Multicast(Method1);
        func += new Delegate_Multicast(Method2);
        func(1,2);             // Method1 and Method2 are called
        func -= new Delegate_Multicast(Method1);
        func(2,3);             // Only Method2 is called
    }
}

 

Common Interview Questions

Basics


Explain the differences between Server-side and Client-side code?
  Server side code will execute at server (where the website is hosted) end, & all the business logic will execute at server end where as client side code will execute at client side (usually written in javascript, vbscript, jscript) at browser end.


What is the use of a multicast delegate?
Ans. A multicast delegate may be used to call more than one method.




What is the use of Singleton pattern?
Ans. A Singleton pattern .is used to make sure that only one instance of a class exists.


What is the use of a private constructor?
Ans. A private constructor may be used to prevent the creation of an instance for a class


Is it possible to debug java-script in .NET IDE? If yes, how?
Ans. Yes, simply write "debugger" statement at the point where the breakpoint needs to be set within the javascript code and also enable javascript debugging in the browser property settings.




Which method is used to redirect the user to another page without performing a round trip to the client?
Ans. Server.Transfer method.


What is an .ashx file?
Ans. It is a web handler file that produces output to be consumed by an xml consumer client (rather than a browser). 


What is a Delegate?
Ans. A delegate is a strongly typed function pointer object that encapsulates a reference to a method, and so the function that needs to be invoked may be called at runtime.




What’s a strong name? 

Strong Name:-A strong name includes the name of the assembly, version number, culture identity, and a public key token.

How do I make a DLL in C#? 

To make a Dll in C# we need to use the /target:library compiler option



What is the difference between const and static read-only? 

The difference is that static read-only can be modified by the containing class, but const can never be modified and must be initialized to a compile time constant. To expand on the static read-only case a bit, the containing class can only modify it: -- in the variable declaration (through a variable initializer). -- in the static constructor (instance constructors if it's not static). 









Are MSIL and CIL the same thing?
Ans. Yes, CIL is the new name for MSIL.


  What is a Satellite Assembly?
Ans. Satellite assemblies contain resource files corresponding to a locale (Culture + Language) and these assemblies are used in deploying an application globally for different languages.




How to register a client side script from code-behind?
Ans. Use the Page.RegisterClientScriptBlock method in the server side code to register the script that may be built using a StringBuilder. 


How to instruct the garbage collector to collect unreferenced data?
Ans. We may call the garbage collector to collect unreferenced data by executing the System.GC.Collect() method. 


How to set the default button on a Web Form?
Ans. <asp:form id="form1" runat="server" defaultbutton="btnGo"/>


What is Boxing and Unboxing?
Ans. Boxing is the process where any value type can be implicitly converted to a reference type object while Unboxing is the opposite of boxing process where the reference type is converted to a value type.


What is the access modifier of a member function of in an Interface created in .NET?
Ans. It is always public, we cant use any other modifier other than the public modifier for the member functions of an Interface.




What is a HashTable in .NET?
Ans. A Hashtable is an object that implements the IDictionary interface, and can be used to store key value pairs. The key may be used as the index to access the values for that index.


What is an ArrayList in .NET?
Ans. Arraylist object is used to store a list of values in the form of a list, such that the size of the arraylist can be increased and decreased dynamically, and moreover, it may hold items of different types. Items in an arraylist may be accessed using an index.


What does the virtual keyword in C# mean?
Ans. The virtual keyword signifies that the method and property may be overridden.


What is the use of Finalize method in .NET?
Ans. .NET Garbage collector performs all the clean up activity of the managed objects, and so the finalize method is usually used to free up the unman-aged objects like File objects, Windows API objects, Database connection objects, COM objects etc.



How do you save all the data in a dataset in .NET?
Ans. Use the AcceptChanges method which commits all the changes made to the dataset since last time Acceptchanges was performed.




Can we achieve operator overloading in VB.NET?
Ans. Yes, it is supported in the .NET 2.0 version, the "operator" keyword is used.




How to prevent inheritance of a class in .NET?
Ans. Use the keyword NotInheritable in VB.NET and sealed in C#.


How to prevent overriding of a class in .NET?
Ans. Use the keyword NotOverridable in VB.NET and sealed in C#.


Is it possible to create a shared event in .NET?
Ans. Yes, but shared events may only be raised by shared methods.


Is it possible to specify an access specifier to an event in .NET?
Ans. Yes, though they are public by default.


How to refer to the current thread of a method in .NET?
Ans. In order to refer to the current thread in .NET, the Thread.CurrentThread method can be used. It is a public static property.


What does AddressOf in VB.NET operator do?
Ans. The AddressOf operator is used in VB.NET to create a delegate object to a method in order to point to it.






Is there a way to suppress the finalize process inside the garbage collector forcibly in .NET?
Ans. Use the GC.SuppressFinalize() method.




In .NET, is it possible for two catch blocks to be executed in one go?
Ans. This is NOT possible because once the correct catch block is executed then the code flow goes to the finally block. 




What is the use of the dispose() method in .NET?
Ans. The Dispose method in .NET belongs to IDisposable interface and it is best used to release unmanaged objects like File objects, Windows API objects, Database connection objects, COM objects etc from the memory. Its performance is better than the finalize() method.


Is there any difference between System.String and System.StringBuilder classes?
Ans. System.String is immutable by nature whereas System.StringBuilder can have a mutable string in which plenty of processes may be performed.


What is the difference between Web.config and Machine.Config in .NET?
Ans. Web.config file is used to make the settings to a web application, whereas Machine.config file is used to make settings to all ASP.NET applications on a server(the server machine).




Is it possible to stop the clientside validation of an entire page?
Ans. Set Page.Validate = false;


How do we enable tracing in .NET applications?
Ans. <%@ Page Trace="true" %>




Whats the difference between web.config and app.config?
Ans. Web.config is used for web based asp.net applications whereas app.config is used for windows based applications.


Validation


Which property of a validation control is used to associate it with a server control on that page?
 ControlToValidate property. 






Session Management
What method is used to explicitly kill a user's session?
 Session.Abandon()




How many ways can we maintain the state of a page?
Ans. 1. Client Side - Query string, hidden variables, viewstate, cookies
2. Server side - application , cache, context, session, database




ADO.NET


Which method is invoked on the DataAdapter control to load the generated dataset with data?
 Fill() method.


What property within the asp:gridview control is changed to bind columns manually?
Ans. Autogenerated columns is set to false

Global XML Web Services Architecture

The Global XML Web Services Architecture (GXA) platform is a term that encompasses a variety of proposed new standards in the area of Web services interoperability. A fair number of big corporate players are cooperating behind the curtain of GXA, including Microsoft and IBM.

The primary goal of GXA is to define the syntax and semantics of a new family of Web-service-specific protocols that take the basic capabilities of SOAP and XML to the next level of interoperability. While a lot of work has been done to create standards for Web services over the past few years, there is more to be done. This work consists mainly of enhancing and specializing the way in which Web services interact and interoperate. The GXA initiative is aimed at defining specifications for these infrastructure-related services that form a sort of abstract virtual machine for a new generation of Web services.

GXA highlights
A few years of real-world experience with Web services revealed that a large percentage of applications implement repetitive tasks that cut through a broad range of problem domains. Issues such as security and message routing are common to many, if not all, distributed enterprise-level applications. As such, they would be better addressed by ad hoc wire-level protocols than individually by each application.

For example, when SOAP was first introduced back in 1998, it was an XML-based protocol for remote procedure calls (RPC). Everyone who was interested in RPC over the Web had to learn how to write raw SOAP payloads. Today SOAP is perceived as a kind of low-level driver that platform-specific libraries abstract away and bury within the Web server’s infrastructure for Web services. Examples of this infrastructure are ASP.NET in the Microsoft .NET platform and Axis in the Apache open source world. In both cases, you create and consume Web services using classes in an object-oriented paradigm instead of dealing with raw SOAP payloads.

In a similar fashion, you currently must secure Web services yourself by writing similar pieces of code over and over again. You’re also responsible for having SOAP messages travel from an initial sender to the final receiver, potentially routed through a bunch of intermediaries.

GXA attempts to define SOAP-based protocols to deal with security, routing, and more, using a common and well-understood syntax and semantics. Companies involved with the development of the GXA extended infrastructure may one day bury the details of the protocols into some sort of virtual machine.

Extensions for building applications
The official definition of GXA is a protocol platform implemented as SOAP extensions for building Web-service-based applications. The list of extensions includes WS-Security, WS-Routing, plus support for transaction coordination, reliable message delivery, ubiquitous metadata, and more.

WS-Security proposes a standard set of SOAP extensions that can be used to implement data integrity and confidentiality in Web services. Its goal is to allow applications to exchange SOAP messages securely by integrating in the SOAP schema ad hoc extensions to deal with encryption and credentials.

WS-Routing is a stateless protocol for routing SOAP messages asynchronously over transportation means like TCP and HTTP. Headers that form the various protocols can be composed to form a richer context for the message that may also contain attachments.

WS-Attachments and Direct Internet Message Encapsulation (DIME) also fall under the umbrella of the GXA, and the number of specifications in GXA continues to grow.

Microsoft currently supports a WS-Security specific extension for .NET Web services, as does IBM in its WebSphere SDK for Web Services version 5.0. Although the WS-Routing specification exploits the concept of an intermediary already built in SOAP 1.1, Microsoft and IBM don't natively support WS-Routing yet.

The future of Web services
While the GXA focuses on interoperability, a committee within the W3C is concerned with creating new versions of the core Web service specifications. By design, W3C is continuously catching up with the progress of the technology. The committee attempts to standardize and formalize what is sometimes already established by the evolution of breakthrough products.

Although the GXA and W3C are doing different things (with GXA being one generation ahead), in a few years the definition and the implementation of Web services will have a unique grammar and a unique semantics. To be successful, Web services must seamlessly integrate with applications and with each other. For this to happen, the GXA must be entirely outlined and developed. When that process is complete, the W3C will standardize the results, and we’ll have a single specification.

As for GXA, Microsoft is committed to include a significant implementation of the standards in the next major release of the .NET platform (currently slated to be released around Q3 2004), and in the next version of Windows (codenamed Longhorn).

Best Practises For Web Service


  1. Call Web Methods Asynchronously 
  2. Use ExecuteXmlReader instead of DataSet
  3. Use Compression
  4. Using SOAP Extensions
  5. Use One-Way Method
  6. Using Transactions in Web Services
  7. SOAP, HTTP GET, HTTP Post
  8. Create instances in advance to preload all the referenced assemblies at the very beginning
  9. Use pre-authentication
  10. Edit IIS custom error messages




Call Web Methods Asynchronously

  • Invoking a web-method asynchronously means that an invoked member will perform its work on a different thread and after all the work is done, this member must notify the main thread and, optionally, pass the return values to it.
  • This seriously increases performance. If a complicated and slow web method is executed in a separate thread, the main application can proceed performing its tasks without waiting for a web method to complete.
  • To call a Web method asynchronously, you have the following choices:

    Create a new thread and call the method from there.
    Create a delegate object that matches the Web method signature and call it from there.
Use ExecuteXmlReader instead of DataSet

  • Using ExecuteXmlReader you can return an XmlDocument object or a string from a Web service.
  • You can fully control the response of a WebMethod.

    String sqlString = "SELECT CustomerID, CompanyName FROM Customers For XML AUTO";
    rdr = command.ExecuteXmlReader();
    rdr.Read();
    while (rdr.ReadState != System.Xml.ReadState.EndOfFile)
    {
        ret += rdr.ReadOuterXml();
    }
Use Compression
  • Compress the XML-traffic between the client and the server using the SOAPExtensions mechanism and any compression algorithm.
  • You can use a ZIP-compression for you data. There are a lot of open-source compression libraries for C#.
  • You can use a free library called SharpZipLib to compress your web methods. 
  • Adding a compression to your webservice is very easy: include the downloaded project into your solution, reference it in your webservice, and mark your web methods with [CompressionExtension] in the proxy-class code.
Using SOAP Extensions
  • Typically SOAP extensions are used to handle data encryption or to compress data to provide better performance. SOAP extensions are often used in conjunction with a custom SOAP header for user authentication.
  • You can use custom SOAP extensions to handle unhandled exceptions for Web services.
  • For this solution, code need to be added in AfterSerialize stage to check for unhanded SOAP exceptions.
  • SOAP extension can be used to override the processing of the SOAP message on the Web server. On the Web server, there are four stages associated with these steps. Each of these stages is repeated twice.

    1. BeforeSerialize
    2. AfterSerialize
    3. BeforeDeserialize
    4. AfterDeserialize
Use OneWay Method
  • In many cases, the Web method you expose through your Web service does not require a response from the client. In cases such as this, you can specify that your Web method is a one-way method by applying the OneWay attribute.
  • Applying this attribute makes your method perform more efficiently because it will not wait for a response from the client.
  • Your method will only process input parameters and cannot be used to return referenced values or throw exceptions.
  • In this caller does not get anything in return so it is called as one-way communication.

    [SoapDocumentMethod (OneWay=true)]
    [WebMethod]
    public string TestMethod()
    { } 
Using Transactions in Web Services
  • You can declare the Web service's transactional behaviour by setting the TransactionOption property of the WebMethod attribute applied to the Web service method.
  • XML Web service methods can only participate as the root object in a transaction, due to the stateless nature of the HTTP protocol.

    Example:
    using System.EnterpriseServices;
    public class Bank : WebService
    {
        [WebMethod(TransactionOption = TransactionOption.RequiresNew)]
        public int DeleteAuthor(string lastName)
        {
            //ContextUtil.SetAbort();
        }
    }
SOAP, HTTP GET, HTTP Post
  • By default, in .NET Framework 1.0, all three protocols are enabled. By default, in .NET Framework 1.1, HTTP GET and HTTP POST are both disabled. This is for security reasons.
  • Only HTTP POST and SOAP care about the Content-Type because they send the data in the body of the HTTP request. The HTTP GET protocol does not really care about the Content-Type because all of the parameters are packaged into the query string.
Create instances in advance to preload all the referenced assemblies at the beginning
Everybody notices that a first call to a web service takes more time to execute than the subsequent calls.
Why is that? Try to run your application in Debug mode and look at the "Output" window of Visual Studio.
  • Once a web method is invoked, the application loads a number of libraries like System.Web.dll, System.Web.Services.dll, System.XML.dll etc. And maybe other assemblies of your own, which describe some classes you, use to work with your web service.
  • This loading takes time, of course. So create an instance of a web service in advance, when your application starts.
  • This loads all the needed libraries in memory and saves time.
Using pre-authentication
  • Any call to a webservice's method generates at least one 401 error (and if you use "integrated Windows authentication", then there might be two or three 401 errors!). To avoid this, set PreAuthenticate to true.
  • But keep in mind that not all authentication methods used by the hosting web servers support pre-authentication if your hosting IIS-server uses "Windows Integrated Authentication", pre-authentication is not possible.
  • To speed-up the web service call, use the "basic" authentication scheme. Use it only with SSL-protected webservices and websites.
Edit IIS custom error messages
  • When something goes wrong, a web server displays an error message. The htm-files containing these messages are located in the c:\WINDOWS\Help\iisHelp\common\ server folder (if not, look at your IIS settings).
  • Edit these files to minimize traffic! Get rid of styles, tables, and other "beauties".
  • There' always a 401 error when a web-service is accessed. Even if PreAuthenticate is set to true, the 401-error will be generated when a Web Service is accessed for the first time. So minimize the 401-files.
  • Error 401.2 - Unauthorized: Access is denied due to server configuration.
  • IIS's default 401-2.htm is 5 kilobytes, but you can change it and it will be only 73 bytes long.

Basics of Web Services

Web services (sometimes called application services) are services (usually including some combination of programming and data, but possibly including human resources as well) that are made available from a business's Web server for Web users or other Web-connected programs

Users can access some Web services through a peer-to-peer arrangement rather than by going to a central server.


As Web services proliferate, concerns include the overall demands on network bandwidth and, for any particular service, the effect on performance as demands for that service rise. A number of new products have emerged that enable software developers to create or modify existing applications that can be "published" (made known and potentially accessible) as Web services.



Advantages


Web Services offer many benefits over other types of distributed computing architectures.

  • Interoperability - This is the most important benefit of Web Services. Web Services typically work outside of private networks, offering developers a non-proprietary route to their solutions. Services developed are likely, therefore, to have a longer life-span, offering better return on investment of the developed service. Web Services also let developers use their preferred programming languages. In addition, thanks to the use of standards-based communications methods, Web Services are virtually platform-independent.
  • Usability - Web Services allow the business logic of many different systems to be exposed over the Web. This gives your applications the freedom to chose the Web Services that they need. Instead of re-inventing the wheel for each client, you need only include additional application-specific business logic on the client-side. This allows you to develop services and/or client-side code using the languages and tools that you want.
  • Reusability - Web Services provide not a component-based model of application development, but the closest thing possible to zero-coding deployment of such services. This makes it easy to reuse Web Service components as appropriate in other services. It also makes it easy to deploy legacy code as a Web Service.
  • Deployability - Web Services are deployed over standard Internet technologies. This makes it possible to deploy Web Services even over the fire wall to servers running on the Internet on the other side of the globe. Also thanks to the use of proven community standards, underlying security (such as SSL) is already built-in.



Disadvantages


  • Although the simplicity of Web services is an advantage in some respects, it can also be a hindrance. Web services use plain text protocols that use a fairly verbose method to identify data. This means that Web service requests are larger than requests encoded with a binary protocol. The extra size is really only an issue over low-speed connections, or over extremely busy connections.
  • Although HTTP and HTTPS (the core Web protocols) are simple, they weren't really meant for long-term sessions. Typically, a browser makes an HTTP connection, requests a Web page and maybe some images, and then disconnects. In a typical CORBA or RMI environment, a client connects to the server and might stay connected for an extended period of time. The server may periodically send data back to the client. This kind of interaction is difficult with Web services, and you need to do a little extra work to make up for what HTTP doesn't do for you.
  • The problem with HTTP and HTTPS when it comes to Web services is that these protocols are "stateless"—the interaction between the server and client is typically brief and when there is no data being exchanged, the server and client have no knowledge of each other. More specifically, if a client makes a request to the server, receives some information, and then immediately crashes due to a power outage, the server never knows that the client is no longer active. The server needs a way to keep track of what a client is doing and also to determine when a client is no longer active.
  • Typically, a server sends some kind of session identification to the client when the client first accesses the server. The client then uses this identification when it makes further requests to the server. This enables the server to recall any information it has about the client. A server must usually rely on a timeout mechanism to determine that a client is no longer active. If a server doesn't receive a request from a client after a predetermined amount of time, it assumes that the client is inactive and removes any client information it was keeping. This extra overhead means more work for Web service developers.


    The "vanilla" XML SOAP+WSDL over HTTP web services implementation can be thought of as the core of an entire stack of protocols relating to web services. 




SOAP is a simple XML-based protocol to let applications exchange information over HTTP.
Or more simply: SOAP is a protocol for accessing a Web Service.

It is important for application development to allow Internet communication between programs.
Today's applications communicate using Remote Procedure Calls (RPC) between objects like DCOM and CORBA, but HTTP was not designed for this. RPC represents a compatibility and security problem; firewalls and proxy servers will normally block this kind of traffic.
A better way to communicate between applications is over HTTP, because HTTP is supported by all Internet browsers and servers. SOAP was created to accomplish this.
SOAP provides a way to communicate between applications running on different operating systems, with different technologies and programming languages.


SOAP Building Blocks

A SOAP message is an ordinary XML document containing the following elements:
  • An Envelope element that identifies the XML document as a SOAP message
  • A Header element that contains header information
  • A Body element that contains call and response information
  • A Fault element containing errors and status information

Skeleton SOAP Message

<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">

<soap:Header>
...
</soap:Header>

<soap:Body>
...
  <soap:Fault>
  ...
  </soap:Fault>
</soap:Body>

</soap:Envelope>



WSDL is a specification defining how to describe web services in a common XML grammar. WSDL describes four critical pieces of data:
  • Interface information describing all publicly available functions
  • Data type information for all message requests and message responses
  • Binding information about the transport protocol to be used
  • Address information for locating the specified service
Using WSDL, a client can locate a web service and invoke any of its publicly available functions. With WSDL-aware tools, you can also automate this process, enabling applications to easily integrate new services with little or no manual code. WSDL therefore represents a cornerstone of the web service architecture, because it provides a common language for describing services and a platform for automatically integrating those services.

Universal Description, Discovery and Integration (UDDI) is a directory service where businesses can register and search for Web services.


UDDI is a cross-industry effort driven by all major platform and software providers like Dell, Fujitsu, HP, Hitachi, IBM, Intel, Microsoft, Oracle, SAP, and Sun, as well as a large community of marketplace operators, and e-business leaders.

Over 220 companies are members of the UDDI community.

  XML-RPC

XML-RPC is a protocol that uses XML messages to perform Remote Procedure Calls. Requests are encoded in XML and sent via HTTP POST; XML responses are embedded in the body of the HTTP response.

More succinctly, XML-RPC = HTTP + XML + Remote Procedure Calls.

Because XML-RPC is platform independent, diverse applications can communicate with one another. For example, a Java client can speak XML-RPC to a Perl server.

To get a quick sense of XML-RPC, here is a sample XML-RPC request to a weather service (with the HTTP Headers omitted):

weather.getWeather
10016



The request consists of a simple element, which specifies the method name (getWeather) and any method parameters (zip code).

Here is a sample XML-RPC response from the weather service:

65

The response consists of a single element, which specifies the return value (the current temperature). In this case, the return value is specified as an integer.

In many ways, XML-RPC is much simpler than SOAP, and therefore represents the easiest way to get started with Web services.

The official XML-RPC specification is available at XML-RPC.com. Dozens of XML-RPC implementations are available in Perl, Python, Java, and Ruby. See the XML-RPC home page for a complete list of implementations.