Microsoft Silverlight

(formerly known as code name “WPF/E”)

Microsoft Silverlight is a cross-browser, cross-platform plug-in for delivering the next generation of .NET-based media experiences and rich interactive applications for the Web. Silverlight offers a flexible and consistent programming model that supports AJAX, Python, Ruby, and .NET languages such as Visual Basic and C#, and integrates with existing Web applications. Silverlight media capabilities include fast, cost-effective delivery of high-quality audio and video to all major browsers including Firefox, Safari, and Internet Explorer running on Mac or Windows.


Updated Silverlight 1.1 SDK Now Available


Get the Silverlight 1.1 Software Development Kit Alpha Refresh with an updated version of Silverlight.js and refreshed Quick Starts.

.NET Interview Question & Answer

What is the difference between .Net Remoting and Asp.Net Web Services?

ASP.NET Web Services Can be accessed only over HTTP but .Net Remoting Can be accessed over various protocols like TCP, HTTP, SMTP etc.

Web Services are based on stateless service architecture but .Net Remoting support for both stateful and stateless environment.

Web Services support heterogeneous environments means interoperability across platforms but .Net remoting requires .Net on both server and client end.

.NET Remoting provides the fast communication than Web Services when we use the TCP channel and the binary formatter.

Web services support only the objects that can be serialized but .NET Remoting can provide support to all objects that inherit MarshalByRefObject.

Web Services are reliable than .Net remoting because Web services are always hosted in IIS.

Web Services are ease to create and deploy but .Net remoting is bit complex to program.



What would be the common layers in an n- tier architecture based web application?
Common layers in an n- tier architecture

Presentation GUI: Look & Feel ,Html, aspx file, JavaScript, window forms etc.

Controller- Work flow layer: aspx.cs file, means event handlers and Data binding with controls etc.

Business Logic: where we implement business rules like add book, search library etc.

Data Access: SQLHelper.cs like create connection, get DataSet, Execute Query etc.

Physical Data: tables, views, stored procedures, indexes etc.



What are the different state management techniques used in asp.net for web applications?

In ASP.Net the state can be maintained in following ways
Server-side state management
Application objects
Session Variables
Database
Client-side state management
Cookies
Hidden input fields
Query String
ViewState


How to get records in random order from a sql query in sql server?
In SQL Server we can get records in random order from a sql query using NEWID() Function like:

SELECT Subject FROM dbo.forumThreads ORDER BY NEWID()

.NET Interview Question & Answer

What is the use of indexes and what are the types of indexes available in SQL Server?

Indexes are used to find data quickly when a query is processed in any relational database. Indexes improve performance by 10 to 500 times.
Index can improve the performance in following operations:


Find the records matching with WHERE clause
UPDATE Books SET Availability = 1 WHERE SubjectId =12
DELETE FROM Books WHERE Price <10
SELECT * FROM Books WHERE Price BETWEEN 50 AND 80

Sorting the result with ORDER BY
SELECT * FROM Books ORDER BY Price DESC

Grouping records and aggregate values
SELECT Count(*) as Units, Price FROM Books GROUP BY Price

There are two types of indexes available in SQL Server: clustered and non-clustered
Clustered index
Clustered index physically reorders the records of a table. Therefore a table can have only one clustered index. Usually a clustered index will be created on the primary key of a table.
Non – Clustered Index
Non – Clustered index are stored in the order of the index key values, but the information in the table is stored in a different order. Means logical sorting of data not Physical. In SQl Server 2005 a table can have 249 non-clustered indexes.
Composite Indexes
A composite index is an index on two or more columns. Both clustered and non-clustered indexes can be composite indexes. If you have composite index on Price and BookName then take can take advantage of it like this:
SELECT BookName, Price FROM Products ORDER BY UnitPrice BookName, Price DESC


What is the difference between abstract class and interface?
We use abstract class and interface where two or more entities do same type of work but in different ways. Means the way of functioning is not clear while defining abstract class or interface. When functionality of each task is not clear then we define interface. If functionality of some task is clear to us but there exist some functions whose functionality differs object by object then we declare abstract class.
We can not make instance of Abstract Class as well as Interface. They only allow other classes to inherit from them. And abstract functions must be overridden by the implemented classes. Here are some differences in abstract class and interface.


An interface cannot provide code of any method or property, just the signature. we don’t need to put abstract and public keyword. All the methods and properties defined in Interface are by default public and abstract. An abstract class can provide complete code of methods but there must exist a method or property without body.

A class can implement several interfaces but can inherit only one abstract class. Means multiple inheritance is possible in .Net through Interfaces.

If we add a new method to an Interface then we have to define implementation for the new method in every implemented class. But If we add a new method to an abstract class then we can provide default implementation and therefore all the existing code might work properly.



What is the use of Master Pages in Asp.Net?
A master page in ASP.Net provides shared HTML, controls, and code that can be used as a template for all of the pages of a website.
Every master page has asp:contentplaceholder control that will be filled by the content of the pages that use this master page.
You can create a master page that has header and footer i.e. a logo, an image, left navigation bar etc and share this content on multiple pages. You need not to put these things on every aspx page.

.NET Interview Question & Answer

What is the difference between classes and structs in Microsoft.Net?
A struct is a value type, while a class is a reference type.
When we instantiate a class, memory will be allocated on the heap. When struct gets initiated, it gets memory on the stack.
Classes can have explicit parameter less constructors. But structs cannot have this.
Classes support inheritance. But there is no inheritance for structs. A struct cannot inherit from another struct or class, and it cannot be the base of a class. Like classes, structures can implement interfaces.
We can assign null variable to class. But we cannot assign null to a struct variable, since structs are value type.
We can declare a destructor in class but can not in struct.



What is a Strong Name in Microsoft.Net?
In Microsoft.Net a strong name consists of the assembly's identity. The strong name guarantees the integrity of the assembly. Strong Name includes the name of the .net assembly, version number, culture identity, and a public key token. It is generated from an assembly file using the corresponding private key.
Steps to create strong named assembly:

To create a strong named assembly you need to have a key pair (public key and a private key) file. Use sn -k KeyFile.snk
Open the dot net project to be complied as a strong named assembly. Open AssembyInfo.cs/ AssembyInfo.vb file. Add the following lines to AssemblyInfo file.
[Assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyDelaySign(false)]
[assembly: AssemblyKeyFile("..\\..\\KeyFile.snk")]
Compile the application, we have created a strong named assembly.




What is the use of XSLT?
XSLT stands for Extensible Stylesheet Language Transformations. This language used in XSL style sheets to transform XML documents into other XML documents.

XSLT is based on template rules which specify how XML documents should be processed. An XSLT processor reads both an XML document and an XSLT style sheet. Based on the instructions the processor finds in the XSLT style sheet, it produce a new XML document. With XSLT we can also produce HTML or XHTML from XML document. With XSLT we can add/remove elements and attributes, rearrange and sort elements, hide and display elements from the output file. Converting XML to HTML for display is probably the most common application of XSLT today.


Explain ACID properties of the database?

All Database systems which include transaction support implement ACID properties to ensure the integrity of the database. ACID stands for Atomicity, Consistency, Isolation and Durability


Atomicity: Each transaction is said to be “atomic.” If one part of the transaction fails, the entire transaction fails. Modifications on the data in the database either fail or succeed.
Consistency: This property ensures that only valid data will be written to the database. If, for some reason, a transaction is executed that violates the database’s consistency rules, the entire transaction will be rolled back and the database will be restored to a state consistent with those rules.
Isolation: It requires that multiple transactions occurring at the same time not impact each other’s execution.
Durability: It ensures that any transaction committed to the database will not be lost.



What is the basic functionality of Garbage Collector in Microsft.Net?

The Common Language Runtime (CLR) requires that you create objects in the managed heap, but you do not have to bother with cleaning up the memory once the object goes out of the scope or is no longer needed. The Microsoft .NET Framework Garbage Collector provides memory management capabilities for managed resources. The Garbage Collector frees objects that are not referenced and reclaims their memory. You should set your references to Nothing(null) as soon as you are done with them to ensure your objects are eligible for collection as soon as possible.
Here are the list of some tasks performed by the Garbage collector:


Garbage collector reserves a piece of memory as the application starts for the managed heap.
Garbage collector controls the managed heap memory currently used and available to an application.
Garbage collector allocates memory for new objects within the application.
The Garbage Collector attempts to reclaim the memory of objects that are not referenced.



What is a static class?
We can declare a static class. We use static class when there is no data or behavior in the class that depends on object identity. A static class can have only static members. We can not create instances of a static class using the new keyword. .NET Framework common language runtime (CLR) loads Static classes automatically when the program or namespace containing the class is loaded.

Here are some more features of static class



Static classes only contain static members.
Static classes can not be instantiated. They cannot contain Instance Constructors
Static classes are sealed.


What is static member of class?
A static member belongs to the class rather than to the instances of the class. In C# data fields, member functions, properties and events can be declared static. When any instances of the class are created, they cannot be used to access the static member.
To access a static class member, use the name of the class instead of an instance variable
Static methods and Static properties can only access static fields and static events.

Like: int i = Car.GetWheels;
Here Car is class name and GetWheels is static property.

Static members are often used to represent data or calculations that do not change in response to object state.



What is the purpose of Server.MapPath method in Asp.Net?
In Asp.Net Server.MapPath method maps the specified relative or virtual path to the corresponding physical path on the server. Server.MapPath takes a path as a parameter and returns the physical location on the hard drive. Syntax

Suppose your Text files are located at D:\project\MyProject\Files\TextFiles

If the root project directory is MyProject and the aspx file is located at root then to get the same path use code

//Physical path of TextFiles
string TextFilePath=Server.MapPath("Files/TextFiles");

.NET Interview Question & Answer

What is the difference between classes and structs in Microsoft.Net?
A struct is a value type, while a class is a reference type.
When we instantiate a class, memory will be allocated on the heap. When struct gets initiated, it gets memory on the stack.
Classes can have explicit parameter less constructors. But structs cannot have this.
Classes support inheritance. But there is no inheritance for structs. A struct cannot inherit from another struct or class, and it cannot be the base of a class. Like classes, structures can implement interfaces.
We can assign null variable to class. But we cannot assign null to a struct variable, since structs are value type.
We can declare a destructor in class but can not in struct.



What is a Strong Name in Microsoft.Net?
In Microsoft.Net a strong name consists of the assembly's identity. The strong name guarantees the integrity of the assembly. Strong Name includes the name of the .net assembly, version number, culture identity, and a public key token. It is generated from an assembly file using the corresponding private key.
Steps to create strong named assembly:

To create a strong named assembly you need to have a key pair (public key and a private key) file. Use sn -k KeyFile.snk
Open the dot net project to be complied as a strong named assembly. Open AssembyInfo.cs/ AssembyInfo.vb file. Add the following lines to AssemblyInfo file.
[Assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyDelaySign(false)]
[assembly: AssemblyKeyFile("..\\..\\KeyFile.snk")]
Compile the application, we have created a strong named assembly.




What is the use of XSLT?
XSLT stands for Extensible Stylesheet Language Transformations. This language used in XSL style sheets to transform XML documents into other XML documents.

XSLT is based on template rules which specify how XML documents should be processed. An XSLT processor reads both an XML document and an XSLT style sheet. Based on the instructions the processor finds in the XSLT style sheet, it produce a new XML document. With XSLT we can also produce HTML or XHTML from XML document. With XSLT we can add/remove elements and attributes, rearrange and sort elements, hide and display elements from the output file. Converting XML to HTML for display is probably the most common application of XSLT today.


Explain ACID properties of the database?

All Database systems which include transaction support implement ACID properties to ensure the integrity of the database. ACID stands for Atomicity, Consistency, Isolation and Durability


Atomicity: Each transaction is said to be “atomic.” If one part of the transaction fails, the entire transaction fails. Modifications on the data in the database either fail or succeed.
Consistency: This property ensures that only valid data will be written to the database. If, for some reason, a transaction is executed that violates the database’s consistency rules, the entire transaction will be rolled back and the database will be restored to a state consistent with those rules.
Isolation: It requires that multiple transactions occurring at the same time not impact each other’s execution.
Durability: It ensures that any transaction committed to the database will not be lost.



What is the basic functionality of Garbage Collector in Microsft.Net?

The Common Language Runtime (CLR) requires that you create objects in the managed heap, but you do not have to bother with cleaning up the memory once the object goes out of the scope or is no longer needed. The Microsoft .NET Framework Garbage Collector provides memory management capabilities for managed resources. The Garbage Collector frees objects that are not referenced and reclaims their memory. You should set your references to Nothing(null) as soon as you are done with them to ensure your objects are eligible for collection as soon as possible.
Here are the list of some tasks performed by the Garbage collector:


Garbage collector reserves a piece of memory as the application starts for the managed heap.
Garbage collector controls the managed heap memory currently used and available to an application.
Garbage collector allocates memory for new objects within the application.
The Garbage Collector attempts to reclaim the memory of objects that are not referenced.



What is a static class?
We can declare a static class. We use static class when there is no data or behavior in the class that depends on object identity. A static class can have only static members. We can not create instances of a static class using the new keyword. .NET Framework common language runtime (CLR) loads Static classes automatically when the program or namespace containing the class is loaded.

Here are some more features of static class



Static classes only contain static members.
Static classes can not be instantiated. They cannot contain Instance Constructors
Static classes are sealed.


What is static member of class?
A static member belongs to the class rather than to the instances of the class. In C# data fields, member functions, properties and events can be declared static. When any instances of the class are created, they cannot be used to access the static member.
To access a static class member, use the name of the class instead of an instance variable
Static methods and Static properties can only access static fields and static events.

Like: int i = Car.GetWheels;
Here Car is class name and GetWheels is static property.

Static members are often used to represent data or calculations that do not change in response to object state.



What is the purpose of Server.MapPath method in Asp.Net?
In Asp.Net Server.MapPath method maps the specified relative or virtual path to the corresponding physical path on the server. Server.MapPath takes a path as a parameter and returns the physical location on the hard drive. Syntax

Suppose your Text files are located at D:\project\MyProject\Files\TextFiles

If the root project directory is MyProject and the aspx file is located at root then to get the same path use code

//Physical path of TextFiles
string TextFilePath=Server.MapPath("Files/TextFiles");

.Net Interview Questions & Answers

Multiple - Language Development in .NET Framework

.NET Framework encourages cross-language development using multiple programming languages. To become a .NET language, any language should have a compiler that translates the source code written in different languages into Microsoft Intermediate Language (MSIL).

MSIL code is called as Managed Code. Managed code runs in .NET environment.

In .Net framework the Common Runtime Language (CLR) contains a couple of just-in-time compilers (JIT) which can understand IL Code (managed Code), and can convert IL to native code (binary code targeted at a specific machine processor).

Hence any language with IL Code generating compiler can become a .Net language



Explain the delegates in C#.

Delegates in C# are objects which points towards a function which matches its signature. Delegates are reference type used to encapsulate a method with a specific signature. Delegates are similar to function pointers in C++; however, delegates are type-safe and secure.
Here are some features of delegates:

A delegate represents a class.
A delegate is type-safe.
We can use delegates both for static and instance methods
We can combine multiple delegates into a single delegate.
Delegates are often used in event-based programming, such as publish/subscribe.
We can use delegates in asynchronous-style programming.
We can define delegates inside or outside of classes.
Syntax of using delegates

//Declaring delegate
delegate void SampleDelegate(string message);

// declare method with same signature:
static void SampleDelegateMethod(string message) { Console.WriteLine(message); }

// create delegate object
SampleDelegate d1 = SampleDelegateMethod;

// Invoke method with delegate
d1("my program");



What is the purpose of connection pooling in ADO.NET?

Connection pooling enables an application to use a connection from a pool of connections that do not need to be re-established for each use. Once a connection has been created and placed in a connection pool, an application can reuse that connection without performing the complete connection creation process.

By default, the connection pool is created when the first connection with a unique connection string connects to the database. The pool is populated with connections up to the minimum pool size. Additional connections can be added until the pool reaches the maximum pool size.

When a user request a connection, it is returned from the pool rather than establishing new connection and, when a user releases a connection, it is returned to the pool rather than being released. But be sure than your connections use the same connection string each time. Here is the Syntax

conn.ConnectionString = "integrated Security=SSPI; SERVER=192.168.0.123; DATABASE=MY_DB; Min Pool Size=4;Max Pool Size=40;Connect Timeout=14;";

.NET Remoting Versus Web Services

The Web services technology enables cross-platform integration by using HTTP, XML and SOAP for communication thereby enabling true business-to-business application integrations across firewalls. Because Web services rely on industry standards to expose application functionality on the Internet, they are independent of programming language, platform and device.

Remoting is .a technology that allows programs and software components to interact across application domains, processes, and machine boundaries. This enables your applications to take advantage of remote resources in a networked environment.

Both Web services and remoting support developing distributed applications and application integration, but you need to consider how they differ before choosing one implementation over the other. In this article, I will show the differences between these two technologies. I will present samples for each type of implementation and identify when to use which technology.



.NET Remoting

NET Remoting uses a flexible and extremely extensible architecture. Remoting uses the .NET concept of an Application Domain (AppDomain) to determine its activity. An AppDomain is an abstract construct for ensuring isolation of data and code, but not having to rely on operating system specific concepts such as processes or threads. A process can contain multiple AppDomains but one AppDomain can only exist in exactly one process. If a call from program logic crosses an AppDomain boundary then .NET Remoting will come into place. An object is considered local if it resides in the same AppDomain as the caller. If the object is not in the same appdomain as the caller, then it is considered remote.

In .NET remoting, the remote object is implemented in a class that derives from System.MarshalByRefObject. The MarshalByRefObject class provides the core foundation for enabling remote access of objects across application domains. A remote object is confined to the application domain where it is created. In .NET remoting, a client doesn't call the methods directly; instead a proxy object is used to invoke methods on the remote object. Every public method that we define in the remote object class is available to be called from clients.




When a client calls the remote method, the proxy receives the call, encodes the message using an appropriate formatter, then sends the call over the channel to the server process. A listening channel on the server appdomain picks up the request and forwards it to the server remoting system, which locates and invokes the methods on the requested object. Once the execution is completed, the process is reversed and the results are returned back to the client.

Out of the box, the remoting framework comes with two formatters: the binary and SOAP formatters. The binary formatter is extremely fast, and encodes method calls in a proprietary, binary format. The SOAP formatter is slower, but it allows developers to encode the remote messages in a SOAP format. If neither formatter fits your needs, developers are free to write their own and plug it in as a replacement.

Different Types of Remote Objects
The remoting infrastructure allows you to create two distinct types of remote objects.

Client-activated objects - A client-activated object is a server-side object whose creation and destruction is controlled by the client application. An instance of the remote object is created when the client calls the new operator on the server object. This instance lives as long as the client needs it, and lives across one to many method calls. The object will be subject to garbage collection once it's determined that no other clients need it.


Server-activated objects - A server-activated object's lifetime is managed by the remote server, not the client that instantiates the object. This differs from the client-activated object, where the client governs when the object will be marked for finalization. It is important to understand that the server-activated objects are not created when a client calls New or Activator.GetObject. They are rather created when the client actually invokes a method on the proxy. There are two types of server activated objects. They are:

Single call . Single-call objects handle one, and only one, request coming from a client. When the client calls a method on a single call object, the object constructs itself, performs whatever action the method calls for, and the object is then subject to garbage collection. No state is held between calls, and each call (no matter what client it came from) is called on a new object instance.


Singleton - The difference in a singleton and single call lies in lifetime management. While single-call objects are stateless in nature, singletons are stateful objects, meaning that they can be used to retain state across multiple method calls. A singleton object instance serves multiple clients, allowing those clients to share data among themselves.


ASP.NET Web Services
With the arrival of .NET, creating an ASP.NET Web service is a breezy experience with the .NET framework taking away all the complexities in creating and consuming Web services. To create a Web service, all you need to do is create a Web service class that derives from the System.Web.Services.WebService class and decorate the methods (that you want to expose as Web services) with the WebMethod attribute. Once this is done, these methods can be invoked by sending HTTP requests using SOAP.

Consuming a Web service is very straightforward too. You can very easily create a proxy class for your Web service using either wsdl.exe utility or the Add Web Reference option in VS.NET. The Web service proxy hides all the network and marshaling plumbing from the application code, so using the Web service looks just like using any other local object.



As you can see from the above diagram, the client proxy receives the request from the client, serializes the request into a SOAP request which is then forwarded to the remote Web service. The remote Web service receives the SOAP request, executes the method, and sends the results in the form of a SOAP response to the client proxy, which deserializes the message and forwards the actual results to the client.

ASP.NET Web Services Vs .NET Remoting

Now that we have understood the basic concepts of .NET remoting and Web services, let us identify the differences between these two technologies. For this, I present different factors such as performance, state management, etc and then identify which technology to use in what situations.

Performance
In terms of performance, the .NET remoting plumbing provides the fastest communication when you use the TCP channel and the binary formatter. In the case of Web services, the primary issue is performance. The verbosity of XML can cause SOAP serialization to be many times slower than a binary formatter. Additionally, string manipulation is very slow when compared to processing the individual bits of a binary stream. All data transported across the wire is formatted into a SOAP packet. However if your Web service performs computation intensive operations, you might want to consider using caching to increase the performance of your Web service on the server side. This will increase the scalability of the Web service, which in turn can contribute to the increase in performance of the Web service consumers. A remoting component, using the TCP channel and the binary formatter, provides the greatest performance of any remoting scenario, primarily because the binary formatter is able to serialize and deserialize data much faster.

If you use .NET remoting with a SOAP formatter, you will find that the performance provided by ASP.NET Web services is better than the performance provided by NET remoting endpoints that used the SOAP formatter with either the HTTP or the TCP channel. However the .NET remoting provides clear performance advantages over ASP.NET Web services only when you use TCP channels with binary communication.

State Management
Web services are a stateless programming model, which means each incoming request is handled independently. In addition, each time a client invokes an ASP.NET Web service, a new object is created to service the request. The object is destroyed after the method call completes. To maintain state between requests, you can either use the same techniques used by ASP.NET pages, i.e., the Session and Application objects, or you can implement your own custom solution. However it is important to remember that maintaining state can be costly with Web services as they use extensive memory resources.

.NET remoting supports a range of state management options that you can choose from. As mentioned before, SingleCall objects are stateless, Singleton objects can share state for all clients, and client-activated objects maintain state on a per-client basis. Having three types of remote objects (as opposed to one with Web services) during the design phase helps us create more efficient, scalable applications. If you don't need to maintain state, use single-call objects; if you need to maintain state in a small section of code, use single call and singletons together. The ability to mix and match the various object types facilitates creation of solid architectural designs.

Security
.NET remoting plumbing does not provide out of the box support for securing cross-process invocations. However a .NET remoting object hosted in IIS, can leverage all the same security features provided by IIS. If you are using the TCP channel or the HTTP channel hosted in a container other than IIS, you have to implement authentication, authorization and privacy mechanisms yourself.

Since ASP.NET Web services are hosted, by default, in IIS, they benefit from all the security features of IIS such as support for secure communication over the wire using SSL, authentication and authorization services.

Reliability
.NET remoting gives you the flexibility to host remote objects in any type of application including a Windows Form, a managed Windows Service, a console application or the ASP.NET worker process. If you host your remote objects in a windows service, or a console application, you need to make sure that you provide features such as fault tolerance within your hosting application so that the reliability of the remote object is not compromised. However if you do host remote objects in IIS, then you can take advantage of the fact that the ASP.NET worker process is both auto-starting and thread-safe. In the case of ASP.NET Web services, reliability is not a consideration as they are always hosted in IIS, making it easy for them to take advantage of the capabilities provided by IIS.

Extensibility
Both the ASP.NET Web services and the .NET remoting infrastructures are extensible. You can filter inbound and outbound messages, control aspects of type marshaling and metadata generation. .NET remoting takes extensibility to the next level allowing you to implement your own formatters and channels.

Since ASP.NET Web services rely on the System.Xml.Serialization.XmlSerializer class to marshal data to and from SOAP messages at runtime, we can very easily customize the marshaling by adding a set of custom attributes that can be used to control the serialization process. As a result, you have very fine-grained control over the shape of the XML being generated when an object is serialized.


Ease of programming and deployment
In this section, we will consider a simple remoting object and an ASP.NET Web service to understand the complexities involved in creating and consuming them. We will start off by creating a simple remote object.

Creating a remote object
Creating a remoting object is a simple process. To create a remote object, you need to inherit from MarshalByRefObject class. The following code shows a remotable class.

using System;
namespace RemoteClassLib
{
public class MyRemoteObject : System.MarshalByRefObject
{
public MyRemoteObject()
{
Console.WriteLine("Constructor called");
}

public string Hello(string name)
{
Console.WriteLine("Hello Called");
return "Hello " + name;
}
}
}

The above code is very simple and straightforward. We start off by defining a class that inherits from MarshalByRefObject. After that we add code to the constructor of the class to write out a message to the console. Then we have a method named Hello that basically takes a string argument and appends that with the string and returns the concatenated value back to the caller. Once the remote object is created, the next step is to create a host application that hosts the remote object. For the purposes of this article, we will create a console application that reads the details of the remote object from its configuration file.

using System;
using System.Runtime.Remoting;

namespace RemoteClassLibServer
{
class RemoteServer
{
[STAThread]
static void Main(string[] args)
{
RemotingConfiguration.Configure(
"RemoteClassLibServer.exe.config");
Console.WriteLine("Press return to Exit");
Console.ReadLine();
}
}
}

In the main method, we just read the configuration settings from the configuration file using the RemotingConfiguration.Configure method and wait for the client applications to connect to it.

The configuration file used by the above hosting application looks like the following. In the configuration file, we specify that we want to expose the remote object using the TCP channel by using the channel element.






type="RemoteClassLib.MyRemoteObject,RemoteClassLib"
objectUri="MyRemoteObject">









Once the hosting application is started, then client applications can start creating instances of the remote object and invoke its methods. In the next section, we will understand the processes involved in creating an ASP.NET Web service.

Creating an ASP.NET Web Service
As mentioned before, creating an ASP.NET Web service is pretty easy in VS.NET. Select the ASP.NET Web Service template using Visual Studio.NET New Project dialog box. Enter the name of the project and click OK to create the project. Once the project is created, modify the default service1.asmx file to look like the following.

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Web;
using System.Web.Services;

namespace XmlWebServicesExample
{

public class Service1 : System.Web.Services.WebService
{
public Service1()
{
}

[WebMethod (EnableSession=true)]
public string HelloWorld()
{
return "Hello World";
}
}
}

As you can see from the above, the Web service class named Service1 is derived from System.Web.Services.WebService. Inheriting from the WebService class is optional and it is used to gain access to common ASP.NET objects like Application, Session, User, and Context. Then we also add a method named HelloWorld that basically returns a simple string back to the callers of the Web service. In the WebMethod attribute of the HelloWorld method, we also specify that we want to enable session state for our ASP.NET Web service by setting the EnableSession attribute to true.

Creating the consumer for the ASP.NET Web Service
You can consume the Web service by using the Add Web Reference option in VS.NET to create a proxy for the Web service. When you create a Web reference, the VS.NET IDE creates a proxy for you based on the WSDL file published by the Web service. Once the proxy is generated, you can treat the proxy class methods as if they are the actual Web service methods. At runtime, when the proxy class methods are invoked, they will connect to the actual Web service, invoke the Web service method, retrieve the results returned by the Web service and hand it back to the consumers. The following screenshot shows how to use the Add Web Reference option to create a proxy for the Web service.



So far, we have seen the steps involved in creating a .NET remoting object and an ASP.NET Web service. As can be seen from the above code, ASP.NET Web services are very easy-to-create. Consuming ASP.NET Web service is also a very simple process due to the excellent Web service support provided by Visual Studio.NET. With .NET remoting, you need to create the remote object first and then write a hosting application (assuming that you are not using IIS) to expose that remote object. You also need to make sure that the information about the remote object is retrieved from the configuration file to allow for extensibility in the future. If you all these factors into consideration, you will agree that .NET remoting objects are complex to develop and deploy.

Type Fidelity
ASP.NET Web services favor the XML schema type system, and provide a simple programming model with broad cross-platform reach. .NET remoting favors the runtime type system, and provides a more complex programming model with much more limited reach. This essential difference is the primary factor in determining which technology to use.

Java-Tutorial : Classes, Methods and Objects

tent="Microsoft Word 9">

Classes and Objects








Classes and Objects



The idea of Object-Oriented Programming (OOP) is to place data and methods
together in a single entity. The single entity holding the data and methods is
called a class. An Object is an instance of a class.

To create a Java application, you organize programming structures by creating
classes that consist of reusable code. You can create a class in Java to
perform simple tasks, such as declaring the member variables of the class and
perhaps initializing the member variables by using the methods of the class.



An instance of a class is declared the same way that a primitive data type
is declared. A class defines both data and methods. You can reuse the same
class in several applications without rewriting it. You can create as many
instances or objects of a class as needed. When multiple objects are created,
each object maintains a separate copy of the member variables defined by the
class.



Creating a Classlang=EN style='font-family:"Bookman Old Style";mso-ansi-language:EN'> lang=EN style='mso-ansi-language:EN'>



lang=EN style='mso-ansi-language:EN'>1.     
Specify the
class name.



lang=EN style='mso-ansi-language:EN'>2.     
Declare data
members.



lang=EN style='mso-ansi-language:EN'>3.     
Declare
methods.



4.     
Define the
processing.



In order to define a class, you must specify the class name, declare the
member variables, and declare the methods of the class.

There are certain naming conventions that should be followed when naming a
class. First, class names should be nouns. The first character of the class
name should be upper case, and each internal word of the name should be upper
case. The rest of the characters in the name should be lower case. The words in
the name should be whole words. Acronyms and abbreviates should be avoided.



In addition, you must define the processing that is required for the
method. For example, operations such as addition or subtraction on member
variables can be specified in the methods. The contents of the class definition
are enclosed within braces.







public class Rectangle {
 //class name and Body begins now… 
  int length=10; 
  int width=5; 
  String color; 
  void calculateArea() { //method declartion 
    int totArea = length * width;//processing 
    System.out.println(”The total area ” + totArea); 
  } 
}//end class body


Consider the Rectangle class shown above. It consists of the class keyword
followed by the class name. The class body begins with an opening brace. The class
body consists of member variables and a method. In the method declaration, the
member variables are accessed and processed. To end the class declaration you
use a closing brace.



A class declared in Java usually contains an access modifier. The access
modifier determines the type of access other classes and objects can have to a
specific class and the fields and methods that it defines. In our example,
Rectangle class is declared using “public” access modifier meaning it can be
accessed by anyone.



Access Modifiers for Class

The access modifiers that can be used while declaring a class are public,
private, and protected
. When the class is declared without an
access modifier, the class is accessible by the other classes in the current
package. When a class is declared with the public access modifier, the class is
accessible by all the other classes.

The private and protected access modifiers may only be used on inner classes.
They cannot be used for top-level classes. When a class is declared with the
private access modifier, the class is not accessible by any other classes. When
a class is declared with the protected access modifier, the class is accessible
by subclasses of the class.



In addition to the access modifiers, the modifiers final, abstract,
and strictfp
may be specified.



If the final modifier is specified, the class represents a
complete class and cannot be overridden by a subclass.



The abstract modifier is used to declare that a class is
considered incomplete. An abstract class may have abstract methods that are not
implemented within the class. The final modifier cannot be used with the
abstract modifier.



The strictfp modifier is used to force the code within the
entire class to use strict floating-point logic. This applies to all float and
double values that are used within the class.



style='mso-ansi-language:EN'> 



Declaring Methods



A class is defined by its state and behavior. The member variables of the
class define the state of the class. The methods of a class define the behavior
of the class.

Consider an example, To add the values stored in the member variables of a
class, you declare a method that operates on these member variables to compute
their sum. The result can be displayed by another method that calls the
computed method.



The six basic components of a method include the access modifier, other
modifiers, the return type of the method, the name of the method, a list of the
arguments passed to the method, and the body of the method.







<access modifiers> <other method modifiers>
<return type> methodName(arg1, arg2, ...)
 { //method body   style='font-family:monospace'>}


Access Modifier for Methods

It is a Subset of the method modifier group. This specifies the type of access
granted to other objects for that method. You can declare a method public,
private, or protected. If no access modifier is specified, the method is
accessible to all classes in the current package. A public method may be
accessed from any class. A protected method may be accessed from any subclass
of the class in which the method is defined. A private method may only be
accessed from within the class in which it is declared.







void myPackageMethod() { 
// This method may be accessed from any 
// class declared in the same package 
}
public void myPublicMethod() { 
  //This method may be accessed fro  style='font-family:monospace;color:#003300'>m any class 
}
private void myPrivateMethod() {
   // This method cannot be 
   // accessed from other classes.
}
protected void myProtectedMethod() { 
  // This method may be accessed from any 
  // subclass of the class that declares it. 
} 
public final void myFinalMethod() { 
  // This method cannot be overridden or hidden 
} 
public abstract void myAbstractMethod();
//This method must be overridden 
 // to create a concrete class
public static void myStaticMethod() {
  //Do Work 
} 
public native void someExternalMethod(String name); 
public strictfp void myStrictFpMethod() {
  // All float and doubles 
  // use strict floating point logic. 
} 
public syncrhornized void mySynchronizedMethod() { 
  //Multiple threads will not be able to 
  //access this   style='font-family:monospace;color:#003300'>method at the same time. 
  style='font-family:monospace'>}


Other Method modifiers

In addition to the access modifiers, the modifiers static, final, abstract,
native, strictfp, and synchronized may be specified.



Static methods are scoped to the class and not to the instance of the object.
These methods may be called without an instance of the class being created.
These methods may be called without an instance of the class being created.
They may access static variables, but do not have direct access to member
variables.



If the final modifier is specified, the method cannot be overridden or
hidden by a subclass. The abstract modifier is used to declare that a method is
not implemented in a class. In this case, the method must be implemented by a
subclass in order to create a class that can be instantiated. This final
modifier cannot be used with the abstract modifier.



The native modifier is used to define a class that is implemented in code
external to the Java Code. This is typically used to allow a Java application
to call code in languages such as C++.



The strictfp modifier is used to force the code within the method to use
strict floating-point logic. This applies to all float and double values that
are used within the method.



The synchronized modifier is used when access to the method needs to be
synchronized in order to prevent multiple threads from accessing it at the same
time. This can be used to keep multiple threads from modifying variables or
accessing resources at the same time.



Return Type

The return type of the method indicates the return type of the method. The
return type of the method indicates the type of value that the method provides
to a calling method. The return type is specified by a primitive or object data
type, such as void, int, char, String, or Date. The return type is always
followed by the method name.



Method Name

A method name that follows the int data type would signify that the method
returns a type integer when its is involved. Note if the method does not return
any type, the method name is preceded by the void return type.



The method name is user-defined and should be meaningful. According to Java
variable naming conventions, if a name consists of two or more words, you join
the words to form a single word and capitalize the first letter of each word,
except for the first word.



The name of the method must not be a Java Keyword, such as int, package, or
void. In addition, the method name should not begin with a digit and must not
contain embedded spaces or periods. For example, findFile is a valid method
name.



If a method defines a return type, then the return keyword is used to
return the value. The keyword is followed by the value that is to be returned
by the method. Note that this keyword is not required if the method does not
return a value because its return type is void.



Method Arguments

This is a comma separated list of variable declarations that are defined within
enclosing parentheses. Arguments are optional. The parentheses are mandatory.



Method Body

The body contains statements and expressions that run when the method is
invoked. The body of the method can have conditions and loops, and it can send
messages to other instances or to other objects.



Method Overloading



Programming languages like C require unique names for different methods in
the same program. In Java, you can declare methods with the same name. This
process is called method overloading.

In C, a program contains many methods that perform different tasks. Therefore,
it is difficult for an application developer to remember the function and name
of each method.



In Java, you can declare methods with the same name. However, these methods
must accept different arguments. This process of declaring methods with the
same name is called method overloading.



In Java, every method has a signature, which consists of a method name and
an argument list. The data type of the arguments and their sequence helps
define the signature of a method.



A Class cannot have two methods with the same signature. This is because
compiler will not be able to determine which method to invoke.



In addition to overloading a method with a different number of arguments,
you can overload a method by specifying different data types for the arguments.
You can also overload a method by providing a different sequence for arguments.







void addNum(int num, float num1)
  style='font-family:monospace'>void addNum(float num, int num1)


Consider an example in which you declare a method that adds an integer
value and a float value. In such situation, a user can pass an integer value
first and then the float value or vice-versa. To conform to this requirement,
you declare two methods with a different sequence of arguments but with the
same name.



Pass By Value: Primitives



When you invoke a method, you may pass arguments to the method. The arguments
are used by the method. Either the value of the argument or a reference to an
object is passed.

When you invoke a method by passing arguments by value, it is know as passing
by value. When you invoke a method by passing a value to a method, it is known as
passing arguments by value. Java passes all method arguments by value for
primitive data types. By passing the arguments by value, the original value of
arguments is not altered inside the method. The method only receives a copy of
the variable.







void computePrice(int unitPrice, int numberOfUnits) {
  unitPrice = unitPrice * numberOfUnits; 
  System.out.println(
    “unitPrice in the computePrice method : ” 
    + unitPrice); 
  style='font-family:monospace'>}


For example, to calculate the total price for four identical items, you multiply
the unit price of the item by four. This will not change the price of the
individual item. This is because the price was passed by value.

When you invoke a method by passing a value, a local copy of each argument is
made in the called method. Consider the code of the item class shown in the
above example. This class contains the computePrice method. This method has a
piece of code that changes the value of the unitPrice parameter. The
computePrice method calculates the price of the number of items and stores the
total in the unitPrice variable. The method also displays the total value.



style='mso-ansi-language:EN'>In Summary:style='mso-ansi-language:EN'> Calling a method and passing the arguments by
value does not affect the original value.



Pass By Reference: Objects



Whenever arguments of type Object are passed to a method, their references
are passed as opposed to a copy of the object. An object is passed by reference
when it is an argument of a method. This ensures that the changes to the object
are retained because the actual object is being updated.







class Employee { String name; 
 String department; 
 double salary;
  public Employee(String empName, 
                  String empDept, 
                  double empSalary) {
    this.name = empName;
    this.department = empDept;
    this.salary = empSalary;
   }
   void printAll() {
     System.out.println(”Name : ” + name);
     System.out.println(”Department : ” + department); 
     System.out.println(”Salary : ” + salary); 
   } 
   public sta  style='font-family:monospace;color:#003300'>tic void main(String args[]) { 
     Employee jane = new 
                  Employee(”Jane”, “Research”, 60000); 
     Employee tempEmp = jane;
     tempEmp.name = “Tom”;  
     jane.printAll();  
   } 
  style='font-family:monospace'>}


Consider a situation where each employee is assigned three details. These details
are name, department, and salary. In addition, an employee can print all the
details through the printAll method. The sample code in the example
instantiates a new Employee object, bound to the variable jane. The code then
assigns Jane to the name, Research to the department, and 60000 to the salary.
Next, a variable of type Employee called tempEmp is declared and assigned to
the same instance that the variable jane is bound to. Both jane and tempEmp are
references pointing to the same object. A change to one will be reflected in
the other.





 











Assembly In Microsoft.Net

What is an assembly in .NET Framework?
An assembly is the primary building block of a .NET Framework application. It is a collection of functionality that is built, versioned, and deployed as a single implementation unit (as one or more files). All managed types and resources are marked either as accessible only within their implementation unit, or as accessible by code outside that unit.
Assemblies are self-describing by means of their manifest, which is an integral part of every assembly. The manifest:

What is assembly manifest?
Every assembly, whether static or dynamic, contains a collection of data that describes how the elements in the assembly relate to each other. The assembly manifest contains this assembly metadata. An assembly manifest contains all the metadata needed to specify the assembly's version requirements and security identity, and all metadata needed to define the scope of the assembly and resolve references to resources and classes. The assembly manifest can be stored in either a PE file (an .exe or .dll) with Microsoft intermediate language (MSIL) code or in a standalone PE file that contains only assembly manifest information.
For an assembly with one associated file, the manifest is incorporated into the PE file to form a single-file assembly. You can create a multi-file assembly with a standalone manifest file or with the manifest incorporated into one of the PE files in the assembly.
Explain the information stored in assembly manifest.
Assembly manifest contains the following information:

Assembly name -A text string specifying the assembly's name.

Version number- A major and minor version number, and a revision and build number. The common language runtime uses these numbers to enforce version policy.

Culture- Information on the culture or language the assembly supports. This information should be used only to designate an assembly as a satellite assembly containing culture- or language-specific information. (An assembly with culture information is automatically assumed to be a satellite assembly.)

Strong name information- The public key from the publisher if the assembly has been given a strong name.
List of all files in the assembly- A hash of each file contained in the assembly and a file name. Note that all files that make up the assembly must be in the same directory as the file containing the assembly manifest.

Type reference information -Information used by the runtime to map a type reference to the file that contains its declaration and implementation. This is used for types that are exported from the assembly.

Information on referenced assemblies -A list of other assemblies that are statically referenced by the assembly. Each reference includes the dependent assembly's name, assembly metadata (version, culture, operating system, and so on), and public key, if the assembly is strong named.

You can add or change some information in the assembly manifest by using assembly attributes in your code. You can change version information and informational attributes, including Trademark, Copyright, Product, Company, and Informational Version. Every assembly, whether static or dynamic, contains a collection of data that describes how the elements in the assembly relate to each other. The assembly manifest contains this assembly metadata. An assembly manifest contains all the metadata needed to specify the assembly's version requirements and security identity, and all metadata needed to define the scope of the assembly and resolve references to resources and classes. The assembly manifest can be stored in either a PE file (an .exe or .dll) with Microsoft intermediate language (MSIL) code or in a standalone PE file that contains only assembly manifest information. For an assembly with one associated file, the manifest is incorporated into the PE file to form a single-file assembly. You can create a multi-file assembly with a standalone manifest file or with the manifest incorporated into one of the PE files in the assembly.

What are the functions performed by the assembly manifest?
Each assembly's manifest performs the following functions:

* Enumerates the files that make up the assembly.
* Governs how references to the assembly's types and resources map to the files that contain their declarations and implementations.
# Enumerates other assemblies on which the assembly depends.
# Provides a level of indirection between consumers of the assembly and the assembly's implementation details.
# Renders the assembly self-describing.

What is GAC (Global Assembly Cache)?
Each computer where the common language runtime is installed has a machine-wide code cache called the global assembly cache that stores assemblies specifically designated to be shared by several applications on the computer.
You should share assemblies by installing them into the global assembly cache only when you need to. As a general guideline, keep assembly dependencies private, and locate assemblies in the application directory unless sharing an assembly is explicitly required. In addition, it is not necessary to install assemblies into the global assembly cache to make them accessible to COM interop or unmanaged code.

Assemblies deployed in the global assembly cache must have a strong name. When an assembly is added to the global assembly cache, integrity checks are performed on all files that make up the assembly.

DOTNET Remoting interview Questions

What’s a Windows process?
It’s an application that’s running and had been allocated memory.

What’s typical about a Windows process in regards to memory allocation?
Each process is allocated its own block of available RAM space, no process can access another process’ code or data. If the process crashes, it dies alone without taking the entire OS or a bunch of other applications down.

Explain what relationship is between a Process, Application Domain, and Application?
A process is an instance of a running application. An application is an executable on the hard drive or network. There can be numerous processes launched of the same application (5 copies of Word running), but 1 process can run just 1 application.

What are possible implementations of distributed applications in .NET?
.NET Remoting and ASP.NET Web Services. If we talk about the Framework Class Library, noteworthy classes are in System.Runtime.Remoting and System.Web.Services.

What are the consideration in deciding to use .NET Remoting or ASP.NET Web Services?
Remoting is a more efficient communication exchange when you can control both ends of the application involved in the communication process. Web Services provide an open-protocol-based exchange of informaion. Web Services are best when you need to communicate with an external organization or another (non-.NET) technology.

What’s a proxy of the server object in .NET Remoting?
It’s a fake copy of the server object that resides on the client side and behaves as if it was the server. It handles the communication between real server object and the client object. This process is also known as marshaling.

What are remotable objects in .NET Remoting?
Remotable objects are the objects that can be marshaled across the application domains. You can marshal by value, where a deep copy of the object is created and then passed to the receiver. You can also marshal by reference, where just a reference to an existing object is passed.

What are channels in .NET Remoting?
Channels represent the objects that transfer the other serialized objects from one application domain to another and from one computer to another, as well as one process to another on the same box. A channel must exist before an object can be transferred.

What security measures exist for .NET Remoting in System.Runtime.Remoting?
None. Security should be taken care of at the application level. Cryptography and other security techniques can be applied at application or server level.

What is a formatter?
A formatter is an object that is responsible for encoding and serializing data into messages on one end, and deserializing and decoding messages into data on the other end.

Choosing between HTTP and TCP for protocols and Binary and SOAP for formatters, what are the trade-offs?
Binary over TCP is the most effiecient, SOAP over HTTP is the most interoperable.

What’s SingleCall activation mode used for?
If the server object is instantiated for responding to just one single request, the request should be made in SingleCall mode.

What’s Singleton activation mode?
A single object is instantiated regardless of the number of clients accessing it. Lifetime of this object is determined by lifetime lease.

How do you define the lease of the object?
By implementing ILease interface when writing the class code.

Can you configure a .NET Remoting object via XML file?
Yes, via machine.config and application level .config file (or web.config in ASP.NET). Application-level XML settings take precedence over machine.config.

How can you automatically generate interface for the remotable object in .NET with Microsoft tools?
Use the Soapsuds tool.