May 10, 2010

Writing Excel file with data set

here is the way by which we can create a excel file. here i hvae use a data set in which all the values are present which i want to write in the excel sheet.

first of all the column head is stored in an array and the value is present in the data set.  You just need to add the COM reference in the application using the Microsoft 12.0 Excel object library.
Use the name space to create the excel object.
                                           

string[] sExcelRow ={ "A", "B", "C", "D", "E", "F", "G", "H", "I",}
 Microsoft.Office.Interop.Excel.Sheets sheets;                 

                  Microsoft.Office.Interop.Excel.Workbooks workbooks = exc.Workbooks;

                  Microsoft.Office.Interop.Excel._Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);

                  sheets = workbook.Worksheets;

                  Microsoft.Office.Interop.Excel._Worksheet worksheet;
                  worksheet = (Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(1);


   for (int i = 0; i <>
                  {
                      worksheet.get_Range(sExcelRow[i] + 1,  sExcelRow[i] + 1).Value2 = sExcelCol[i].ToString();
                      worksheet.get_Range(sExcelRow[i] + 1, sExcelRow[i] + 1).Font.Bold = true;
                      worksheet.get_Range(sExcelRow[i] + 1, sExcelRow[i] + 1).HorizontalAlignment = Microsoft.Office.Interop.Excel.Constants.xlCenter;
                      worksheet.get_Range(sExcelRow[i] + 1, sExcelRow[i] + 1).EntireColumn.AutoFit();



  for (int j = 0; j <>
                  {
                      string strFieldStatus = string.Empty;
                      for (int l = 0; l <>
                      {
                      
                              worksheet.get_Range(sExcelRow[l] + x, sExcelRow[l] + x).Value2 = System.IO.Path.GetFileName(Convert.ToString(ldsUser1.Tables[0].Rows[j][l + 1]));
                              worksheet.get_Range(sExcelRow[l] + x, sExcelRow[l] + x).EntireColumn.AutoFit();
                              worksheet.get_Range(sExcelRow[l] + x, sExcelRow[l] + x).EntireColumn.NumberFormat = "@";

                        }


workbook.SaveAs(strFile1, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, false, false, Type.Missing, Type.Missing, Type.Missing);
 workbook.Close(true, Type.Missing, Type.Missing);

Apr 7, 2010

webservices in asp.net

Introduction

Microsoft .NET marketing has created a huge hype about its Web Services. This is the first of two articles on Web Services. Here we will create a .NET Web Service using C#. We will look closely at the Discovery protocol, UDDI, and the future of the Web Services. In the next article, we will concentrate on consuming existing Web Services on multiple platforms (i.e., Web, WAP-enabled mobile phones, and windows applications).

Why do we need Web Services?


After buying something over the Internet, you may have wondered about the delivery status. Calling the delivery company consumes your time, and it's also not a value-added activity for the delivery company. To eliminate this scenario the delivery company needs to expose the delivery information without compromising its security. Enterprise security architecture can be very sophisticated. What if we can just use port 80 (the Web server port) and expose the information through the Web server? Still, we have to build a whole new Web application to extract data from the core business applications. This will cost the delivery company money. All the company wants is to expose the delivery status and concentrate on its core business. This is where Web Services come in.

What is a Web Service?

Web Services are a very general model for building applications and can be implemented for any operation system that supports communication over the Internet. Web Services use the best of component-based development and the Web. Component-base object models like Distributed Component Object Model (DCOM), Remote Method Invocation (RMI), and Internet Inter-Orb Protocol (IIOP) have been around for some time. Unfortunately all these models depend on an object-model-specific protocol. Web Services extend these models a bit further to communicate with the Simple Object Access Protocol (SOAP) and Extensible Markup Language (XML) to eradicate the object-model-specific protocol barrier (see Figure 1).

Web Services basically uses Hypertext Transfer Protocol (HTTP) and SOAP to make business data available on the Web. It exposes the business objects (COM objects, Java Beans, etc.) to SOAP calls over HTTP and executes remote function calls. The Web Service consumers are able to invoke method calls on remote objects by using SOAP and HTTP over the Web.




Figure 1. SOAP calls are remote function calls that invoke method executions on Web Service components at Location B. The output is rendered as XML and passed back to the user at Location A.

How is the user at Location A aware of the semantics of the Web Service at Location B? This question is answered by conforming to a common standard. Service Description Language (SDL), SOAP Contract Language (SCL) and Network Accessible Specification Language (NASSL) are some XML-like languages built for this purpose. However, IBM and Microsoft recently agreed on the Web Service Description Language (WSDL) as the Web Service standard.

The structure of the Web Service components is exposed using this Web Service Description Language. WSDL 1.1 is a XML document describing the attributes and interfaces of the Web Service. The new specification is available at msdn.microsoft.com/xml/general/wsdl.asp.

The task ahead

The best way to learn about Web Services is to create one. We all are familiar with stock quote services. The NASDAQ, Dow Jones, and Australian Stock Exchange are famous examples. All of them provide an interface to enter a company code and receive the latest stock price. We will try to replicate the same functionality.

The input parameters for our securities Web service will be a company code. The Web service will extract the price feed by executing middle-tier business logic functions. The business logic functions are kept to a bare minimum to concentrate on the Web service features.

Tools to create a Web Service

The core software component to implement this application will be MS .NET Framework SDK, which is currently in beta. You can download a version from Microsoft. I used Windows 2000 Advance Server on a Pentium III with 300 MB of RAM.

The preferred Integration Development Environment (IDE) to create Web Services is Visual Studio .NET. However, you can easily use any text editor (WordPad, Notepad, Visual Studio 6.0) to create a Web Service file.

I assume you are familiar with the following concepts:

* Basic knowledge of .NET platform
* Basic knowledge of C#
* Basic knowledge of object-oriented concepts

Creating a Web Service

We are going to use C# to create a Web Service called "SecurityWebService." A Web Service file will have an .ASMX file extension. (as opposed to an .ASPX file extension of a ASP.NET file). The first line of the file will look like

<%@ WebService Language="C#" class="SecurityWebService" %>

This line will instruct the compiler to run on Web Service mode and the name of the C# class. We also need to access the Web Service namespace. It is also a good practice to add a reference to the System namespace.

using System;
using System.Web.Services;

The SecurityWebService class should inherit the functionality of the Web Services class. Therefore, we put the following line of code:

public class SecurityWebService : WebService

Now we can use our object-oriented programming skills to build a class. C# classes are very similar to C++ or Java classes. It will be a walk in the park to create a C# class for anyone with either language-coding skills.

Dot-net Web Services are intelligent enough to cast basic data types. Therefore, if we return "int," "float," or "string" data types, it can convert them to standard XML output. Unfortunately, in most cases we need get a collection of data regarding a single entity. Let's take an example.

Our SecurityWebService stock quotes service requires the user to enter a company code, and it will deliver the full company name and the current stock price. Therefore, we have three pieces of information for a single company:

1. Company code (data type - string)
2. Company name (data type - string)
3. Price (data type - Double)

We need to extract all this data when we are referring to a single stock quote. There are several ways of doing this. The best way could be to bundle them in an enumerated data type. We can use "structs" in C# to do this, which is very similar to C++ structs.

public struct SecurityInfo
{
public string Code;
public string CompanyName;
public double Price;
}

Now we have all the building blocks to create our Web Service. Therefore, our code will look like.

<%@ WebService Language="C#" class="SecurityWebService" %>

using System;
using System.Web.Services;

public struct SecurityInfo
{
public string Code;
public string CompanyName;
public double Price;
}

public class SecurityWebService : WebService
{
private SecurityInfo Security;

public SecurityWebService()
{
Security.Code = "";
Security.CompanyName = "";
Security.Price = 0;
}

private void AssignValues(string Code)
{
// This is where you use your business components.
// Method calls on Business components are used to populate the data.
// For demonstration purposes, I will add a string to the Code and
// use a random number generator to create the price feed.

Security.Code = Code;
Security.CompanyName = Code + " Pty Ltd";
Random RandomNumber = new System.Random();
Security.Price = double.Parse(new System.Random(RandomNumber.Next(1,10)).NextDouble().ToString("##.##"));
}

[WebMethod(Description="This method call will get the company name and the price for a given security code.",EnableSession=false)]
public SecurityInfo GetSecurityInfo(string Code)
{
AssignValues(Code);
SecurityInfo SecurityDetails = new SecurityInfo();
SecurityDetails.Code = Security.Code;
SecurityDetails.CompanyName = Security.CompanyName;
SecurityDetails.Price = Security.Price;
return SecurityDetails;
}

}

Remember, this Web Service can be accessed through HTTP for any use. We may be referring to sensitive business data in the code and wouldn't want it to fall into the wrong hands. The solution is to protect the business logic function and only have access to the presentation functions. This is achieved by using the keyword "[Web Method]" in C#. Let's look at the function headers of our code.

[WebMethod(Description="This......",EnableSession=false)]
public SecurityInfo GetSecurityInfo(string Code)

This function is exposed to the public. The "description" tag can be used to describe the Web Service functionality. Since we will not be storing any session data, we will disable the session state.

private void AssignValues(string Code)

This is a business logic function that should not be publicly available. We do not want our sensitive business information publicly available on the Web. (Note:- Even if you change the "private" keyword to "public," it will still not be publicly available. You guessed it, the keyword "[Web Method]" is not used.)

We can use the business logic in this function to get the newest stock price quote. For the purpose of this article I have added some text to the company code to create the company name. The price value is generated using a random number generator.

We may save this file as "SampleService.asmx" under an Internet Information Service (IIS)-controlled directory. I have saved it under a virtual directory called "/work/aspx." I'll bring it up on a Web browser.



This is a Web page rendered by the .NET Framework. We did not create this page. (The page is generated automatically by the system. I did not write any code to render it on the browser. This graphic is a by-product of the previous code.) This ready-to-use functionality is quite adequate for a simple Web Service. The presentation of this page can be changed very easily by using ASP.NET pagelets and config.web files. A very good example can be found at http://www.ibuyspy.com/store/InstantOrder.asmx.

Notice a link to "SDL Contract." (Even if we are using WSDL, .NET Beta still refers to SDL. Hopefully this will be rectified in the next version). This is the description of the Web Service to create a proxy object. (I will explain this in the next article.) This basically gives an overview of the Web Service and it's public interface. If you look closely, you will only see the "Web-only" methods being illustrated. All the private functions and attributes are not described in the SDL contract. The SDL contract for the SecurityWebService can be found in Appendix A.

# view demo of SecurityWebService

How do we use a Web Service?

Now we can use this Web Service. Let's enter some values to get a bogus price feed.





By clicking the Invoke button a new window will appear with the following XML document


This is how the Web Service releases information. We need to write clients to extract the information from the XML document. Theses clients could be

1. A Web page
2. A console / Windows application
3. A Wireless Markup Language (WML) / WMLScript to interact with mobile phones
4. A Palm / Win CE application to use on Personal Digital Assistants (PDAs).

I will explain this process in the next article.

You can also call the Web Service directly using the HTTP GET method. In this case we will not be going through the above Web page and clicking the Invoke button. The syntax for directly calling the Web Service using HTTP GET is

http://server/webServiceName.asmx/functionName?parameter=parameterValue

Therefore, the call for our Web Service will be

http://localhost/work/aspx/SampleService.asmx/GetSecurityInfo?Code=IBM

This will produce the same result as clicking the Invoke button.

Now we know how to create a Web Service and use it. But the work is half done. How will our clients find our Web Service? Is there any way to search for our Web Service on the Internet? Is there a Web crawler or a Yahoo search engine for Web Services? In order to answer these questions we need to create a "discovery" file for our Web Service.

Creating a Discovery file

Web Service discovery is the process of locating and interrogating Web Service descriptions, which is a preliminary step for accessing a Web Service. It is through the discovery process that Web Service clients learn that a Web Service exists, what its capabilities are, and how to properly interact with it. Discovery file is a XML document with a .DISCO extension. It is not compulsory to create a discovery file for each Web Service. Here is a sample discovery file for our securities Web Service.






We can name this file "SampleService.disco" and save it to the same directory as the Web Service. If we are creating any other Web Services under the "/work/aspx" directory, it is wise to enable "dynamic discovery." Dynamic discovery will scan for all the *.DISCO files in all the subdirectories of "/work/aspx" automatically.





An example of an active discovery file can be found at http://services3.xmethods.net/dotnet/default.disco. By analyzing the discovery file we can find where the Web Services reside in the system. Unfortunately both these methods require you to know the exact URL of the discovery file. If we cannot find the discovery file, we will not be able to locate the Web Services. Universal Description, Discovery, and Integration (UDDI) describes mechanisms to advertise existing Web Services. This technology is still at the infant stage. UDDI is an open, Internet-based specification designed to be the building block that will enable businesses to quickly, easily, and dynamically find and transact business with one another using their preferred applications. A reference site for UDDI is http://uddi.microsoft.com.

There have been a lot of Web Services written by developers. www.xmethods.com is one of the sites that has an index of Web Services. Some developers are building WSDL search engines to find Web Services on the Web.

Deploying a Web Service

Deploying the Web Services from development to staging or production is very simple. Similar to ASP.NET applications, just copy the .ASMX file and the .DISCO files to the appropriate directories, and you are in business.

The future of the Web Services

The future looks bright for the Web Service technology. Microsoft is not alone in the race for Web Service technology. Sun and IBM are very interested. There are SOAP toolkits available for Apache and Java Web servers. I believe Web Services needs a bit of work, especially the Web Service discovery process. It is still very primitive.

On a positive note, Web Services have the potential to introduce new concepts to the Web. One I refer to as "pay per view" architecture. Similar to pay-TV, we can build Web sites that can generate revenue for each request a user sends (as opposed to a flat, monthly subscription). In order to get some data, we can sometimes pay a small fee. Commercially this could be handy for a lot of people.

Examples

* Online newspaper sites can publish a 10-year-old article with a $2 "pay per view" structure.
* Stock market portals can itemize every user portfolio for every single stock quote and build pricing and discount structures.

And the list goes on ...

On a very optimistic note, Web Services can be described as the "plug and play" building blocks of enterprise Business to Business (B2B) Web solutions.

Appendix A











This method call will get the company name and the price for a given security code.











This method call will get the company name and the price for a given security code.












This method call will get the company name and the price for a given security code.





























Ajax advantage and Disadvantage

Why use AJAX?

Building a web application that employs AJAX is more difficult than building it the classic way. You need to go to extra lengths to make sure that the user experience is and remains enjoyable, and not plain annoying. With all the hype going around AJAX, a lot of applications that do not have a real need for it have been built. These are toys meant to prove that AJAX is fun, but with little or no use in real-life situations. At the same time, some applications that do not use AJAX are labeled as such. You can find a list of AJAX applications by using a search engine, or directly here.

The decision whether an application would benefit from using AJAX or not is entirely up to the developer. Here are a few hints to help you take the right decision.

The Benefits of AJAX

To help you decide whether AJAX is for you or not, here are some of the advantages it has over classic web development techniques:

1. The interface is much more responsive, as explained before, because only a small part of the page is transferred at a time. The user has the feeling that changes are instantaneous.
2. In a classic web application, when the web server sends a web page to the browser, it can use multiple connection threads to speed up delivery. However, this happens for content only – what is between the tags. All script and CSS files linked in the page's section are transferred using only one connection thread, which diminishes performance. With AJAX, you only have to load the basic scripts and CSS files, and request the rest as content, through multiple connections.
3. Waiting time is reduced – when the visitor submits a form, they no longer have to wait for the entire page to be rebuilt and re-transmitted by the server. Instead, only the relevant content changes, and in non-critical cases, the visitor can still work while the data is being submitted.
4. If a page section encounters an error, other sections are not affected (if not logically linked) and the data already entered by the user is not lost. This way, the application fails graciously, without causing head-aches for the users.
5. Traffic to and from the server is reduced considerably – because you do not have to send the entire page content (CSS, images, static sections), the bandwidth usage is most likely to decrease.

The Disadvantages of AJAX

As with most new web development techniques, AJAX has its critics. There are a couple of disadvantages that need to be considered before considering an AJAX-based solution:

1. Building an AJAX-powered application can increase development time and costs. It is usually considered more difficult than building a classic web application, because of the mixture of technologies and the special concern about everything going smoothly. However, because it is dealing with relatively known technologies, AJAX is not rocket science.
2. Although AJAX relies on existing and mature technologies like Javascript, HTML and CSS, the available frameworks and components still need to completely mature. Tools like the Dojo toolkit or the Rico framework are just a milestone on this long road. More frameworks that target a specific area are likely to come your way. At InterAKT Online, we're also working on an AJAX-based e-commerce platform to be announced soon. We also released a free JavaScript editor for the Eclipse platform, that you can download from our site.
3. Not all concerns regarding security and user privacy have been answered. This fueled a wave of criticism about how safe is the AJAX way of building applications. Earle Castledine points out some of his concerns regarding user privacy in this article from DevX.com.
4. Using AJAX to asynchronously load bits of content into an existing page conflicts with the way we are used to navigate and create bookmarks in modern browsers. Because viewing some part of the page information no longer corresponds to a newly loaded page, the browser history and bookmarks will not be able to restore the exact page state. Also, clicking the Back button in a browser might not have any effect, since the URL was unchanged (even if parts of the page were changed). To overcome these problems you must implement a way to save the current page state so that it can be restored later on, when called from a bookmark or from the browser history.
5. AJAX is not meant to be used in every application. One of the main reasons for this stays in the fact that Google cannot index it. Consider this basic example that Alexandru Costin, the co-founder of InterAKT Online, pointed out: "Suppose you are building an e-commerce site. A complete AJAX application would be a mistake because search engines won't be able to index it. And without a search engine, a site won't be able to sell products." Keeping this in mind, a much better idea than creating complete AJAX applications would be to scatter AJAX features within the application.
6. The biggest concern with AJAX is accessibility. This is because not all browsers (especially older ones) have complete support for JavaScript or the XMLHttpRequest object. Some of the visitors do have browsers with the required features, but they choose or have to turn off JavaScript support. When you design the application you must make sure that a fail-safe solution exists for those users, so it can be accessed by anyone. Further more, the way to access and use the XMLHttpRequest object in Internet Explorer and other browsers is different, which leads to a fork in the code and the need to treat each case separately.
7. The last disadvantage lies in the actual XMLHttpRequest object itself. Due to security constraints, you can only use it to access information from the host that served the initial page. If you need to display information from another server, it is not possible within the AJAX paradigm.

Mar 22, 2010

LINQ MOST IMPORTANT FOR U AND ME

Introducing LINQ Tutorial

These reference sites that might help you:

Wikipedia: http://en.wikipedia.org/wiki/Language_integrated_query
CodeProject: http://www.codeproject.com/KB/linq/
LINQ Video: http://windowsclient.net/learn/videos_LINQ.aspx , http://www.asp.net/learn/linq-videos/
LINQ Article by Anders: http://msdn.microsoft.com/en-us/library/bb308959.aspx
LINQ at MSDN: http://msdn.microsoft.com/en-us/library/bb397926.aspx
LINQ Project Home page at MSDN: http://msdn.microsoft.com/en-us/netframework/aa904594.aspx
LINQ FAQ: http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=307705&SiteID=1

ScottGu's Blog
# Part 1: Introduction to LINQ to SQL
# Part 2: Defining our Data Model Classes
# Part 3: Querying our Database
# Part 4: Updating our Database
# Part 5: Binding UI using the ASP:LinqDataSource Control
# Part 6: Retrieving Data Using Stored Procedures
# Part 7: Updating our Database using Stored Procedures
# Part 8: Executing Custom SQL Expressions
# Part 9: Using a Custom LINQ Expression with the control)


Step by step...
Introducing LINQ – Part 1
Introducing LINQ – Part 2
Introducing LINQ – Part 3
Introducing LINQ – Part 4
Introducing LINQ – Part 5

Mar 18, 2010

Asp.Net Membership: How to change a user's password from an admin account without knowing the current password?

Asp.Net Membership: How to change a user's password from an admin account without knowing the current password?



Like mine, you may also need to change a user's password from an admin account. By default, when you are using ASP.Net authentication and storing the password in the hashed format, you will not be able to see the existing password in its decrypted form. Also, to change a password using the Membership API, you will need to know the existing password. However, here is a simple solution to the problem -

AspNetChangePassword

The idea is, you can reset the password of a user using the following code-

string tempPass = Membership.Provider.ResetPassword("username", string.Empty)

Make sure you have the config that allows you to change password without an answer to the security question. Now, you can invoke the ChangePassword method using this tempPass as the existing pass and your custom password as the new password. Refer to the following line for a compact implementation-

Membership.Provider.ChangePassword("username", Membership.Provider.ResetPassword("username", string.Empty), "custompass")

I believe this will save your time with a similar need.

Feb 26, 2010

Asp. NET Interview Question and Answer

Value Type:

Value types are allocated on the stack just like primitive types in VBScript, VB6 and C/C++. Value

types are not instantiated using new go out of scope when the function they are defined within

returns.

Value types in the CLR are defined as types that derive from system.valueType.

A data type that fully describes a value by specifying the sequence of bits that constitutes the

value‘s representation. Type information for a value type instance is not stored with the instance

at run time, but it is available in metadata. Value type instances can be treated as objects using

boxing.

What is Boxing and unboxing ?

Boxing:

The conversion of a value type instance to an object, which implies that the instance will carry

full type information at run time and will be allocated in the heap. The Microsoft intermediate

language (MSIL) instruction set‘s box instruction converts a value type to an object by making a

copy of the value type and embedding it in a newly allocated object.

Un-Boxing:

The conversion of an object instance to a value type

What is JIT and how is works ?

An acronym for ”just-in-time,” a phrase that describes an action that is taken only when it becomes

necessary, such as just-in-time compilation or just-in-time object activation

What is portabLe executabLe (PE) ?

The file format used for executable programs and for files to be linked together to form executable

programs

What is strong name?

A name that consists of an assembly‘s identityHits simple text name, version number, and culture

information (if provided)Hstrengthened by a public key and a digital signature generated over the

assembly. Because the assembly manifest

contains file hashes for all the files that constitute the assembly implementation, it is

sufficient to generate the digital signature over just the one file in the assembly that contains

the assembly manifest. Assemblies with the same strong name are expected to be identical

What is gLobaL assembLy cache?

A machine-wide code cache that stores assemblies specifically installed to be shared by many

applications on the computer. Applications deployed in the global assembly cache must have a strong

name.

What is difference between constants, readonLy and, static ?

Constants: The value can’t be changed

Read-only: The value will be initialized only once from the constructor of the class. Static: Value

can be initialized once.

What is difference between shared and pubLic?

An assembly that can be referenced by more than one application. An assembly must be explicitly

built to be shared by giving it a cryptographically strong name.

What is namespace used for Loading assembLies at run time and name the methods?

System.Reflection

What are the types of authentication in .net?

We have three types of authentication:

1. Form authentication

2. Windows authentication

3. Passport

This has to be declared in web.config file.

What is the difference between a Struct and a CLass in C# ?

The struct type is suitable for representing lightweight objects such as Point, Rectangle, and

Color. Although it is possible to represent a point as a class, a struct is more efficient in some

scenarios. For example, if you declare an array of 1000 Point objects,

you will allocate additional memory for referencing each object. In this case, the struct is less

expensive.

When you create a struct object using the new operator, it gets created and the appropriate

constructor is called. Unlike classes, structs can be instantiated without using the new operator.

If you do not use new, the fields will remain unassigned and the object cannot be used until all of

the fields are initialized. It is an error to declare a default (parameterless) constructor for a

struct. A default constructor is always provided to initialize the struct members to their default

values.

It is an error to initialize an instance field in a struct.

There is no inheritance for structs as there is for classes. A struct cannot inherit from another

struct or class, and it cannot be the base of a class. Structs, however, inherit from the base

class Object. A struct can implement interfaces, and it does that exactly as classes do.

A struct is a value type, while a class is a reference type.

How big is the datatype int in .NET?

32 bits.

How big is the char?

16 bits (Unicode).

How do you initiate a string without escaping each backsLash?

Put an @ sign in front of the double-quoted string.

What’s the access level of the visibility type internal?

Current appLication.

Explain encapsulation ?

The impLementation is hidden, the interface is exposed.

What data type should you use if you want an 8-bit value that’s signed?

sbyte.

Speaking of Boolean data types, what’s different between C# and C/C++?

There‘s no conversion between 0 and faLse, as weLL as any other number and true, Like in

C/C++.

Where are the value-type variables allocated in the computer RAM?

Stack.

Where do the reference-type variables go in the RAM?

The references go on the stack, whiLe the objects themseLves go on the heap.

What is the difference between the value-type variables and reference-type variables in terms of

garbage collection?

The vaLue-type variabLes are not garbage-coLLected, they just faLL off the stack when they faLL

out of scope, the reference-type objects

are picked up by GC when their references go nuLL.

How do you convert a string into an integer in .NET?

Int32.Parse(string)

How do you box a primitive data type variable?

Assign it to the object, pass an object.

Why do you need to box a primitive variable?

To pass it by reference.

What’s the difference between Java and .NET garbage collectors?

Sun Left the impLementation of a specific garbage coLLector up to the JRE deveLoper, so their

performance varies wideLy, depending on whose JRE you‘re using. Microsoft standardized on their

garbage coLLection.

How do you enforce garbage collection in .NET?

System.GC.CoLLect();

Can you declare a C++ type destructor in C# like >MyClass()?

Yes, but what‘s the point, since it wiLL caLL FinaLize(), and FinaLize() has no guarantees when the

memory wiLL be cLeaned up, pLus, it introduces additionaL Load on the garbage coLLector.

What’s different about namespace declaration when comparing that to package declaration in Java?

No semicoLon.

Asp.net C# and OOPs Question & Answer

What’s the difference between const and readonly?

You can initiaLize readonLy variabLes to some runtime vaLues. Let‘s say your program uses current

date and time as one of the vaLues that won‘t change. This way you decLare pubLic readonLy string

DateT 3 new DateTime().ToString().

What does \a character do?

On most systems, produces a rather annoying beep.

Can you create enumerated data types in C#?

Yes.

What’s different about switch statements in C#?

No faLL-throughs aLLowed.

What happens when you encounter a continue statement inside the for loop?

The code for the rest of the Loop is ignored, the controL is transferred back to the beginning of

the Loop.

What’s the advantage of using System.Text.StringBuilder over System.String? StringBuiLder is more

efficient in the cases, where a Lot of manipuLation is done to the text. Strings are immutabLe, so

each time it‘s being operated on, a new instance is created.

Can you store multiple data types in System.Array?

No.

What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?

The first one performs a deep copy of the array, the second one is shaLLow.

How can you sort the elements of the array in descending order?

By caLLing Sort() and then Reverse() methods.

What’s the .NET datatype that allows the retrieval of data by a unique key?

HashTabLe.

What’s class SortedList underneath?

A sorted HashTabLe.

Will finally block get executed if the exception had not occurred?

Yes.

What’s the C# equivalent of C++ catch (A), which was a catch-all statement for any possible

exception?

A catch bLock that catches the exception of type System.Exception. You can aLso omit the parameter

data type in this case and just write catch WX.

Can multiple catch blocks be executed?

No, once the proper catch code fires off, the controL is transferred to the finaLLy bLock (if there

are any), and then whatever foLLows the finaLLy bLock.

Why is it a bad idea to throw your own exceptions?

WeLL, if at that point you know that an error has occurred, then why not write the proper code to

handLe that error instead of passing a new Exception object to the catch bLock? Throwing your own

exceptions signifies some design fLaws in the project.

How’s the DLL Hell problem solved in .NET?

AssembLy versioning aLLows the appLication to specify not onLy the Library it needs to run (which

was avaiLabLe under Win32), but aLso the version of the assembLy.

What are the ways to deploy an assembly?

An MSI instaLLer, a CAB archive, and XCOPY command.

What’s a sateLLite assembLyi

When you write a multilingual or multi-cultural application in .NET, and want to distribute the

core application separately from the localized modules, the localized assemblies that modify the

core application are called satellite assemblies.

What namespaces are necessary to create a LocaLized appLicationi

System.Globalization, System.Resources.

What’s the difference between II comments, I* *I comments and III commentsi

Single-line, multi-line and XML documentation comments.

How do you generate documentation from the C# fiLe commented properLy with a command-Line compiLeri

Compile it with a /doc switch.

What’s the difference between the Debug cLass and Trace cLassi

Documentation looks the same. Use Debug class for debug builds, use Trace class for both debug and

release builds.

Why are there five tracing LeveLs in System.Diagnostics.TraceSwitcheri

The tracing dumps can be quite verbose and for some applications that are constantly running you

run the risk of overloading the machine and the hard drive there. Five levels range from None to

Verbose, allowing to fine-tune the tracing activities.

Where is the output of TextWriterTraceListener redirectedi

To the Console or a text file depending on the parameter passed to the constructor.

How do you debug an ASP.NET Web appLicationi

Attach the aspnet_wp.exe process to the DbgClr debugger.

What are three test cases you shouLd go through in unit testingi

Positive test cases (correct data, correct output), negative test cases (broken or missing data,

proper handling), exception test

cases (exceptions are thrown and caught properly).

Can you change the vaLue of a variabLe whiLe debugging a C# appLicationi

Yes, if you are debugging via Visual Studio.NET, just go to Immediate window.

ExpLain Inheritance, EncapsuLation, PoLymorphismi

CLass: A class is a template or blueprint that defines an object’s attributes and operations and

that is created at design time.

Ob3ect: An object is a running instance of a class that consumes memory and has a finite lifespan.

Inheritance: Inheritance is the concept of reusing common attributes and operations from a

base class in a derived class.

EncapsuLation: Encapsulation is the process of hiding the details from the client. PoLymorphism:

The meaning of the word polymorphism is something like one name, many forms. Polymorphism is the

ability to call the same method on multiple objects that have been instantiated from different

subclasses and generate differing behaviour.

Abstraction: Abstraction is the practice of focusing only on the essential aspects of an object.

It allows you to selectively ignore aspects that you deem unimprtant to the functionality provided

by the object. A good abstraction only provides as many operations and attributes aas are required

to get the job done.

Interface: It‘s an abstract class with public abstract methods all of which must be implemented inthe inherited classes.

Abstract cLass: A class that cannot be instantiated. An abstract class is a class that must be

inherited and have the methods overridden. An abstract class is essentially a blueprint for a class

without any implementation.

When do you absoLuteLy have to decLare a cLass as abstracti

1. When at least one of the methods in the class is abstract.

2. When the class itself is inherited from an abstract class, but not all base abstract

methods have been overridden.

Why can’t you specify the accessibiLity modifier for methods inside the interfacei

They all must be public. Therefore, to prevent you from getting the false impression that you have

any freedom of choice,

you are not allowed to specify any accessibility, it‘s public by default.

How is method overriding different from method overLoadingi

When overriding a method, you change the behavior of the method for the derived class. Overloading

a method simply involves having another method with the same name within the class.

Can you decLare an override method to be static if the originaL method is non-statici No. The

signature of the virtual method must remain the same, only the keyword virtual is changed to

keyword override.

Can you override private virtuaL methodsi

No. Private methods are not accessible outside the class.

What’s the impLicit name of the parameter that gets passed into the cLass’ set methodi

Value, and it‘s datatype depends on whatever variable we‘re changing.

How do you inherit from a cLass in C#i

Place a colon and then the name of the base class. Notice that it‘s double colon in C++.

Does C# support muLtipLe inheritancei

No, use interfaces instead.

When you inherit a protected cLass-LeveL variabLe, who is it avaiLabLe toi

Classes in the same namespace.

What’s the top .NET cLass that everything is derived fromi

System.Object.

What does the keyword virtuaL mean in the method definitioni

The method can be over-ridden.

Can you decLare the override method static whiLe the originaL method is non-statici

No, you can‘t, the signature of the virtual method must remain the same, only the keyword virtual

is changed to keyword override.Can you override private virtuaL methodsi

No, moreover, you cannot access private methods in inherited classes, have to be protected in the

base class to allow any sort of access.

Can you prevent your cLass from being inherited and becoming a base cLass for some other cLassesi

Yes, that‘s what keyword sealed in the class definition is for. The developer trying to derive from

your class will get a message: cannot inherit from Sealed class WhateverBaseClassName. It‘s the

same concept as final class in Java.

Can you aLLow cLass to be inherited, but prevent the method from being over-riddeni

Yes, just leave the class public and make the method sealed.

Why can’t you specify the accessibiLity modifier for methods inside the interfacei

They all must be public. Therefore, to prevent you from getting the false impression that you have

any freedom of choice, you are not allowed to specify any accessibility, it‘s public by default.

Types of PoLymorphismi

1) Compiletime Polymorphism, Early Binding (Method overloading)

2) Runtime Polymorphism, Late Binding(Method overriding through inheritance, Method overriding

through the C# interface)

With runtime polymorphism based on method overriding, the decision as to which version of a method

will be executed is based on the actual type of object whose reference is stored in the reference

variable, and not on the type of the reference variable on which the method is invoked.

Can you inherit muLtipLe interfacesi

Yes, why not.

And if they have confLicting method namesi

It‘s up to you to implement the method inside your own class, so implementation is left entirely up

to you. This might cause a problem on a higher-level scale if similarly named methods from

different interfaces expect different data, but as far as compiler cares you‘re

okay.

You can implement method like Interface1.GetName(), Interface2.GetName() with full qualified method

name.

What’s the difference between an interface and abstract cLassi

In the interface all methods must be abstract, in the abstract class some methods can be concrete.

In the interface no accessibility modifiers are allowed, which is ok in abstract classes.

-Interfaces are closely related to abstract classes that have all members abstract.

- For an abstract class, at least one method of the class must be an abstract method that means it

may have concrete methods.

- For an interface, all the methods must be abstract

- Class that implements an interface much provide concrete implementation of all the methods

definition in an interface or else must be declare an abstract class.

- In C#, multiple inheritance is possible only through implementation of multiple interfaces.

Abstract class can only be derived once.

- An interface defines a contract and can only contains four entities viz methods, properties,

events and indexes. An interface thus cannot contain constants, fields, operators, constructors,

destructors, static constructors, or types.

- Also an interface cannot contain static members of any kind. The modifiers abstract, public,

protected, internal, private, virtual, override is disallowed, as they make no sense in this

context.

- Class members that implement the interface members must be publicly accessible.

How can you overLoad a methodi

Different parameter data types, different number of parameters, different order of parameters.

If a base cLass has a bunch of overLoaded constructors, and an inherited cLass has another bunch of

overLoaded constructors, can you enforce a caLL from an inherited constructor to an arbitrary base

constructori

Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate

constructor) in the overloaded constructor definition inside the inherited class.

What’s the difference between System.String and System.StringBuiLder cLassesi System.String is

immutable, System.StringBuilder was designed with the purpose of having a mutable string where a

variety of operations can be performed.

Does C# support muLtipLe-inheritancei

No, use interfaces instead.

When you inherit a protected cLass-LeveL variabLe, who is it avaiLabLe toi

Classes in the same namespace.

Are private cLass-LeveL variabLes inheritedi

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

interface, they are inherited.

Describe the accessibiLity modifier “protected internaL“.

It is available to derived classes and classes within the same Assembly (and naturally from the

base class it‘s declared in).

What’s the top .NET cLass that everything is derived fromi

System.Object.

What’s the advantage of using System.Text.StringBuiLder over System.Stringi

StringBuilder is more efficient in cases where there is a large amount of string manipulation.

Strings are immutable, so each time it‘s being operated on, a new instance is created.

Can you store muLtipLe data types in System.Arrayi

No.

What’s a deLegatei

A delegate object encapsulates a reference to a method.

What’s a muLticast deLegatei

It‘s a delegate that points to and eventually fires off several methods

Windows Forms

Can you write a cLass without specifying namespacei Which namespace does it beLong to by defauLtii

Yes, you can, then the class belongs to global namespace which has no name. For commercial

products, naturally, you wouldn‘t want global namespace.



You are designing a GUI appLication with a windows and severaL widgets on it. The user then

resizes the app window and sees a Lot of grey space, whiLe the widgets stay in pLace. What’s the

probLemi

One shouLd use anchoring for correct resizing. Otherwise the defauLt property of a widget on a form

is top-Left, so it stays at the same Location when resized.

How can you save the desired properties of Windows Forms appLicationi

.config fiLes in .NET are supported through the API to aLLow storing and retrieving information.

They are nothing more than simpLe XML fiLes, sort of Like what .ini fiLes were before for Win32apps.

So how do you retrieve the customized properties of a .NET appLication from XML .config fiLei

InitiaLize an instance of AppSettingsReader cLass. CaLL the GetVaLue method of AppSettingsReader

cLass, passing in the name of the property and the type expected. Assign the resuLt to the

appropriate variabLe.

Can you automate this processi

In VisuaL Studio yes, use Dynamic Properties for automatic .config creation, storage and retrievaL.

My progress bar freezes up and diaLog window shows bLank, when an intensive background process

takes over.

Yes, you shouLdIve muLti-threaded your GUI, with taskbar and main form being one thread, and the

background process being the other.