Sunday, May 31, 2009

Delete multifile entry from gridview

AutoGenerateColumns="False"
DataSourceID="SqlDataSource1"
ShowFooter="true">






OnClick="btnDelete_Click"
OnClientClick="return DeleteConfirmation();"/>


HeaderText="ID"
SortExpression="ID" />
HeaderText="Title"
SortExpression="Title" />
HeaderText="Director"
SortExpression="Director" />
HeaderText="Date"
SortExpression="date" />
HeaderText="BoxOfficeTotal"
SortExpression="boxofficetotal" />







create your data source which can be sql , access whatever u want ..........

C# code


using System;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections.Specialized;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
string strcon = "Data Source=.;Initial Catalog=pubs;Persist Security Info=True;User ID=sa;Password=sa";
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnDelete_Click(object sender, EventArgs e)
{
StringCollection idCollection = new StringCollection();
string strID = string.Empty;

//Loop through GridView rows to find checked rows
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chkDelete = (CheckBox)
GridView1.Rows[i].Cells[0].FindControl("chkSelect");
if (chkDelete != null)
{
if (chkDelete.Checked)
{
strID = GridView1.Rows[i].Cells[1].Text;
idCollection.Add(strID);
}
}
}

//Call the method to Delete records
DeleteMultipleRecords(idCollection);

// rebind the GridView
GridView1.DataBind();
}
private void DeleteMultipleRecords
(StringCollection idCollection)
{
//Create sql Connection and Sql Command
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand();
string IDs = "";

foreach (string id in idCollection)
{
IDs += id.ToString() + ",";
}
try
{
string strIDs =
IDs.Substring(0, IDs.LastIndexOf(","));
string strSql = "Delete from movie WHERE id in (" + strIDs + ")";
cmd.CommandType = CommandType.Text;
cmd.CommandText = strSql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
string errorMsg = "Error in Deletion";
errorMsg += ex.Message;
throw new Exception(errorMsg);
}
finally
{
con.Close();
}
}
}



Tuesday, May 26, 2009

VB.NET QUESTION

VB.NET QUESTION

Question:-Can you define what is Jagged Array in VB.NET ?
Answer: Jagged array is multidimensional array. If jagged array is two dimensinal it also contain a table where each row can have a different number of columns.
A jagged array is really an array of arrays. To create a jagged array, you declare the array of arrays with multiple sets of parentheses or brackets and indicate the size of the jagged array in the first set of brackets.

Question:-What is DataType conversion in VB.NET ?
Answer: Convert one variable type to another one is called datatype conversion we can also caleed this casting in VB.NET some automatically conversion is also there.
Cbool CByte CChar Cdate CDec CDbl CInt CLng CObj CShort CSng CStr CType Asc.

Question:-What do u mean by Redim in VB.NET ?
Answer: In vb.net we use Redim and erase to manipulate Array. Once we declare an array the size set to array its makes limited to that range but with the help of redim we used to change the array size.
Redim arr(6)
we can also used preserve to save these values.
Redim Preserve arr(6)

Question:- What is branching logic control in vb.net ?
Answer: Function and subroutines are the answer.The diffrence in two of them is function send information back from where it is called means function can return a value but subroutines can not do this.

Question:-Write the role of New keyword ?
Answer: New is used to initialize a new object. We sets a variable to any dattype with help of New keyword .The New keyword gives a value to the variable.We can also uses new keyword to initialize an object variable.
Example:- dim obj as new SqlDataAdapter.


Question: What is diffrenet between import System.Data.SqlClient,System.Data.Oledb ?
Answer: System.Data.OleDB It contains the objects that we use to connect to a data source via an OleDB provider , such as OleDbConnection, OleDBCOmmand. System.Data.SqlClient It contains objects that we use to connect to a data source via Tabular data stream interface provided by Microsoft Sql Server. This can be generally used to provide better performance because it removes some of the intermediate layers required by the OleDB provider.

Question: What is the difference between DataTable and DataSet
Answer: Dataset: Represents an in-memory cache of data we can also say data set is a collection of data table it is based on xml format ,it is used for data storing in cache as a disconnected recordset dataset is using data manipulation in cache wthout connection to database. DataTable: Represents one table of in-memory data data table can have one table only or we can say Data table is a collection of record's that consist the single table

Question: What is the difference between VB and VB.NET?
Answer: Object-based language and Does not support inheritance also ADO.Net does not give support for disconnected data architecture and there is No interoperability function and No support for threading. On the other hand VB.NET is Object-Oriented Programming language and ADO.Net gives support for disconnected data architecture also provides interoperability and Its uses managed code and supports threading also provides access to third-party controls like COM, DCOM

COM, DCOM +DCOM+

COM, DCOM +DCOM+


Question:-Can it is possible to use COM objects from a .NET Framework program ?
Answer: :- I think yes COM component which we have deployed today can be used from managed code, and in common cases the its adopt automatic. To access com component from the .NET Framework we use runtime callable wrapper (RCW). This wrapper turns the COM interfaces exposed by the COM component into .NET Framework-compatible interfaces. For OLE automation interfaces, the RCW can be generated automatically from a type library. But for non-OLE automation interfaces, a developer may have to write a custom RCW and then manually map types that is exposed by the COM interface to .NET Framework-compatible types.

Question:-What is Monikers when using COM ?
Answer: Clients always require a easy way to reconnect the same process where he is on last time or we can say that exact same state at a later point in time. This support is provided via "monikers". A moniker is a COM object that helps in this task because its knows how to create and initialize the content of a single COM object instance. A moniker can be asked to bind to the COM object it showing, so a COM object on specific machine on the network, or a group of cells inside a spreadsheet.

Question:-Explain Transaction with COM+ Components?
Answer: Transaction consists of group of task bind in a single execution unit .When a transaction starts with specific task it is completed when all the statement in units are completed if any one produce error it will Rollback.So transaction have only two result Success and failure.
On the other hand COM+ components need code to transaction.Because it will automatically participate in transaction.Its not require any explicit code to specify the start and end of transaction.when we create an object of COM+ it is activated with BeginTransaction with COM+ services provides.And this object is deactivated using CommitTransaction or AbortTransaction method.


Question:-How COM+ Component adopt security?
Answer: To reduce complexity COM+ used or provides role-based security service that's helps in middle-tier components.There are two types of role-based security.
(1)Declaractive
(2)Programmatic
When we applied and configure security without using an explicit programming interface is known as declartive security settings. On the other hand there are some situation when work load is heavy and secuirty is must and exchange of data accross the network and security measure should be taken with programming interface and it is known as programmactic secrity.

Question:-What are the COM Component in .Net?
Answer: .Net not helps in creation of COM components and provides a different solution for making reusable components through Assemblies.There are many COM components present which our .Net application might need to use..Net provides an extremely simple approach to achieve this.
We use com by ‘Wrapper Classes’ and ‘Proxy Components’. .Net wraps the COM component into .Net assembly technically called ‘Runtime Callable Wrapper’ or RCW. Then u can call and use your COM component just as a .Net (or C#, if u are using C#) Assembly.

Question:-Whats the relation between COM/DCOM ?
Answer: DCOM is an extended to COM that allows network-based component interaction. Because COM only ability that processes can run on the same machine but in different address spaces, the DCOM extension allows across a network. DCOM components can helpfull on variety of platforms . we can also say that COM and DCOM is single technology that provides a many services for component interaction, some specific tasks are component integration on a single platform,component interaction across heterogeneous networks.COM and its DCOM extensions are merged into a single runtime.

Question:-Which namespace do the classes, allowing you to support COM functionality, are located?
Answer: System.EnterpriseServices

Question:- How do you make a NET component talk to a COM component?
Answer: To enable the communication between COM and .NET components, the .NET Framework generates a COM Callable Wrapper (CCW). The CCW enables communication between the calling COM code and the managed code. It also handles conversion between the data types, as well as other messages between the COM types and the .NET types.

Question:-How do you generate an RCW from a COM object?
Answer: Use the Type Library Import utility shipped with SDK. tlbimp COMobject.dll /out:.NETobject.dll or reference the COM library from Visual Studio in your project.

Question:-I can’t import the COM object that I have on my machine. Did you write that object?
Answer:You can only import your own objects. If you need to use a COM component from another developer, you should obtain a Primary Interop Assembly (PIA) from whoever authored the original object.

Question:-How do you call unmanaged methods from your .NET code through PInvoke?
Answer: Supply a DllImport attribute. Declare the methods in your .NET code as static extern. Do not implement the methods as they are implemented in your unmanaged code, you’re just providing declarations for method signatures.

Question:- Can you retrieve complex data types like structs from the PInvoke calls?
Answer: Yes, just make sure you re-declare that struct, so that managed code knows what to do with it.

Question:- I want to expose my .NET objects to COM objects. Is that possible?
Answer: Yes, but few things should be considered first. Classes should implement interfaces explicitly. Managed types must be public. Methods, properties, fields, and events that are exposed to COM must be public. Types must have a public default constructor with no arguments to be activated from COM. Types cannot be abstract.

Question:-Can you inherit a COM class in a .NET application?
Answer: The .NET Framework extends the COM model for reusability by adding implementation inheritance. Managed types can derive directly or indirectly from a COM coclass; more specifically, they can derive from the runtime callable wrapper generated by the runtime. The derived type can expose all the method and properties of the COM object as well as methods and properties implemented in managed code. The resulting object is partly implemented in managed code and partly implemented in unmanaged code.

Question:-Suppose I call a COM object from a .NET applicaiton, but COM object throws an error. What happens on the .NET end?
Answer: COM methods report errors by returning HRESULTs; .NET methods report them by throwing exceptions. The runtime handles the transition between the two. Each exception class in the .NET Framework maps to an HRESULT.

XML Interview Question

XML Interview Question

Question :Parse an XML file or XML file validation ?
Answer: We can parse an xml FILE with an xsd FILE. It message us that our file is not well-formed and then if it is not valid it lists out the specific reason ,it is quite helpful to find an error in a large XML file it also returns line number which contain error also the tag name. That is done in Visual Studio .NET so to get it to work you will have to change the code around to whatever you want to do. One thing is that we must have namespace in the root element of the XML file.

Question:-Is it possible that XML accept UNICODE characters ?
Answer: Yes XML documents can contain foreign characters, like Norwegian æ ø å , or French ê è é.But XML document can not under stand this to understand this we have to take XML as UNICODE.There are some encoding techniques.



.

Question:-What is DOM?
Answer: Document Object Model (DOM) is a W3C specification that defines a standard (abstract) programming API to build, navigate and update XML documents. It is a "tree-structure-based" interface. As per the DOM specification, the XML parsers (such as MSXML or Xerces), load the entire XML document into memory, before it can be processed. XPath is used to navigate randomly in the document, and various DOM methods are used to create and update (add elements, delete elements, add/remove attributes, etc.) the XML documents.

Question: What is XMLA define it ?
Answer: First of we take a full form of XMLA (XML Analysis Services). Analysis Service was designed to draw reports from data contained in a Data Warehouses and doe snot have any relation with data structure.From XMLA we can expose the Analysis service data to external world in XML.

Question:-What is XML ?
Answer: XML is the Extensible Markup Language. It improves the functionality of the Web by letting you identify your information in a more accurate, flexible, and adaptable way. It is extensible because it is not a fixed format like HTML (which is a single, predefined markup language). Instead, XML is actually a metalanguage—a language for describing other languages—which lets you design your own markup languages for limitless different types of documents. XML can do this because it's written in SGML, the international standard metalanguage for text document markup (ISO 8879).

Question:-What is XPath?
Answer: XML Path Language (XPath) is a W3C specification that defines syntax for addressing parts of XML document. XML document is considered as a logical tree structure, and syntax based on this consideration is used to address elements and attributes at any level in the XML document. For example, considering the XML document described above in answer to question 2, /abc:Employees/abc:Emp/@EmpID XPath expression can be used to access the EmpID attribute under the (first) Emp element under the Employees document element. XPath is used in various other specifications such as XSLT.

Question:-What is XHTML?
Answer: Is simple words, XHTML, or Extensible HTML, is HTML 4 with XML rules applied to it (each begin tag must have an end tag, attribute values in single/double quotes, etc.). However, the overall vision of XHTML is much more than that. In addition to using XML syntax for HTML, XHTML also encloses specifications such as XHTML Basic (minimal set of modules for devices such as PDAs), XForms (represents the next generation of forms for the Web, and separates presentation, logic, and data), XML Events (provides XML languages with the ability to uniformly integrate event listeners and associated event handlers), etc.


Question:-What is XML Parser ?
Answer: Microsoft's XML parser is a COM component that comes with Internet Explorer 5 and higher. Once you have installed Internet Explorer, the parser is available to scripts.
Microsoft's XML parser supports all the necessary functions to traverse the node tree, access the nodes and their attribute values, insert and delete nodes, and convert the node tree back to XML.

To create an instance of Microsoft's XML parser with JavaScript, use the following code:
var xmlDoc=new ActiveXObject("Microsoft.XMLDOM")

To create an instance of Microsoft's XML parser with VBScript, use the following code:
set xmlDoc=CreateObject("Microsoft.XMLDOM")

To create an instance of Microsoft's XML parser in an ASP page (using VBScript), use the following code:
set xmlDoc=Server.CreateObject("Microsoft.XMLDOM")

The following code loads an existing XML document ("note.xml") into Microsoft's XML parser:


Question:- Some Limitation or Disadvantage of XML?
Answer: XML markup has a few disadvantages:
It can be verbose unless element and attribute names are chosen with care. In large documents the markup overhead need not be large, but in short messages it can be significantly more than the actual data, especially when the element or attribute names are concocted by machine.

Overlapping markup is not permitted (an element cannot start inside one element and end inside another): element markup must nest hierarchically.

Some of the software is truly mediocre.

Question:- How to add in XML document through XSL ?
Answer: XSL (the eXtensible Stylesheet Language) is far more sophisticated than CSS. One way to use XSL is to transform XML into HTML before it is displayed by the browser as demonstrated in these examples:
Below is a fraction of the XML file. The second line,
, links the XML file to the XSL file:




Belgian Waffles
$5.95

two of our famous Belgian Waffles

650



Question:- How do I convert my existing HTML documents into XML?
Answer: Tidy is a command-line utility which runs on a wide variety of operating systems; it uses various command-line switches (parameters) to control its processing. At a minimum, it simply cleans up your HTML by ensuring that elements are properly nested and so on; it also warns you if your HTML uses non-standard code that's likely to cause cross-browser compatibility problems. One of the most useful command-line options is -asxml ("as XML," see?), which does what you seem to be asking. It will properly balance elements, per usual, but it also adds some extra information to the document. For instance, it tacks on an XML declaration, , and a statement, which unambiguously mark this as an XML document. To the root html element it also adds a namespace-declaring attribute that identifies all elements in the document as conforming to the specific XML vocabulary known as XHTML. It even forces all element names to lowercase, since the XHTML standard requires it.

If you're asking about converting HTML to a less generic form of XML than XHTML, your task may turn out to be quite complex. For example, if you've been using HTML to mark up customer invoices, not only the customer's name but also their number, item(s) ordered, quantity, and price are probably all wrapped up inside

and

tags. How do you know which "kind of paragraph" contains a given kind of information, so you can turn one instance of the p element into a custname element, another into custnumber, another into price, and so on? If you've been using CSS for styling your HTML, you may have supplied the different p elements with class="custname" (etc.) attributes and so on; if that's the case, you may be able to generate meaningful XML using an XSLT stylesheet. There may also be customized software to do the sort of conversion you want. Otherwise you're probably looking down the barrel of an ugly gun.

Question:- What is a schema? What are the limitations of a DTD?
Answer: SCHEMA is nothing but METADATA. The schema holds all the information of the xml file that is to be deployed in the project. Metatdata is nothing about data about data since we know that xml is used for data representation language we will be able to understand what metadata is. Metadata includes the tags that is going to be exchanged to and fro from another xml file. DTD (DATA TYPE DEFINITION ) which supervises two conditions namely well formedness and closeness of the xml file. So the user should be aware of what tags he was put into use of this xml file 'A' should be intimated to another application's XML file 'B', by then our xml file will interact with the another xml file, this is the major limitation and mandatory issue that the developers should follow.

WEB SERVICES INTERVIEW QUESTIONS

WEB SERVICES INTERVIEW QUESTIONS


Asp Net Web Services: Here are some web services interview questions which is very helpful in interviews. This great listing of interview questions provides a lot of information on Web Services Questions and Web Services Faqs. Not at all, instead of web services faqs and interview questions you can also learn how to use web services in asp net. If you need more web services faqs used in asp net you can also contact us for more info.


Question: Can you define basic element of WebServices and explain any one from them?
Answer: These are as follows SOAP, WSDL and UDDI. And I am explaining about the SOAP(Simple Object Access Protocol) it is a communication protocol it is for communication between application it is platform and language independent.It is based on XML and also help to get from Firwall.

Question: Explain functioning of Web Services Protocols ?
Answer: Http-Get:- This is standard protocol that helps client to communicate with server with HTTP.When client send a request to server via HTTP request and reuired parameter are attached with the querystring.Example:-
http://www.dotnetquestion.info/dotnet/interview.aspx?id=pervej&cast=munjal and we get the value from querystring.
Request.querystring("id")
Request.querystring("cast").

Http-Post:-This is same as Http-Get but the diffrence is that in place of sending parameters onto the URL information is send with HTTP request message with some extra information which contains Parameters and their values.This Protocols is limited to sending name/value pairs.

SOAP:-The only diffrence is that its relies on the XML as compares to Http-Get,Http-Post.SOAP can send not only the name/value pairs but also some complex object also as for example datatypes,class,objects.SOAP can also uses request/reponse model as Http-Get,Http-post but it is not limited to Request/Response it can also send types of message.Because its uses XML that is pure text so firewalls not created so much problem because its easily converted in to HTML. .

Question: How .NET and non .NET component communicate with each other when they are on different platform?
Answer:
In past when we have to communicate .NET with non .NET component we are using COM component this component helps in doing this. At the moment we are using in both apps a COM component that has an intermediary Windows service running on one machine. But this component is quite old and not in use now because it will create a problem when we are using firewall. So to handle this we use Web-Services which really have a solution for Firewall.

Question: Why do some web service classes derive from System.Web.WebServices while others do not ?
Answer: Those asp net Web Service classes which employ objects like Application, Session, Context, Server, and User have to derive from System.Web.WebServices. If it does not use these objects, it is not necessary to be derived from it.

Question: What is WSDL ?
Answer: WSDL is an XML format for describing network services as a set of endpoints operating on messages containing either document-oriented or procedure-oriented information. The operations and messages are described abstractly, and then bound to a concrete network protocol and message format to define an endpoint. Related concrete endpoints are combined into abstract endpoints (services). (Source: www.w3.org).

Question: What is the standard you use to wrap up a call to a Web service ?
Answer: HTTP with SOAP.

Question: What is Asp Net Web Services ?
Answer: Web services are programmable business logic components that provide access to functionality through the Internet. Standard protocols like HTTP can be used to access them. Web services are based on the Simple Object Access Protocol (SOAP), which is an application of XML. Web services are given the .asmx extension..

Question: Define Protocols that helps Web Services in Asp Net?
Answer: From my point of view Web Services used three protocols for interacting with the clients.Http-Post,Http-Get,SOAP.

Question: What are VSDISCO files ?
Answer:
VSDISCO files are DISCO files that enable dynamic discovery of Web Services. ASP.NET links the VSDISCO to a HTTP handler that scans the host directory and subdirectories for ASMX and DISCO files and returns a dynamically generated DISCO document. A client who requests a VSDISCO file gets back what appears to be a static DISCO document.

Question: What is UDDI ?
Answer:
UDDI stands for Universal Description, Discovery, and Integration. It is like an "Yellow Pages" for Web Services. It is maintained by Microsoft, IBM, and Ariba, and is designed to provide detailed information regarding registered Web Services for all vendors. The UDDI can be queried for specific Web Services.

Question: Is it possible to generate the source code for an ASP.NET Web service from a WSDL ?
Answer:
The Wsdl.exe tool (.NET Framework SDK) can be used to generate source code for an ASP.NET web service with its WSDL link.
Example: wsdl /server http://api.google.com/GoogleSearch.wsdl.



Question: Can you give an example of when it would be appropriate to use a web service as opposed to a non-serviced .NET component ?
Answer:
When to Use Asp Net Web Services:
(i)Communicating through a Firewall When building a distributed application with 100s/1000s of users spread over multiple locations, there is always the problem of communicating between client and server because of firewalls and proxy servers. Exposing your middle tier components as Web Services and invoking the directly from a Windows UI is a very valid option.

(ii)Application Integration When integrating applications written in various languages and running on disparate systems. Or even applications running on the same platform that have been written by separate vendors.

(iii)Business-to-Business Integration This is an enabler for B2B intergtation which allows one to expose vital business processes to authorized supplier and customers. An example would be exposing electronic ordering and invoicing, allowing customers to send you purchase orders and suppliers to send you invoices electronically.

(iv)Software Reuse This takes place at multiple levels. Code Reuse at the Source code level or binary componet-based resuse. The limiting factor here is that you can reuse the code but not the data behind it. Webservice overcome this limitation. A scenario could be when you are building an app that aggregates the functionality of serveral other Applications. Each of these functions could be performed by individual apps, but there is value in perhaps combining the the multiple apps to present a unifiend view in a Portal or Intranet.

Question: What are Service Oriented Architectures (SOA) ?
Answer:
SOA describes an information technology architecture that enables distributed computing environments with many different types of computing platforms and applications. Web services in asp net are one of the technologies that help make SOAs possible. As a concept, SOA has been around since the 1980s, but many early IT technologies failed to achieve the goal of linking different types of applications and systems. By making early investments with .NET, Microsoft has helped provide the building blocks that today are putting many enterprise customers on the path to successfully implementing SOAs. With SOAs, companies can benefit from the unimpeded flow of information that is the hallmark of connected systems.

Question: What is .NET Passport?
Answer:
.NET Passport is a Web-based service that is designed to make signing in to Web sites fast and easy. Passport enables participating sites to authenticate a user with a single set of sign-in credentials, alleviating the need for users to remember numerous passwords and user names

.NET Interview Questions

.NET Interview Questions

Explain the .NET architecture.

How many languages .NET is supporting now? - When .NET was introduced it came with several languages. VB.NET, C#, COBOL and Perl, etc. The site DotNetLanguages.Net says 44 languages are supported.

How is .NET able to support multiple languages? - a language should comply with the Common Language Runtime standard to become a .NET language. In .NET, code is compiled to Microsoft Intermediate Language (MSIL for short). This is called as Managed Code. This Managed code is run in .NET environment. So after compilation to this IL the language is not a barrier. A code can call or use a function written in another language.

How ASP .NET different from ASP? - Scripting is separated from the HTML, Code is compiled as a DLL, these DLLs can be executed on the server.

Resource Files: How to use the resource files, how to know which language to use?

What is smart navigation? - The cursor position is maintained when the page gets refreshed due to the server side validation and the page gets refreshed.

What is view state? - The web is stateless. But in ASP.NET, the state of a page is maintained in the in the page itself automatically. How? The values are encrypted and saved in hidden controls. this is done automatically by the ASP.NET. This can be switched off / on for a single control

How do you validate the controls in an ASP .NET page?

- Using special validation controls that are meant for this. We have Range Validator, Email Validator.

Can the validation be done in the server side? Or this can be done only in the Client side? - Client side is done by default. Server side validation is also possible. We can switch off the client side and server side can be done.

How to manage pagination in a page? - Using pagination option in DataGrid control. We have to set the number of records for a page, then it takes care of pagination by itself.

What is ADO .NET and what is difference between ADO and ADO.NET? - ADO.NET is stateless mechanism. I can treat the ADO.Net as a separate in-memory database where in I can use relationships between the tables and select insert and updates to the database. I can update the actual database as a batch.

Interview questions for Web application developers

Is it possible to inline assembly or IL in C# code? - No.

Is it possible to have a static indexer in C#? - No. Static indexers are not allowed in C#.

If I return out of a try/finally in C#, does the code in the finally-clause run? - Yes. The code in the finally always runs. If you return out of the try block, or even if you do a “goto” out of the try, the finally block always runs:

Using System; 
         
class main
{
         public static void Main()
               {
                               try
                               {
                                              Console.WriteLine(\"In Try block\");
                                              return;
                               }
                               finally
                               {
                                              Console.WriteLine(\"In Finally block\");
                               }
               }
} 

Both “In Try block” and “In Finally block” will be displayed. Whether the return is in the try block or after the try-finally block, performance is not affected either way. The compiler treats it as if the return were outside the try block anyway. If it’s a return without an expression (as it is above), the IL emitted is identical whether the return is inside or outside of the try. If the return has an expression, there’s an extra store/load of the value of the expression (since it has to be computed within the try block).

I was trying to use an “out int” parameter in one of my functions. How should I declare the variable that I am passing to it? - You should declare the variable as an int, but when you pass it in you must specify it as ‘out’, like the following: int i; foo(out i); where foo is declared as follows: [return-type] foo(out int o) { }

How do you specify a custom attribute for the entire assembly (rather than for a class)? - Global attributes must appear after any top-level using clauses and before the first type or namespace declarations. An example of this is as follows:

using System;
[assembly : MyAttributeClass] class X {}

Note that in an IDE-created project, by convention, these attributes are placed in AssemblyInfo.cs.

How do you mark a method obsolete? -

[Obsolete] public int Foo() {...}

or

[Obsolete(\"This is a message describing why this method is obsolete\")] public int Foo() {...}

Note: The O in Obsolete is always capitalized.

How do you directly call a native function exported from a DLL? - Here’s a quick example of the DllImport attribute in action:

using System.Runtime.InteropServices; \
class C
{
               [DllImport(\"user32.dll\")]
               public static extern int MessageBoxA(int h, string m, string c, int type);
               public static int Main()
               {
                               return MessageBoxA(0, \"Hello World!\", \"Caption\", 0);
               }
}

This example shows the minimum requirements for declaring a C# method that is implemented in a native DLL. The method C.MessageBoxA() is declared with the static and external modifiers, and has the DllImport attribute, which tells the compiler that the implementation comes from the user32.dll, using the default name of MessageBoxA. For more information, look at the Platform Invoke tutorial in the documentation.

How do I simulate optional parameters to COM calls? - You must use the Missing class and pass Missing.Value (in System.Reflection) for any values that have optional parameters.

C# developer interview questions

A representative of a high-tech company in United Kingdom sent this in today noting that the list was used for interviewing a C# .NET developer. Any corrections and suggestions would be forwarded to the author. I won’t disclose the name of the company, since as far as I know they might still be using this test for prospective employees. Correct answers are in green color.

1) The C# keyword .int. maps to which .NET type?

1. System.Int16

2. System.Int32

3. System.Int64

4. System.Int128

2) Which of these string definitions will prevent escaping on backslashes in C#?

1. string s = #.n Test string.;

2. string s = ..n Test string.;

3. string s = @.n Test string.;

4. string s = .n Test string.;

3) Which of these statements correctly declares a two-dimensional array in C#?

1. int[,] myArray;

2. int[][] myArray;

3. int[2] myArray;

4. System.Array[2] myArray;

4) If a method is marked as protected internal who can access it?

1. Classes that are both in the same assembly and derived from the declaring class.

2. Only methods that are in the same class as the method in question.

3. Internal methods can be only be called using reflection.

4. Classes within the same assembly, and classes derived from the declaring class.

5) What is boxing?

a) Encapsulating an object in a value type.

b) Encapsulating a copy of an object in a value type.

c) Encapsulating a value type in an object.

d) Encapsulating a copy of a value type in an object.

6) What compiler switch creates an xml file from the xml comments in the files in an assembly?

1. /text

2. /doc

3. /xml

4. /help

7) What is a satellite Assembly?

1. A peripheral assembly designed to monitor permissions requests from an application.

2. Any DLL file used by an EXE file.

3. An assembly containing localized resources for another assembly.

4. An assembly designed to alter the appearance or .skin. of an application.

8) What is a delegate?

1. A strongly typed function pointer.

2. A light weight thread or process that can call a single method.

3. A reference to an object in a different process.

4. An inter-process message channel.

9) How does assembly versioning in .NET prevent DLL Hell?

1. The runtime checks to see that only one version of an assembly is on the machine at any one time.

2. .NET allows assemblies to specify the name AND the version of any assemblies they need to run.

3. The compiler offers compile time checking for backward compatibility.

4. It doesn.t.

11) In the NUnit test framework, which attribute must adorn a test class in order for it to be picked up by the NUnit GUI?

1. TestAttribute

2. TestClassAttribute

3. TestFixtureAttribute

4. NUnitTestClassAttribute

12) Which of the following operations can you NOT perform on an ADO.NET DataSet?

1. A DataSet can be synchronised with the database.

2. A DataSet can be synchronised with a RecordSet.

3. A DataSet can be converted to XML.

4. You can infer the schema from a DataSet.

13) In Object Oriented Programming, how would you describe encapsulation?

1. The conversion of one type of object to another.

2. The runtime resolution of method calls.

3. The exposition of data.

4. The separation of interface and implementation.

.NET deployment questions

What do you know about .NET assemblies? Assemblies are the smallest units of versioning and deployment in the .NET application. Assemblies are also the building blocks for programs such as Web services, Windows services, serviced components, and .NET remoting applications.

What’s the difference between private and shared assembly? Private assembly is used inside an application only and does not have to be identified by a strong name. Shared assembly can be used by multiple applications and has to have a strong name.

What’s a strong name? A strong name includes the name of the assembly, version number, culture identity, and a public key token.

How can you tell the application to look for assemblies at the locations other than its own install? Use the
directive in the XML .config file for a given application.

should do the trick. Or you can add additional search paths in the Properties box of the deployed application.

How can you debug failed assembly binds? Use the Assembly Binding Log Viewer (fuslogvw.exe) to find out the paths searched.

Where are shared assemblies stored? Global assembly cache.

How can you create a strong name for a .NET assembly? With the help of Strong Name tool (sn.exe).

Where’s global assembly cache located on the system? Usually C:\winnt\assembly or C:\windows\assembly.

Can you have two files with the same file name in GAC? Yes, remember that GAC is a very special folder, and while normally you would not be able to place two files with the same name into a Windows folder, GAC differentiates by version number as well, so it’s possible for MyApp.dll and MyApp.dll to co-exist in GAC if the first one is version 1.0.0.0 and the second one is 1.1.0.0.

So let’s say I have an application that uses MyApp.dll assembly, version 1.0.0.0. There is a security bug in that assembly, and I publish the patch, issuing it under name MyApp.dll 1.1.0.0. How do I tell the client applications that are already installed to start using this new MyApp.dll? Use publisher policy. To configure a publisher policy, use the publisher policy configuration file, which uses a format similar app .config file. But unlike the app .config file, a publisher policy file needs to be compiled into an assembly and placed in the GAC.

What is delay signing? Delay signing allows you to place a shared assembly in the GAC by signing the assembly with just the public key. This allows the assembly to be signed with the private key at a later stage, when the development process is complete and the component or assembly is ready to be deployed. This process enables developers to work with shared assemblies as if they were strongly named, and it secures the private key of the signature from being accessed at different stages of development.