.Net General

By venkatesh2urs

The .NET world according to Microsoft
When it comes to Web services, there are essentially two world-views: Microsoft’s and everyone else’s. Microsoft’s world-view, of course, is called .NET and while most people have heard of it, its exact outlines are often fuzzy — so fuzzy, in fact, that a TechTarget survey found that under 10% of respondents even understand what .NET is. (Click here for more information about the survey.)

To bring .NET into focus, this week I’ll start a two-part series about the architecture. This column takes a look at .NET’s basic building blocks, while the next one will look at some of the architecture’s more controversial aspects, including its Passport technology and new TrustBridge technology.

A look at the basics
For a start, .NET is not a drastic departure from Web services — it’s simply Microsoft’s version of the technology. So the roles of UDDI, XML, SOAP, and other basic protocols are essentially no different in the Microsoft view of the world than in the rest of the Web services world.

How those services are used and built, though, differs in .NET from the rest of the world. And there’s the rub. In theory, when you build a Web service, you should be able to pick and choose among technologies and vendors, assembling a “best-of-breed” suite of development platforms, servers, security and other tools in order to deliver your service. With .NET that’s not really the case: In essence, Microsoft offers a soup-to-nuts approach with .NET, in which every part of the process, and every piece of hardware and software comes from Microsoft and is based on Windows. In fact, cynical observers might believe that Microsoft’s head-first jump into Web services via .NET is nothing more than an attempt to shore up Windows in the face of a Web services architecture in which protocols like SOAP, UDDI, and XML could conceivably make an underlying operating system irrelevant.

Whether you believe that, or whether you instead believe that .NET is Microsoft’s coherent strategy for making it easier for developers and users to achieve a kind of universal connectivity, you need to know about the core of .NET. So here is the current lineup of what .NET is and how it works, according to Microsoft.

The building blocks of .NET
In the Microsoft vision, there are four primary building blocks of .NET:

1) Developer tools, including Microsoft Visual Studio .NET and the Microsoft .NET Framework;

2) Servers, including .NET Enterprise Servers and the .NET Server Family;

3) XML-based Web services, which are the applications themselves, such as the Microsoft MapPoint .NET, a modular Web service that can be integrated into other applications and Web sites; and

4) Smart clients, which are the devices that run the Web services, and can be anything from a PC to a PocketPC, to the Xbox gaming console. Not surprisingly, they all run some version of Windows.
In the rest of this column, we’ll take a closer look at each.

Developer tools The centerpiece of Microsoft’s developer tools is Visual Studio .NET, which allows developers to use a variety of languages including Microsoft’s Visual Basic .NET, C++ .NET, and Visual C# .NET to build .NET services. Notably missing from the lineup, of course, is Java — no surprise, since Microsoft has all but abandoned its support for Java. Java developers who do want to develop for .NET can use Visual J# .NET, the beta of which has just been released. (Note: For more information about Visual Studio, head to http://msdn.microsoft.com/vstudio/, and for information about Visual J# .Net, go to http://msdn.microsoft.com/vjsharp/.) Also part of the tools is the .NET Framework, required to build and run Web services. [Editor's Note: For more .NET resources, be sure to also visit the SearchVB .NET Info Center.]

Servers Microsoft has several server product lines that support .NET: Windows 2000 Servers and .NET Enterprise Servers, and the upcoming Windows .NET Server Family. In essence, the Windows 2000 Servers and .NET Enterprise Servers are nothing new, and to a certain extent merely extend existing server software, with an eye toward supporting .NET and XML. Of them, the Microsoft BizTalk Server 2000, which serves XML-based business processes, is particularly relevant, but to one degree or another, most of Microsoft’s server line supports NET. The Windows .NET Server family, on the other hand, was designed specifically for .NET and so will greater . NET support. It’s currently in beta 3, includes the .NET Framework built into it, and integrates with other .NET technologies such as Microsoft Passport.

XML-based Web services These, of course, are the Web service applications themselves. After an initial flurry of announcements indicating that Microsoft was going full-bore into developing consumer-level .NET services such as stock alerts and similar services, it’s now unclear where it plans to go with developing .NET services itself. One of few functioning Web services is the MapPoint .NET service — a useful if run-of-the-mill service that lets you find maps and driving directions, and that, for a price, can be integrated into a Web site using .NET.

Smart clients In the Microsoft world-view, Windows will run on everything from cell phones to PDAs to gaming consoles, to kiosks — in fact, anything that has any intelligence built into it. And the plan is that those “smart client” devices will be .NET capable. In the long run, the most interesting of these devices won’t be computers — it may be your refrigerator, toaster or car. Microsoft is pushing Windows XP Embedded, a “componentized” version of the operating system designed to run on any kind of intelligent device. So .NET services could connect all of your home appliances into larger networks of retail stores, automobiles, gaming consoles and more…think of it as .NET everywhere.

 

What is Microsoft .NET?

Microsoft .NET is the Microsoft strategy for connecting systems, information, and devices through Web services so people can collaborate and communicate more effectively. .NET technology is integrated throughout Microsoft products, providing the capability to quickly build, deploy, manage, and use connected, security-enhanced solutions through the use of Web services.

What are Web Services?

Web services are small, reusable applications that help computers from many different operating system platforms work together by exchanging messages. Web services are based on industry protocols that include XML (Extensible Markup Language), SOAP (Simple Object Access Protocol), and WSDL (Web Services Description Language). These protocols help computers work together across platforms and programming languages.

From a business perspective, Web services are used to reenable information technology so that it can change, move, and adapt like other aspects of a business. They not only connect systems, they can help connect people with the information they need, within the software applications they are used to using, and wherever they happen to be.

Microsoft offers a complete range of software that helps organizations and individuals benefit from Web service-based connectivity. These include theMicrosoft Visual Studio .NET 2003 developer tools, the Windows Server System that hosts Web services, and familiar desktop applications such as the Microsoft Office System that “consume” Web services.

This illustration shows the relationship between the core technology components of .NET.

What are the Benefits of .NET?

.NET technologies use Web services to help enhance the computing experience with highly integrated communications and information. Because .NET includes the core technologies for building Web services, it benefits everyone: individual users, organizations, and developers.

.NET benefits organizations by helping them get the most out of their existing technology investments while creating new ways to implement powerful, cost-effective information technology that will meet future needs. .NET technologies and Web services can be used to integrate even the most disparate computing environments. .NET frees organizations from the confines of proprietary technology, providing the flexibility and scalability that can help organizations connect their existing IT systems and build a foundation for the next wave of computer technology. .NET and Web services can help organizations lower operating costs by helping connect systems; increase sales by helping employees access the right information when and where they need it; integrate services and applications with customers and partners; and lower the costs of information technology with tools that help developers quickly create new solutions to address business issues.

.NET benefits individuals by helping provide a more personal and integrated computing experience. .NET-enabled computing is centered on the user–not on the features of the software or hardware. The user’s experience becomes very customizable and provides integrated data and customized interactions that work well with a wide range of computing hardware, such as Pocket PCs, Smartphones, laptops, and other devices. The .NET-based experience enhances the mobile computing experience so user’s can get their information regardless of their location. For example, it can take place on a desktop computer, in the car on a Smartphone, or at the store on a Pocket PC.

.NET benefits developers by providing a tightly integrated set of tools for building and integrating Web services. Visual Studio .NET and the .NET Framework provide comprehensive development platforms that offer the best, fastest, and most cost-effective way to build Web services. With Visual Studio .NET and the .NET Framework, developers can take advantage of a programming model designed from the ground up for creating Web services in a highly productive, multilanguage environment. With scalable, high-performance execution, the .NET tools allow developers to use existing skills to create a wide range of solutions that work across a broad array of computing devices. .NET also provides a foundation for building Service Oriented Architectures (SOA).

What are Service Oriented Architectures (SOA)?

SOA describes an information technology architecture that enables distributed computing environments with many different types of computing platforms and applications. Web services 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.

What are Web Services Enhancements for Microsoft .NET (WSE)?

WSE is an add-on to Microsoft Visual Studio .NET and the Microsoft .NET Framework that helps developers build greater security features into Web services using the latest Web services protocol specifications and standards. With WSE 2.0 developers can create security-enhanced connected systems that help improve business processes within–and beyond–corporate trust boundaries and create new revenue-generating opportunities.

What is a Smart Client?

Smart clients are client applications that consume Web services and reside on user hardware such as desktop PCs, laptops, Pocket PCs, and Smartphones. They are easily deployed and managed and provide an adaptive, responsive, and rich interactive experience by taking advantage of the computing resources on the device and intelligently connecting to distributed data sources.

What is .NET Passport?

.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.

What are the Current Microsoft Products and Technologies That Use .NET?

Microsoft .NET provides everything that is needed to develop and deploy a Web service-based IT architecture: servers to host Web services; development tools to create Web services; applications to use them; and a network of more than 35,000 Microsoft partners to help organizations deploy and manage them. .NET technologies are supported throughout the family of Microsoft products, including the Windows Server System, the Windows XP desktop operating system, and the Microsoft Office System. And .NET technologies will play an even larger role in future versions of Microsoft products.

Who is Using .NET?

Organizations worldwide are implementing .NET technologies and Web services to create connected businesses and to help individuals communicate and collaborate more effectively. For example, Honeywell, GlaxoSmithKline, Sony, Dollar Rent A Car, Farmers Insurance, and the United States Postal Service are just a few of the well-known names that are using .NET. To read more about .NET technology in use today, visit the Microsoft .NET Case Study site.

How Do I Find a Microsoft Partner to Help Me Connect My Organization Using .NET?

Microsoft Certified Partners are independent companies that can provide you with the highest levels of technical expertise, strategic thinking, and hands-on skills. Microsoft Certified Partners encompass a broad range of expertise and vendor affiliations. Their real-world perspective can help you prioritize and effectively deliver your technology solutions. Find a partner in your area, here.

 

ASP.NET is a technology for building powerful, dynamic Web applications. It is part of the .NET Framework.

Developer Productivity

ASP.NET helps you deliver real world Web applications in record time.

Easy Programming Model ASP.NET makes building real world Web applications dramatically easier. ASP.NET server controls enable an HTML-like style of declarative programming that lets you build great pages with far less code than with classic ASP or technologies like PHP or JSP. Best of all, ASP.NET pages work in all browsers – including Firefox, Opera, Safari, and Internet Explorer.

Great Tool Support A broad range of tools support development with ASP.NET. You can work with a simple text editor (even Notepad), take advantage of the freely available Visual Web Developer 2005 Express Edition, or work with a full-powered integrated development environment, such as Visual Studio 2005. For enterprise developers, Visual Studio Team System 2005 includes additional tools for stress-testing and designing Web applications.

Starter Kits Not sure how to get started building an ASP.NET Web site? Download one of the ASP.NET Starter Kits – ready-built Web sites using best practices to help you see how a site should be created. Starter Kits for personal, club, portal and e-commerce Web sites are already available, and both Microsoft and third parties are making many more available.

Easy to get started Quickly get up to speed programming with ASP.NET by following along with the QuickStart tutorials. Read a guided tour of Visual Web Developer to become familiar with its features. Access the broad and growing community support for ASP.NET.

Improved Design

ASP.NET helps you create appealing, functional Web applications.

Master Pages ASP.NET makes it easy to create and apply a common look-and-feel to your Web site with Master Pages. Change the Master Page, and all pages automatically update to reflect those changes.

Themes Give your Web pages a consistent appearance with the built-in theming support in ASP.NET. Easily organize and apply changes to stylesheets and controls by applying a new theme to your pages.

Built Upon Standards

ASP.NET helps you create pages compliant with international standards.

XHTML Compliance Creating XHTML-compliant pages is easy with ASP.NET. Web controls support rendering valid, well-formed XHTML markup with a simple configuration option.

Accessibility Support Create Web applications usable by the widest possible audience support for building and testing accessible Web applications.
Improved Security

ASP.NET helps you protect your data and users.

Application Services There is no need to write common code for managing users and personalization with ASP.NET, as these features are included as application services. ASP.NET membership services provide best practices guidance and support for managing access to your Web applications.

Built-in Protection ASP.NET provides built-in protection from many common forms of hacker attacks, including cross-site scripting, request-replay attacks and more.

Improved Performance and Scalability

ASP.NET lets you use serve more users with the same hardware.

Caching Caching can dramatically improve the performance of Web applications, and ASP.NET supports many forms of caching. Output caching improves the rendering of controls to XHTML. Database caching enables the application to be notified when the underlying database changes, eliminating unnecessary queries.

Web-Farm Session State ASP.NET session state lets you share session data user-specific state values across all machines in your Web farm. Now a user can hit different servers in the web farm over multiple requests and still have full access to her session.

Extensible Architecture

ASP.NET can grow and change with your needs.

Provider Model The application services of ASP.NET use the provider model to connect to external services for storage and more. This enables the developer to change the database or other service used to store the membership, personalization or site map information by editing the configuration.

Web Parts Easily build portal applications with the built-in Web part functionality. Create Web applications that enable end users to organize and personalize their page content and layout.

 

Creating Professional Reports using Crystal Report for Visual Studio.NET (Part 2)

In the previous part we saw how the Report Expert wizard just dumps all the items of the report into the predefined sections in an order irrespective of the exact requirement. Now, it is up to us to move these items around and place it in a particular order to get the desired result. This is the tricky part of the whole report creation.

The next obvious step would seem like moving the items to its appropriate Group, but this is where the trouble starts. If you do this and view the report in a browser, you would notice all the Group Names being repeated. As you drill down each time, you would notice an extra row at the bottom of the report which is the parent Group Name, and you get to see all the details together, only after you have drilled down to the last section.

Before we proceed, it would help to get an understanding of the various sections that have been created and where each of the items has been placed. The current layout is as shown below:

To get the desired result, the trick here is to use a higher level Header section to display the headings and a lower level Footer section to display the actual values. For example, placing the headings related to the Store in the Report Header and placing its corresponding values in the Group 1 Footer will generate a report which will display the Store heading only once but will repeat the corresponding values depending on the number of records in the database.

We will also have to move the Book details and Order details to the lower sections and format it in such a way that it can be viewed only by drilling down to it.

Your Crystal Report Designer screen should now look similar to the image shown below. Incase, your report contains an extra Group 1 Header called ‘Group Header #1 b’, you could leave it alone as it would not make any difference to the final report.

The following tips explains how-to achieve certain tasks while converting from the old layout to the new layout.

- Insert a new chart into the Group 1 Header to represent the Book Titles.

Right click within the Group 1 Header area, select Insert and then select Chart.

From the pop-up window, select Bar graph from the Type tab, and set the Placement option on the Data tab to For each Stores.stor_name so that the chart is plotted depending on the Store.

- Hide Group 1 Header initially, to allow viewing the details only thru Drill down

Right click on the Group 1 Header Panel, select Hide (Drill Down OK)

- Suppress the Group 2 Header

Right click on the Group 2 Header Panel and select Suppress (No Drill Down).

Those sections that are either suppressed (permanently) or hidden (for drill down) will be shaded and hence can be distinguished from the normal sections easily. (It would have really helped if there was also a way to differentiate between the suppressed and hidden section, which does not seem to exist)

- Insert a new Detail Section (Details b).

Right click on the Detail Section and select Insert Section Below

- Insert an additional heading (for Quantity)

Right click within the particular Group, and select Text Object, place it at the required position, double click on it and type in a title.

- Create a formula

You must have noticed that the Publication Date and the Order Date displays the Date & Time currently and it needs to be formatted for date only. This can be achieved using a formula field.

Right click on the Formula Fields option under the Field Explorer window, and select New.

Give your formula a name and this opens up the Formula Editor window where you can type in the actual date conversion formula. Note that the image shows the code required to extract the date alone from the PublicationDate Field.

Now replace the original PublicationDate field on the report with this formula field.

Now view the report in a browser and you will notice that the report is getting real close to what we saw initially (at least functionality wise).

One thing that still hasn’t been fixed is that, each time you drill down into the details, one dangling parent record gets displayed at the bottom of the report. This is where conditional formatting comes to the rescue, which will be covered in the last part of this Walkthrough.

 

 

1.How many languages .NET is supporting now?

Ans :When .NET was introduced it came with several languages. VB.NET, C#, COBOL and Perl, etc. The site DotNet Languages. Net says 44 languages are supported..

2.How is .NET able to support multiple languages?

Ans :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..

3.How ASP .NET different from ASP?

Ans :Scripting is separated from the HTML, Code is compiled as a DLL, and these DLLs can be executed on the server.

4.What is smart navigation?

Ans :The cursor position is maintained when the page gets refreshed due to the server side validation and the page gets refreshed.

5.What is view state?

Ans :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.

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

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

7.Can the validation be done in the server side? Or this can be done only in the Client side?

Ans :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..

8.How to manage pagination in a page?

Ans :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..

9.What is ADO .NET and what is difference between ADO and ADO.NET?

Ans :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..

10.Describe the role of inetinfo.exe, aspnet_isapi.dll andaspnet_wp.exe
in the page loading process.

Ans :inetinfo.exe is theMicrosoft IIS server running, handling ASP.NET requests among other things.When an ASP.NET request is received (usually a file with .aspx extension),the ISAPI filter aspnet_isapi.dll takes care of it by passing the request tothe actual worker process aspnet_wp.exe..

11.What?s the difference between Response.Write() and Response.Output.Write()?

Ans :The latter one allows you to write formatted output..

12.What methods are fired during the page load?

Ans :Init() – when the pageis instantiated, Load() – when the page is loaded into server memory,PreRender() – the brief moment before the page is displayed to the user asHTML, Unload() – when page finishes loading..

13.Where does the Web page belong in the .NET Framework class hierarchy?
Ans :System.Web.UI.Page .

14.Where do you store the information about the user?s locale?

Ans :System.Web.UI.Page.Culture .

15.What?s the difference between Codebehind=”MyCode.aspx.cs” andsrc=”MyCode.aspx.cs”?

Ans :CodeBehind is relevant to Visual Studio.NET only.

16.What?s a bubbled event?

Ans :When you have a complex control, like DataGrid, writing an event processing routine for each object (cell, button, row, etc.) is quite tedious. The controls can bubble up their eventhandlers, allowing the main Data Grid event handler to take care of its constituents..

17.Suppose you want a certain ASP.NET function executed on MouseOver over a
certain button. Where do you add an event handler?

Ans :It?s the Attributesproperty, the Add function inside that property. So
btnSubmit.Attributes.Add(“onMouseOver”,”someClientCode();”) A simple?Javascript:ClientCode();? in the button control of the .aspx page will attach the handler (javascript function)to the onmouseover event..

18.What data type does the RangeValidator control support?

Ans :Integer,String and Date..

19.Where would you use an iHTTPModule, and what are the limitations of any
approach you might take in implementing one?

Ans :One of ASP.NET?s most useful features is the extensibility of the HTTP pipeline, the path that data takes between client and server. You can use them to extend your ASP.NET applications by adding pre- and post-processing to each HTTP request coming into your application. For example, if you wanted custom authentication facilities for your application, the best technique would be to intercept the request when it comes in and process the request in a custom HTTP module..

20.Explain what a diffgram is and a good use for one?

Ans :A DiffGram is an XML format that is used to identify current and original versions of data elements. The DataSet uses the DiffGram format to load and persist its contents, and to serialize its contents for transport across a network connection. When a DataSet is written as a DiffGram, it populates the DiffGram with all the necessary information to accurately recreate the contents, though not the schema, of the DataSet, including column values from both the Original and Current row versions, row error information, and row order..

What is the difference between Server.Transfer and Response.Redirect? Why would I choose one over the other?
Server.Transfer transfers page processing from one page directly to the next page without making a round-trip back to the client’s browser. This provides a faster response with a little less overhead on the server. Server.Transfer does not update the clients url history list or current url. Response.Redirect is used to redirect the user’s browser to another page or site. This performas a trip back to the client where the client’s browser is redirected to the new page. The user’s browser history list is updated to reflect the new address.

Can you explain the difference between an ADO.NET Dataset and an ADO Recordset?
Valid answers are:
· A DataSet can represent an entire relational database in memory, complete with tables, relations, and views.
· A DataSet is designed to work without any continuing connection to the original data source.
· Data in a DataSet is bulk-loaded, rather than being loaded on demand.
· There’s no concept of cursor types in a DataSet.
· DataSets have no current record pointer You can use For Each loops to move through the data.
· You can store many edits in a DataSet, and write them to the original data source in a single operation.
· Though the Dataset is universal, other objects in ADO.NET come in different versions for different data sources.

What is the Global.asax used for?
The Global.asax (including the Global.asax.cs file) is used to implement application and session level events.

What are the Application_Start and Session_Start subroutines used for?
This is where you can set the specific variables for the Application and Session objects.


Can you explain what inheritance is and an example of when you might use it?

When you want to inherit (use the functionality of) another class. Example: With a base class named Employee, a Manager class could be derived from the Employee base class.

Whats an assembly?
Assemblies are the building blocks of the .NET framework. Overview of assemblies from MSDN

Describe the difference between inline and code behind.
Inline code written along side the html in a page. Code-behind is code written in a separate file and referenced by the .aspx page.

Explain what a diffgram is, and a good use for one?

The DiffGram is one of the two XML formats that you can use to render DataSet object contents to XML. A good use is reading database data to an XML file to be sent to a Web Service.

Whats MSIL, and why should my developers need an appreciation of it if at all?
MSIL is the Microsoft Intermediate Language. All .NET compatible languages will get converted to MSIL. MSIL also allows the .NET Framework to JIT compile the assembly on the installed computer.

Which method do you invoke on the DataAdapter control to load your generated dataset with data?

The Fill() method.

Can you edit data in the Repeater control?
No, it just reads the information from its data source.

Which template must you provide, in order to display data in a Repeater control?
ItemTemplate.

How can you provide an alternating color scheme in a Repeater control?
Use the AlternatingItemTemplate.

What property must you set, and what method must you call in your code, in order to bind the data from a data source to the Repeater control?
You must set the DataSource property and call the DataBind method.

What base class do all Web Forms inherit from?
The Page class.

Name two properties common in every validation control?
ControlToValidate property and Text property.

Which property on a Combo Box do you set with a column name, prior to setting the DataSource, to display data in the combo box?
DataTextField property.

Which control would you use if you needed to make sure the values in two different controls matched?
CompareValidator control.

How many classes can a single .NET DLL contain?
It can contain many classes.

 

 

Tricks:

This is a BoF session where attendees and presenters (from Canada, yay) share neat little things (some known, some obscure) about working in VS.NET.
Creating a class that implements an interface, pressing Tab after the interface name will create stubs for the methods of the interface
Ctrl+] jumps to the next end block.
Ctrl+Shift+] selects the block.
Ctrl+Shift+I enters incremental search.
Ctrl+Space (sometimes Ctrl+J, depending on the language) enters IntelliSense.
In command window you can create aliases (alias command) to access all menu entries
In command window, immed enters immediate mode.
Change Dockable from the context menu of the Output window to put it into the source panes.
Select New Horizontal/Vertical Tab to split the source window to view two or more files at once.
Ctrl+Tab navigates through open source windows (Ctrl+Shift+Tab navigates backwards)
Clicking Mark All in the Find dialog will create a bookmark for each entry found.
Alt+Drag selects arbitrary blocks of text.
Entering a TODO comment (// TODO: do something) will insert the comment in the task list. You can customize the list of tags that will go in the task list from the Options dialog.
Alt+Shift+Enter toggles the full screen code window.
Toggling Search Hidden Text in the Find dialog will search into the collapsed regions.
In C#, from the Class View, right click on a class and select Add > Property to get a wizard to automatically build a property structure.
When removing a file from a solution, remember to take it out also from the source code manager (Visual SourceSafe or CVS) to avoid having it compiled and built nightly.
Don’t use MDI Smiley
Lots of built-in aliases for the Command Window.
In Solution Explorer, right click the solution, select Properties and toggle Multiple Startup Projects to start both the client and the server (if you have them) applications.
Shift-F7 or Ctrl+PgUp/Ctrl+PgDn toggles between views on your file (Design, Source, HTML, Data, etc…)

 

 

.NET: Retrieving Assembly Attributes

To retrieve the value set in the Assembly Attributes in the AssemblyInfo.cs or AssemblyInfo.vb file, use the code below. The example shows retrieving the AssemblyDescription attribute.

[C#]
private static readonly string strAssemblyDescription =
((AssemblyDescriptionAttribute)
Assembly.GetExecutingAssembly().GetCustomAttributes(
typeof(AssemblyDescriptionAttribute), false)[0]).Description;

[Visual Basic]
Private ReadOnly strAssemblyDescription As String = _
CType([Assembly].GetExecutingAssembly().GetCustomAttributes( _
GetType(AssemblyDescriptionAttribute), False), _
AssemblyDescriptionAttribute())(0).Description

.NET: Getting the Path of the Executing Assembly

To retrieve the path of the executing assembly (the VB 6.0 equivalent of App.Path), use the following code:

[C#]
String strPath = System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().CodeBase);

[Visual Basic]
Dim strPath As String = System.IO.Path.GetDirectoryName( _
System.Reflection.Assembly.GetExecutingAssembly().CodeBase)

.NET: Setting the RootFolder to Other Values in the FolderBrowserDialog in .NET

The Browser Folder Dialog in ASP.NET 1.1 allows you to select a folder. There is a property, RootFolder, that allows you to select what folder is the root in the dialog. The RootFolder property can be set to any of the values in the System.Environment.SpecialFolder enum in the .NET Framework. However, there may be settings that are not in that enumeration that you may want to use. For example, you may want to set the root to be My Network Places.

It turns out that the Browse Folder Dialog is a cover for a Windows API call. The Windows API call takes a parameter that is a constant that indicates what the root should be. For some reason the allowed constants in Windows were not fully implemented in the System.Environment.SpecialFolder enum (for no good reason that I can figure out).

You can’t just set the RootFolder property to the values in the constants provided by Windows. Instead you will have to pull a trick using Reflection to modify the internally stored number in a private variable inside the dialog.

Include the following class in your project:

[c#]

using System;
using System.Reflection;

public sealed class FolderBrowserDialogEx
{
[Flags()]
public enum CsIdl
{
Desktop = 0×0000, // Desktop
Internet = 0×0001, // Internet Explorer (icon on desktop)
Programs = 0×0002, // Start Menu\Programs
Controls = 0×0003, // My Computer\Control Panel
Printers = 0×0004, // My Computer\Printers
Personal = 0×0005, // My Documents
Favorites = 0×0006, // user name\Favorites
Startup = 0×0007, // Start Menu\Programs\Startup
Recent = 0×0008, // user name\Recent
SendTo = 0×0009, // user name\SendTo
BitBucket = 0×000a, // desktop\Recycle Bin
StartMenu = 0×000b, // user name\Start Menu
MyDocuments = 0×000c, // logical “My Documents” desktop icon
MyMusic = 0×000d, // “My Music” folder
MyVideo = 0×000e, // “My Videos” folder
DesktopDirectory = 0×0010, // user name\Desktop
Drives = 0×0011, // My Computer
Network = 0×0012, // Network Neighborhood (My Network Places)
Nethood = 0×0013, // user name\nethood
Fonts = 0×0014, // windows\fonts
Templates = 0×0015,
CommonStartMenu = 0×0016, // All Users\Start Menu
CommonPrograms = 0×0017, // All Users\Start Menu\Programs
CommonStartup = 0×0018, // All Users\Startup
CommonDesktopDirectory = 0×0019, // All Users\Desktop
AppData = 0×001a, // user name\Application Data
PrintHood = 0×001b, // user name\PrintHood
LocalAppData = 0×001c, // user name\Local Settings\Applicaiton Data (non roaming)
AltStartup = 0×001d, // non localized startup
CommonAltStartup = 0×001e, // non localized common startup
CommonFavorites = 0×001f,
InternetCache = 0×0020,
Cookies = 0×0021,
History = 0×0022,
CommonAppdata = 0×0023, // All Users\Application Data
Windows = 0×0024, // GetWindowsDirectory()
System = 0×0025, // GetSystemDirectory()
ProgramFiles = 0×0026, // C:\Program Files
MyPictures = 0×0027, // C:\Program Files\My Pictures
Profile = 0×0028, // USERPROFILE
SystemX86 = 0×0029, // x86 system directory on RISC
ProgramFilesX86 = 0×002a, // x86 C:\Program Files on RISC
ProgramFilesCommon = 0×002b, // C:\Program Files\Common
ProgramFilesCommonx86 = 0×002c, // x86 Program Files\Common on RISC
CommonTemplates = 0×002d, // All Users\Templates
CommonDocuments = 0×002e, // All Users\Documents
CommonAdminTools = 0×002f, // All Users\Start Menu\Programs\Administrative Tools
AdminTools = 0×0030, // user name\Start Menu\Programs\Administrative Tools
Connections = 0×0031, // Network and Dial-up Connections
CommonMusic = 0×0035, // All Users\My Music
CommonPictures = 0×0036, // All Users\My Pictures
CommonVideo = 0×0037, // All Users\My Video
Resources = 0×0038, // Resource Direcotry
ResourcesLocalized = 0×0039, // Localized Resource Direcotry
CommonOemLinks = 0×003a, // Links to All Users OEM specific apps
CdBurnArea = 0×003b, // USERPROFILE\Local Settings\Application Data\Microsoft\CD Burning
ComputersNearMe = 0×003d, // Computers Near Me (computered from Workgroup membership)
FlagCreate = 0×8000, // combine with CSIDL_ value to force folder creation in SHGetFolderPath()
FlagDontVerify = 0×4000, // combine with CSIDL_ value to return an unverified folder path
FlagNoAlias = 0×1000, // combine with CSIDL_ value to insure non-alias versions of the pidl
FlagPerUserInit = 0×0800, // combine with CSIDL_ value to indicate per-user init (eg. upgrade)
FlagMask = 0xFF00, // mask for all possible flag values
}

private FolderBrowserDialogEx()
{
}

public static void SetRootFolder(System.Windows.Forms.FolderBrowserDialog fbd, CsIdl csidl)
{
Type t = fbd.GetType();
FieldInfo fi = t.GetField(“rootFolder”, BindingFlags.Instance | BindingFlags.NonPublic);
fi.SetValue(fbd, (System.Environment.SpecialFolder) csidl);
}
}

To set the FolderRoot property, call it like this:

[c#]

FolderBrowserDialogEx.SetRootFolder(fbd, FolderBrowserDialogEx.CsIdl.Network);

Where fbd is the name of the FolderBrowserDialog on your form, and the second argument is what you want to use as the root of the dialog.

 

.NET: Sizing Columns in a ListView Control in .NET

In a ListView control, with the View property set to Details, you can create a multi-column output. Sometimes you will want the last column of the ListView to size itself to take up all remaining space. You can do this by setting the column width to the magic value -2.

In the following example, the name of the ListView control is lvSample:

[c#]
private void Form1_Load(object sender, System.EventArgs e)
{
SizeLastColumn(lvSample);
}

private void listView1_Resize(object sender, System.EventArgs e)
{
SizeLastColumn((ListView) sender);
}

private void SizeLastColumn(ListView lv)
{
lv.Columns[lv.Columns.Count - 1].Width = -2;
}

[vb]
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
SizeLastColumn(lvSample)
End Sub

Private Sub ListView1_Resize(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles lvSample.Resize
SizeLastColumn(CType(sender, ListView))
End Sub

Private Sub SizeLastColumn(ByVal lv As ListView)
lv.Columns(lv.Columns.Count – 1).Width = -2
End Sub

You can also size a column to its contents. This is especially useful after adding an item to the ListView. For example:

[c#]
lvSample.Items.Add(“foo”);
lvSample.Columns[0].Width = -1;

[vb]
lvSample.Items.Add(“foo”)
lvSample.Columns(0).Width = -1

If the column width is set to -1, the column is sized to the width of the widest item in it. If the value is set to -2, it has a minimum width of the size of the column header, except for the last column, which takes up all remaining space.

.NET: Using Remoting in .NET
While Web Services are getting all the attention in .NET, there are other techniques that it supports that are more efficient for communicating between processes. The advantage of a Web Service is that it is a platform neutral mechanism that uses SOAP as the transport mechanism. However, if you are in control of both sides of the communication between processes, it is more efficient to use Remoting. As an example, I use Remoting as the mechanism for having an ASP.NET page talk to a Windows Service.

The basic idea is that you register a TCP channel on one side of the communications, then register a class as a well-known service type. From the other side you can instantiate the class and do things to it. The two processes can be running on the same machine, or they could be on different machines that have tcp access to each other.

So if you have one process running, it can run this code to register MyClass on tcp port 8040. The port is just an arbitrary high number that you use on both sides of the conversation:

chan = new TcpChannel(8040);
ChannelServices.RegisterChannel(chan);
RemotingConfiguration.RegisterWellKnownServiceType(
typeof(MyNameSpace.MyClass), “MyClass”, WellKnownObjectMode.Singleton);

You will also need a class, in this case called MyClass. This class will need to inherit MarshalByRefObject.

using System;

namespace MyNameSpace
{
public class MyClass : MarshalByRefObject
{
public String Check()
{
return “Success”;
}
}
}

On the other side, when you want to call the class, you execute this code:

MyClass mc = (MyClass) Activator.GetObject(typeof(MyClass), “tcp://localhost:8040/MyClass”);
System.Windows.Forms.MessageBox.Show(mc.Check())

You will need to replace localhost with the domain name or IP address of the machine that you are connecting to if it is not the current machine. If going through a firewall, that port will have to be open. (Web Services go through port 80 by default, so it usually doesn’t require any firewall configuration).

Also, if any objects are passed back from the call, they need to have the serializable attribute on them. For example, if you had a collection class called Units, you could pass an object created from this class back from a method by declaring the class like this:

[Serializable] public class Units : CollectionBase

ASP.NET: Constructing a Graphic on the Fly in ASP.NET
I needed to construct a PNG file on the fly, so that its content was constructed at the moment it was downloaded. This technique will also work with GIF and JPEG files. This proved easier than I expected in .NET. The graphic is constructed entirely virtually, and is never saved to disk. In fact, there is no file with the graphic name at all.

Step 1, You need to tell IIS that the expected file type needs to be processed by the .NET framework. This has to occur in the IIS Manager dialogs. You may need to get your ISP to perform this task for you.
Right click on the web site in IIS manager and select Properties.
Click on the Home Directory tab.
Click on Configuration button. In the Application Configuration dialog, you are going to set the mapping for .PNG files (or GIF or JPEG) to run through the .NET processing. The easiest way is to…
Select the line in the dialog for an existing extension that is mapped to aspnet_isapi.dll, such as .config and click Edit.
Select and Copy (using Ctrl+C) the path in the Executable textbox from this entry and select Cancel.
Press the Add button.
Paste (using Ctrl+V) the path that you copied.
In the extension textbox add your extension, such as .png.
In the Verbs section, select the Limit To option and put GET, HEAD into the textbox.
Press OK and close all the dialogs

Step 2, Next you have to tell IIS that it should call a piece of code when a file is requested. In the web.config file for the web site, add the following section as a child of <system.web>:

<httpHandlers>
<add verb=”GET” path=”mygraphic.png” type=”MyNameSpace.MyImage, MyAssemblyName” />
</httpHandlers>

This tells .NET that when mygraphic.png is requested that it should instantiate the MyNameSpace.MyImage class.

Step 3, Create the MyImage class. The MyImage class is responsible for drawing the graphic. Add the following class to the web site:

using System;
using System.Collections;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Web;

namespace MyNameSpace
{
public class MyImage: IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
Bitmap bmp;
Graphics gph;
Brush brushFill;
System.IO.MemoryStream ms;

context.Response.BufferOutput = true;
context.Response.Clear();
context.Response.ClearHeaders();
context.Response.ClearContent();
context.Response.ContentType = “image/png”;
context.Response.Expires = 0;
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.Cache.SetNoServerCaching();
context.Response.Cache.SetNoStore();
context.Response.Cache.SetMaxAge(System.TimeSpan.Zero);

bmp = new Bitmap(100, 100, PixelFormat.Format24bppRgb);
gph = Graphics.FromImage(bmp);
brushFill = new SolidBrush(Color.Blue);
gph.FillRectangle(brushFill, 1, 1, 50, 50);
ms = new System.IO.MemoryStream();
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
Byte[] abyte = ms.ToArray();
context.Response.OutputStream.Write(abyte, 0, abyte.Length);
context.Response.End();
bmp.Dispose();
gph.Dispose();
}

public Boolean IsReusable
{
//To enable pooling, return true here.
//This keeps the handler in memory.
get
{
return false;
}
}
}
}

Step 4, Create a web page that uses the graphic. Put the following line in the web page:

<img src=”mygraphic.png” />

When the page is rendered, you will have a 100 x 100 pixel black square with a 50 x 50 pixel blue square in the upper left hand corner. You will need to study the GDI+ features of the .NET framework to modify the drawing. But that’s beyond the scope of what I wanted to cover here.

 

ASP.NET: Controlling Caching in ASP.NET Web Forms

ASP.NET allows you to cache pages. The means that when the code behind the page runs, it produces HTML, the HTML is sent down to the client, however a copy is stored in the memory of the web server. If the same page is requested again, then the page is retrieved from the cache and the code is not rerun. You have virtually infinite flexibility on controlling when the cache gets flushed.

The most basic caching is implemented by placing this line at the top of your ASPX page:

<%@ OutputCache Duration=”3600″ VaryByParam=”none”%>

What this tells the ASP.NET caching code is to cache the page for one hour.

The full spec for the @Output Cache lines is:

<%@ OutputCache Duration=”#ofseconds” Location=”Any Client Downstream
Server None” VaryByControl=”controlname” VaryByCustom=”browser
customstring” VaryByHeader=”headers” VaryByParam=”parametername” %>

Duration is a count in seconds to cache.

Location allows the caching to occur on the server, on the client, on a proxy server in between. The default is Any. If you always want server caching (which seems to me to be the most useful choice), change the line to read:

<%@ OutputCache Duration=”3600″ Location=”Server” VaryByParam=”none”%>

VaryByControl is only used by user controls, not on standard web pages. See the .NET documentation for more details.

VaryByCustom=”browser” keeps a different copy of the output for each browser name and major version information. So if you have cloaking by browser version going on (which is easy to implement in .NET), then each separate page will get delivered.

VaryByCustom=”customstring” Allows you to specify a string that will be passed to your code. To make this useful, you must then override the GetVaryByCustomString method in the Global.asax file. For example, place this line in your ASPX file:

<%@ OutputCache Duration=”3600″ Location=”Server” VaryByCustom=”Referer” VaryByParam=”none”%>

Then in your Global.asax file add the following code:

public override String GetVaryByCustomString(System.Web.HttpContext hcContext, String strCustom)
{
switch (strCustom)
{
case “Referer”:
Uri uriReferrer = hcContext.Request.UrlReferrer;
String strRet;
if (uriReferrer != null)
strRet = uriReferrer.Host;
else
strRet = null;
return strRet;
default:
return base.GetVaryByCustomString(hcContext, strCustom);
}
}

VaryByHeader allows you to cache based off of some field in the HTTP header sent by the client. The classic example is based off the Accept-Language header line.

VaryByParam allows you to cache different versions based off of querystring or post field parameters. So http://www.domain.com/foo.aspx?bar=baz would be cached separately from http://www.domain.com/foo.aspx?bar=bletch

There are also ways of controlling the caching through code.

ASP.NET: How to use the FrontPage Server Extensions with ASP.NET

To use the FrontPage Server Extensions (fpse) 2000 or 2002 with ASP.NET on a NTFS file system can cause some problems. The problem occurs when you use the Check Server Health functionality. This feature modifies the Access Control Lists (ACL) on the files so that the ASP.NET worker process (aspnet_wp) user, ASPNET, no longer has access to the files.

The solution is a minor trick. In the FrontPage Server Extensions, add the named ASPNET as a user of the web site. Grant ASPNET “Browser” permission to the web site. Then re-check the server health, adjusting the file permissions. The FrontPage server extensions will then add read permission for ASPNET to each file on the site.

.NET: Getting and Setting the Application Version Number

In the AssemblyInfo.cs file for each project, you have the opportunity to set the version number of the Assembly. A version number is designed by four number: major.minor.build.revision. The default is 1.0.* If left to this, third number (build) will be set to the number of days since January 1, 2000 local time. The fourth number (revision) will be set to the number of seconds since midnight local time. This is useful since it will always increment every time you build the assembly, unless you are working at 2 a.m. on the last Sunday in October in most places in the United States.

However, in a production environment, you may want to control those numbers manually. In which case, you could set the version to something like 1.3.25.31.

Note that .NET considers changes to the major or minor version to be significant changes, but changes to the build and revision are not. So if you have a reference to an Assembly in the Global Assembly Cache and the major or minor version changes, the new version is considered incompatible with the old version and the previous version will still be linked to.

To retrieve the version number from the assembly in your code, you use can do this:

String strVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();

To retrieve the version number from the assembly that is calling your assembly, you can use this:

String strVersion = System.Reflection.Assembly.GetCallingAssembly().GetName().Version.ToStrin

 

Classes, Objects, and Structures in .NET

Summary

The following article kicks off a three-part article series that will present definitions and samples for different Object-Oriented Programming concepts and its implementation in .NET. The first part will examine the concepts of classes, objects, and structures. The second part will examine the concepts of inheritance, abstraction, and polimorphism. The third and last part will examine the concepts of interface, multiple interface inheritance, collections, and overloading.
Contents
Introduction
Class
Object
Structures
Conclusion
Reference
Introduction

Object-Oriented Programming (OOP) is a software development paradigm that suggests developers to split a program in building blocks known as objects. The OOP paradigm allows developers to define the object’s data, functions, and its relationship with other objects.

Microsoft created the .NET Framework using OOP, and knowing this concepts has helped me to understand the .NET Framework and to design and develop better software components. The purpose of this article is to describe the basic OOP concepts using real world scenarios and to provide some code samples that demonstrate how to work with OOP and .NET.
Class

The most common definition states that a class is a template for an object. Suppose that someone builds a paper pattern for a shirt. All the shirts done with the same paper pattern will be identical (same design, size, etc.). In this sample, the paper pattern is the class and the shirt is the object. To build the same exact shirt over and over, you need the paper pattern as a template. Another great example are house plans and blueprints. The plans and blueprints define the number of rooms, the size of the kitchen, the number of floors, and more. In this real world sample, the house plans and blueprints are the class and the house is the object. In OOP you program a class as a template for a specific object or groups ob objects that will always have the same features.
Class members

A class has different members, and developers in Microsoft suggest to program them in the following order:
Namespace: The namespace is a keyword that defines a distinctive name or last name for the class. A namespace categorizes and organizes the library (assembly) where the class belongs and avoids collisions with classes that share the same name.
Class declaration: Line of code where the class name and type are defined.
Fields: Set of variables declared in a class block.
Constants: Set of constants declared in a class block.
Constructors: A method or group of methods that contains code to initialize the class.
Properties: The set of descriptive data of an object.
Events: Program responses that get fired after a user or application action.
Methods: Set of functions of the class.
Destructor: A method that is called when the class is destroyed. In managed code, the Garbage Collector is in charge of destroying objects; however, in some cases developers need to take extra actions when objects are being released, such as freeing handles or deallocating unmanaged objects. In .NET, there is no concept of deterministic destructors. The Garbage Collector will call the Finalize() method at a non-deterministic time while reclaiming memory for the application.
Access keywords

Access keywords define the access to class members from the same class and from other classes. The most common access keywords are:
Public: Allows access to the class member from any other class.
Private: Allows access to the class member only in the same class.
Protected: Allows access to the class member only within the same class and from inherited classes.
Internal: Allows access to the class member only in the same assembly.
Protected internal: Allows access to the class member only within the same class, from inherited classes, and other classes in the same assembly.
Static: Indicates that the member can be called without first instantiating the class.

The following sample code illustrates a sample class in C#:
/// C#
///Imported namespaces
using System;

/// Namespace: Consider using CompanyName.Product.ComponentType
namespace DotNetTreats.OOSE.OOP_CSharp {

///Class declaration
public class employee {

///Fields
private string _name;
private int _salary;

///Constants
private const int anualBonus = 1000;

///Constructor
public employee(){
}

///Properties
public string Name {
get {
return _name;
}
set {
_name = value;
}
}
public int Salary {
get {
return _salary;
}
set {
_salary = value;
}
}

/// Event handlers
public event EventHandler OnPromotion {
add {
}
remove {
}
}

/// Methods
public void DuplicateSalary() {
_salary = _salary*2;
}

}
}

Listing 1. Sample class implementation in C#

The following sample code illustrates a sample class in VB.NET:
‘ VB.NET
‘Imported namespaces
Imports System

‘ Namespace: Consider using CompanyName.Product.ComponentType
Namespace DotNetTreats.OOSE.OOP_VBNET

‘Class declaration
Public Class employee

‘Fields
Private _name As String
Private _salary As Integer

‘Constants
Private Const anualBonus As Integer = 1000

‘Constructors
Public Sub New()
MyBase.New
End Sub

‘Properties
Public Property Name As String
Get
Return _name
End Get
Set
_name = value
End Set
End Property

Public Property Salary As Integer
Get
Return _salary
End Get
Set
_salary = value
End Set
End Property

‘ Event handlers
Public Event OnPromotion As EventHandler

‘Methods
Public Sub DuplicateSalary()
_salary = (_salary * 2)
End Sub

End Class

End Namespace

Listing 2. Sample class implementation in VB.NET

Object

Objects are the building blocks of OOP and are commonly defined as variables or data structures that encapsulate behavior and data in a programmed unit. Objects are items that can be individually created, manipulated, and represent real world things in an abstract way.
Object composition

Every object is composed by:
Object identity: Means that every object is unique and can be differentiated from other objects. Each time and object is created (instantiated) the object identity is defined.
Object behavior: What the object can do. In OOP, methods work as functions that define the set of actions that the object can do.
Object state: The data stored within the object at any given moment. In OOP, fields, constants, and properties define the state of an object.
Structures

Not everything in the real world should be represented as a class. Structures are suitable to represent lightweight objects. Structures can have methods and properties and are useful for defining types that act as user-defined primitives, but contain arbitrary composite fields. The .NET Framework defines some structures such as System.Drawing.Rectangle, System.Drawing.Point, and System.Drawing.Color.

The following code sample represents a structures in C#:
/// C#
struct Point {
private int _x;
private int _y;

Point(int x, int y){
this._x = x;
this._y = y;
}

public int X {
get {
return _x;
}
set {
_x = value;
}
}

public int Y {
get {
return _y;
}
set {
_y = value;
}
}
}

Listing 3. Sample structure implementation in C#

The following code sample represents a structure in VB.NET:
‘ VB.NET
Structure Point
Private _x As Integer
Private _y As Integer

Sub New(ByVal x As Integer, ByVal y As Integer)
MyBase.New
Me._x = x
Me._y = y
End Sub

Public Property X As Integer
Get
Return _x
End Get
Set
_x = value
End Set
End Property

Public Property Y As Integer
Get
Return _y
End Get
Set
_y = value
End Set
End Property
End Structure

Listing 4. Sample structure implementation in VB.NET

Conclusion

OOP is full of abstract concepts, and the best approach to understand them is practical and not only theoretical. I learned more OOP after making some designs and after implementing some components. The concepts presented in this article might clarify the meaning, but I strongly recommend to go and have fun playing around with OOP. In this article, I examined the concept of classes, objects, and structs. The second part will examine the concepts of inheritance, abstraction, and polimorphism.

 

The release of ADO.NET 2.0, as part of the Visual Studio 2005 launch and the refresh of the .NET Framework and Common Language Runtime, passed relatively unnoticed. That’s understandable. With so much going on in the Microsoft tools domain, with the new Visual Studio Team System, SQL Server 2005, and previews of Office 12 and Windows Vista, that some little database connectivity stuff could easily be overlooked.

Well, look closer. ADO.NET 2.0 is a significant revamping of the connectivity infrastructure within .NET and the CLR, and has special benefits for SQL Server 2005 developers. If you’re already been working with the new classes and methods, kudos to you. For the rest of you, it’s time to see what the updated relational data access system can do for you. Specifically, we’re going to talk about a few of my favorite enhancements, including asynchronous data access, metadata schemas, query notification, multiple active result sets and some new data types. And even with all this, we’re only scratching the surface of what ADO.NET 2.0 offers.

Async Data Access
This is a biggie, folks. With the first versions of ADO.NET, numbered 1.0 and 1.1, a database connection could only process commands serially; in a series of commands to a data provider, like SqlClient, each command had to terminate before the next could begin. Sure, that’s often perfectly fine for simple transaction-processing scenarios, where you to open a connection, write a record, and then close the connection again. But what if you are planning to execute a sequence of operations that can logically be performed in parallel, such as reading a number of datasets into memory? Why not do them all at once?

When using the SqlClient data provider under ADO.NET 2.0, you can now perform true non-blocked async I/O with the SQL Server database. This is enabled by initializing the connection using the phrase async=true in the connection string, and then by taking advantage of new methods in the data provider that can express that you want to perform operations asynchronously.

For example, where you used to have the synchronous ExecuteReader method, you now have two new methods, BeginExecuteReader and EndExecuteReader. Similarly, there’s now a BeginExecuteNonQuery / EndExecuteNonQuery pair, and a BeginExecuteXmlReader / EndExecuteXmlReader pair. The Begin… methods take all the input parameters; the End… methods take all the output parameters and provide the return value. Neat, huh? Note that these async commands work against SQL Server 7.0, SQL Server 2000 and SQL Server 2005. Learn more from “Asynchronous Command Execution in ADO.NET 2.0.”

Metadata Schemas
When you use Visual Studio 2005 to configuring ADO.NET 2.0 to talk to a live database within your application, the IDE can prepopulate many of the database access parameters. Why? Because ASP.NET 2.0 and its data providers can access metadata about that database, which the IDE can take advantage of to help you with drag-and-drop functionality as you link the database to your app. The result is that Visual Studio 2005 is more helpful, when it comes to database development, than any previous version.

Okay, so it makes coding a little easier. Beyond that, who cares about database metadata? Well, you should, if you want your own application to be as smart as Visual Studio 2005 itself. By using that metadata, your app can become more flexible, such as being able to link dynamically to databases and automatically configure itself to discover and use the appropriate tables, columns, stored procedures and triggers. Alternatively, you can use the metadata to help your users customize their interactions with databases, such as by creating reports that take advantage of tables or columns that you didn’t know about you built your application.

Where does this metadata come from? Initially, it comes from the database engine itself. Every modern relational database or data source has its own way of expressing metadata to its access clients. SQL Server 2005, for example, uses a different metadata system than SQL Server 2000, but both are understood by SqlClient. Oracle has its own metadata system, which is read the OracleClient data provider.

ADO.NET 2.0 provides a class, System.Data.Common.DbMetaDataCollectionNames class, to store the metadata, and it’s up to each data-provider writer to import that metadata from the database and populate the class. Microsoft does that with the SqlClient and OracleClient data providers included with ADO.NET 2.0, of course.

These new metadata classes work with all data sources supported by ADO.NET 2.0 data providers, not just with SQL Server 2005. Want to learn more? Check out “Schemas in ADO.NET 2.0.”

Query Notification
A lot of Web applications use external databases to store lookup tables—lists of product codes, perhaps, or branch office locations, state abbreviations, product categories. These items don’t change often; perhaps hourly, perhaps daily, perhaps annually. So, it’s reasonable to cache those items within the Web app, instead of making a new query back to SQL Server every time a browser asks for a list of states to populate a drop-down field.

The problem with caching using ADO.NET 1.0 and 1.1 was that it was difficult to know when one of those rarely changed tables had actually changed, and thus the cache should be reloaded. That meant duct-tape workarounds, such as arbitrary decisions when to reload the cache, or using triggers or other mechanisms to set a “dirty” flag, which your application would watch for somehow.

ADO.NET 2.0 and SQL Server 2005 solve this problem with their new Query Notification signaling mechanism. The ASP.NET 2.0 cache can now register a request for notification with the SQL Server 2005 database, though a new SqlNotificationRequest class contained within the SqlCommand. The SQL Server database will remember that query notification, along with the query and its rowset. If that rowset changes, SQL Server 2005 will send back a notification to the client’s SqlDependency class using the new SQL Server Service Broker. Simple and elegant. This only works with SQL Server 2005; more information is at “Query Notifications in ADO.NET 2.0.”

Multiple Active Result Sets
It seemed like a big step backwards to many Visual Basic and Visual C++ developers: The original ADO permitted you to maintain multiple active cursorless result sets within a database, but ADO.NET 1.0 / 1.1 did not. If you tried to open more than one cursorless result set, ADO.NET 1.0 / 1.1 returned an error condition. The upshot was that in ADO.NET 1.0/1.1, if you needed multiple result sets, you had to close one SqlDataReader before opening another. Annoying, and arbitrary.

When used in conjunction with SQL Server 2005, ADO.NET 2.0 solves that problem by allowing you to open multiple result sets at the same time. You can learn more about this from “Multiple Active Result Sets (MARS) In SQL Server 2005.” If you relied upon this capability in ADO, doesn’t this make your day?

User Defined, XML Data Types
Another SQL Server 2005-specific feature of ADO.NET 2.0 is support for user defined types and XML data types.

User defined types were standardized by the SQL:2003 specification published by the ISO. You can now access them by using the SqlUdt namespace in the System.Data.SqlTypes namespace; the result is a .NET Object. Similarly, there’s a new SqlXml namespace for XML data; the results are returned as a .NET String. These match up with the new XML data type within SQL Server 2005; this is a first-class data type, not just something cobbled together from strings, and you can also access XML using the new SqlCommand.Execute.XmlReader method.

For more, see “XML Data Type Support in ADO.NET 2.0: Handling XML from SQL Server 2005.”

 

 

Classes—Wrapping Data and Behavior Together

Starting with the release of Visual Basic 4.0, the capability to create classes has been intrinsic to the Visual Basic language. Some might say that Microsoft’s move to support this was the true beginning of VB’s evolution into an object-oriented language. Whenever it started, and whatever you thought of Visual Basic’s prior ability (or inability) to support object-oriented (OO) concepts, .NET brings Visual Basic up to speed with all of the basic properties of an object-oriented programming language. The deep object support in Visual Basic .NET, and the .NET Framework in general, is certainly one of the most compelling changes offered in this new environment.

This chapter will focus on defining the concepts of object orientation as they relate to software development in general. In Chapter 4, “Introduction to the .NET Framework Class Library,” we will also examine their specific manifestations in the .NET Framework.

There have been more than a few books written on object-oriented programming, so this chapter will not attempt to deliver a full treatise on a subject well deserving of hundreds of pages. Instead, we will cover only the ground that we need to cover so that programmers new to object-oriented programming and programmers with no OO experience at all will have a good backdrop of knowledge for exploring the .NET Framework Class Library.

We’ll start by reviewing all of the pertinent characteristics of object-oriented languages—an obvious first step when you consider that the classes and other pieces of the Framework Class Library are all object-oriented in nature. Then we’ll examine how these concepts have been brought to life inside of .NET and Visual Basic .NET, hopefully arming you with a solid-enough understanding of these concepts to make your programming experiences with the Framework Class Library more productive.

In years past, many developers have debated whether Visual Basic was an object-oriented language. Instead of investigating any of these prior claims, arguments, or discussions, let’s focus instead on the here and now. Visual Basic .NET supports the major traits of an object-oriented language, including the capability to:

Wrap data and behavior together into packages called classes (this is a trait known as encapsulation)

Define classes in terms of other classes (a trait known as inheritance)

Override the behavior of a class with a substitute behavior (a trait known as polymorphism)

We’ll examine each one of these traits in detail. We’ll also examine ways in which you will see these concepts at work inside of the .NET Framework. Chapter 4 will continue this thread by specifically examining the nature of the Framework Class Library and attempting to relate these object-oriented concepts directly to the Framework Class Library.
Classes—Wrapping Data and Behavior Together

Classes are blueprints or specifications for actual objects that we will create in our code. They define a standard set of attributes and behaviors. Because classes only define a structure or intent, they are virtual in nature. For instance, a class cannot hold data, it can’t receive a message, and in fact can’t do any processing at all. This is because classes are only meant to be object factories. Just like real engineering blueprints of a building, they only exist to construct something else. When we program, this “something else” we are trying to construct is an object. An object can hold data, can receive messages, and can actually carry out processing.

While you don’t typically use the term class in your everyday (non-programming) life, we are all certainly familiar with the concept of objects. These are the things that surround us day in and day out; they are the nouns in our universe. We are used to interacting with objects. For example, you place a plate on your table for dinner. The plate has food on it—a few different types of food, in fact. We can see that all of these things have distinct properties: The plate is white with a faint flower pattern, and the food has a particular texture, taste, and smell. We also expect that objects will allow us to interact with them in different ways.

Just like in the real world, code objects (we also call them instances) are actual physical manifestations of classes.
Classes as Approximations

If we discuss classes in the context of programming, we say that they establish a template for objects by defining a common set of possible procedures and data. Procedures are used to imbue the class with a set of behaviors; when implemented in a class they are called methods. Classes maintain data inside of properties (which may or may not be visible to other classes). Behaviors are the verbs of classes, and properties are the nouns. A car, for instance, will accelerate in a prescribed fashion. This would be a behavior. A car will also have a specific weight, color, length, and so on. These are properties. From a technical, implementation point of view, there is actually no difference between the way that methods and properties are implemented. They both have function signatures, and both execute some body of code. In addition, both of them can accept parameters and return values.

Note

There are some general guidelines for when to use properties versus methods (and vice versa), but probably the best advice is to just be consistent. Most of the time, these rules will help steer you to the correct decision:

Use a method if you are going to be passing in more than a few parameters.

If you find yourself writing a method called GetXXX or SetYYY, chances are good this should be a property instead.

Methods are more appropriate than properties if there will be many object instantiations or inter-object communication inside of the function.

Properties, when implemented, should be stateless with respect to one another. In other words, a property should not require that another property be set before or after it is set. If you find this kind of dependency inside of a property, it should probably be a method instead.

Classes are typically constructed to mimic, or approximate, real-world physical structures or concepts. By using classes in your code, you can simplify both your architecture and your understanding of the code; this is due to the inherent approachability of objects—your mind is used to deal with objects. For example, which do you suppose would make more intuitive sense to you?

You are writing code to move an icon from the left side of the screen to the right side of the screen. The procedural programming way would probably have you calling some API function (maybe it’s called SystemDskRsrcBlit) and passing parameters into the function call. But, what if you were free to do this:

Create an icon object

Tell it to MoveLeft

The object-oriented way just seems to make more sense to us—it seems to appeal to the way that our minds are wired.

Note

The difference between the system that we are programming and the real-world process that we are modeling is often referred to as the semantic gap. You could summarize some of what we have been talking about here by saying that object- oriented programming aims to reduce the semantic gap between programming and the real world.

Of course, just because the basic premises of objected-oriented programming are simple to understand doesn’t mean that the actual programming of object-oriented systems is trivial. Once you can work your way through the syntax and condition yourself to think in an object-like fashion while actually designing your applications, some of the perceived complexity associated with software development will begin to fade.
Talking Between Classes

We have said that classes define a set of behaviors. These behaviors would be useless to us unless we had a way to actually stimulate or initiate a particular behavior. Therefore, we have the concept of messaging. A message is nothing more than a request, from one object to another, to perform some sort of action. The receiving object may choose to ignore the action (especially if it doesn’t have a behavior defined that would map to the requested action) or it may perform a specific action that could, in turn, send messages to other objects.

A core tenet of object-oriented systems is that classes think for themselves. A particular class knows how it should react to an incoming message; the calling class isn’t forced to understand how or why the receiving class behaves the way that it does. This is the essence of information hiding. In information hiding, an object hides its internal machinations from other objects (see Figure 3.1). Information hiding is important because it helps reduce the overall design complexity of an application. In other words, if Class A doesn’t have to implement code to understand how Class B operates, we have just reduced the complexity of the code.

As programmers, we initiate a message from one class to another by calling a method or property on the target class. Part of this message that we send encapsulates any parameters or data needed by the receiving class to execute the action.

Thus, we have classes in an object-oriented programming environment. A physical manifestation of a class in the programming world consists of code that defines these attributes and behaviors through property and method routines.

In this book, our focus on the Framework Class Library will introduce you to new classes in each chapter. They will exhibit all of the traits and characteristics of the classes that we have just defined.

Now, let’s move on and discuss the next OO trait of Visual Basic .NET—inheritance.

 

Inheritance—Defining Classes in Terms of One Another

Inheritance is the capability for one class to inherit or take on the traits of another class. Typically, this happens in a hierarchical fashion. Consider the following simple example to see how this inheritance results in a natural hierarchy of classes. Figure 3.2 shows three classes: HR Employee, IT Employee, and Warehouse Employee. Each of these is shown with some of their properties and methods.

By looking at them, it quickly becomes clear that we could hierarchically structure these classes by abstracting their common traits into a parent class. These three classes would then be child classes of that one parent class.

This hierarchical structure is typical of well-engineered class libraries—the Framework Class Library is organized in just such a way.

Inheritance by Natural Relationship

One of the nice things about inheritance is that it often simply realizes a relationship that we already make in our minds. That is, it is often just a recognition of real-world relationships. We can tell that a dog or a cat is a type of an animal—the inheritance between the concept of an animal class and a dog or cat class is obvious. Again, this is a good thing as it helps to reduce the semantic gap that we talked about earlier and helps you make your code organization easier to understand. Organizing your code is only one benefit of inheritance—code reuse is another.

We have said that a class can inherit the traits of another class. We have also said that the traits of a class are implemented as property and method routines. When these routines are inherited between classes, it obviously means we are assuming the actual source code of one class into another. Thus, we have code reuse.

we can see how each line of code that was written to implement the parent class methods can be reused by each of the child classes. Code reuse in this fashion becomes a powerful rapid application development enabler. If we needed to change some lines of code in one of the parent class methods, the change would be immediately realized in its children classes. This also allows us to build up complexity in a child class by inheriting from potentially simple base classes.

There are many different ways to express the inheritance relationship: parent to child, super-class to sub-class, ancestor class to descendant class, generalized class to specialized class, and so on. In this book, anytime we use these terms you should know that we are just referring back to this basic concept of inheritance relationship.

We now know that identifying logical relationships between objects will help us out in the area of code reuse. But the examples we have talked about so far have been based on relationships between objects—an appraisal of one object being a type of another object. If, however, you approach inheritance by first looking at its end result, you’ll find that you can end up with an entirely different perspective. Let’s look at an example: Let’s say that we have a class that defines operations for a specific type of printer. We’ll call this class InkJet. Intuitively, we sense a parent class that would most likely be called Printer.

Inheriting from the Printer class is a good solution for us because it already defines some basic operations (line feed, paper out, and so on) that we can use as building blocks for our InkJet class. At the same time, we will add some of our own behaviors that are specific to inkjet printers. But what if we had the requirement for some low-level communication code that would send an error signal across a parallel port? Also, what if that code was already available to us in yet another class?

This is subtly different from what we were doing before because it is very difficult to envision a logical relationship between a parallel port object and an inkjet object. After all, an inkjet printer is not a type of a parallel port—there is no obvious hierarchical relationship to draw between the two. In this case, we would be implementing inheritance to get at raw code reuse. This doesn’t do anything for us in terms of making our code easier to understand—it does not reinforce a relationship between abstract classes and real-world objects.

Inheriting for pure code reuse in the absence of a sub-type relationship is certainly something that you can do with classes, but isn’t always the best approach. You gain code reuse at the expense of increased complexity in your system (and therefore, a corresponding increase in the effort required to understand your system). In .NET, we advocate implementing an interface instead of using class inheritance to represent this relationship; you still get the desired code reuse without complicating your class relationships

 

Polymorphism—Overriding One Class Method with Another

The next OO trait we will discuss is polymorphism. Unlike inheritance, polymorphism is concerned with how a class presents itself to the outside world. Polymorphism roughly means “many forms,” and alludes to the fact that a specific named behavior can be implemented in different ways by different classes.

In other words, classes can reuse behavior names but implement them differently.

Overriding

One of the common examples used to demonstrate this concept involves a class library that describes geometric shapes. One of the behaviors that we would like to imbue into our shape classes is the capability to draw themselves. Using our basic knowledge of geometry, we know that each shape will require different parameters and use different operations to actually accomplish the draw operations (pi may be used when drawing circles, squares will need to know a side length, and so on). Because a procedural programming language doesn’t allow us to reuse behavior names (think methods), we would end up with a different routine for each shape type such as DrawCircle, DrawTriangle, and so on. Because we can reuse method names with polymorphism, we can simplify the programming model considerably by reusing one method called Draw; each shape class would implement this in a slightly different fashion. This is called overriding and specific manifestations of this in the Framework Class Library are discussed in Chapter 4.

Overriding further promotes the concept of information hiding that we talked about earlier: Each class knows internally how to implement its behaviors, but calling classes don’t know and don’t care. We just send a message saying, “Draw,” and the target class worries about how to carry it out. You will often see overriding with inheritance. A child class may override a parent class’s methods to implement specific functionality not relevant to the parent class.

Overloading

It represents a class, Square, and its draw methods. The implementation of the draw behavior differs based on the information that is passed into the Draw method. This is a special case of overriding called overloading. In our example here, we want to avoid implementing methods called DrawFromLength and DrawFromCoords; we simplify our class architecture by implementing just one method, Draw, and let it determine which implementation of Draw to use based on the function signature. In this way, both of the following would be valid method calls:
mySquare.Draw(10,”inches”)
mySquare.Draw(topLeftPoint, bottomRightPoint)

Polymorphism is really all about keeping interfaces between classes the same while allowing actual implementations to differ. This encourages loosely coupled object designs and hopefully clarifies system architecture and reduces complexity.

 

1. How to get the path for “My Documents” and other system folders?

Use the GetFolderPath method of the System.Environment class to retrieve this information.
MessageBox.Show( Environment.GetFolderPath( Environment.SpecialFolder.Personal ) );
#2. How to get the path to my running EXE?

The Application class has a static member ExecutablePath that has this information.
string appPath = Application.ExecutablePath;

Alternative: The tip below is provided by cbono2000
System.Reflection.Assembly.GetExecutingAssembly().Location
#3. How to determine which operating system is running?

Use System.Environment’s OSVersion static (shared) property.
OperatingSystem os = Environment.OSVersion;
MessageBox.Show(os.Version.ToString());
MessageBox.Show(os.Platform.ToString());
#4. How to get a file’s name from the complete path string?

Use System.IO.Path.GetFileName and System.IO.Path.GetFileNameWithoutExtension static methods.
#5. How to get a file’s extension from the complete path string?

Use System.IO.Path.GetExtension static method.
#6. What is difference beween VB.NET and C#.NET?

Hi friends, click here to find the best comparison ever between VB.NET and C#.NET .
#7. How to find whether your system has mouse or the number of buttons, whether it has wheel, or whether the mouse buttons are swapped or size of your monitor and many such information?

Download source files – 8.65 Kb
Download demo project – 4.60 Kb
Use System.Windows.Forms.SystemInformation.
SystemInformation provides static (Shared in Visual Basic) methods and properties that can be used to get information such as Windows display element sizes, operating system settings, network availability, and the capabilities of hardware installed on the system.This class cannot be instantiated. e.g
MousePresent: SystemInformation.MousePresent.ToString()
MouseButtonsSwapped: SystemInformation.MouseButtonsSwapped.ToString()
#8. What is the purpose of the [STA Thread] attribute for the Main method of a C# program?

That marks the thread as being Single
Thread Apartment which means any multiple threaded calls need to be marshaled
over to that thread before they are called. That’s there because Windows Forms
uses some OLE calls (Clipboard for example), which must be made from the thread
that initialized OLE.
#9. How to import CSV data using .NET application?

Importing CSV files using .NET application
#10. How to find size of logical drives using .NET?

Download source files – 10.0 Kb
Download demo project – 5.48 Kb

There is direct method in .NET for computing the file size but there is no such method for computing directory size and logical drive size.One may think of just adding file size to get directory size and then drive size. But this method has some drawbacks. But we can use Win32 API function GetDiskFreeSpaceEx for this purpose.
The GetDiskFreeSpaceEx function retrieves information about the amount of space that is available on a disk volume, which is the total amount of space, the total amount of free space, and the total amount of free space available to the user that is associated with the calling thread. You can do it as following: Enlist the drives:
string[] tempString = Directory.GetLogicalDrives();
foreach(string tempDrive in tempString)
{
cmbDrives.Items.Add(tempDrive);
}
cmbDrives.SelectedIndex=0;
public sealed class DriveInfo
{

[DllImport("kernel32.dll", EntryPoint="GetDiskFreeSpaceExA")]
private static extern long GetDiskFreeSpaceEx(string lpDirectoryName,
out long lpFreeBytesAvailableToCaller,
out long lpTotalNumberOfBytes,
out long lpTotalNumberOfFreeBytes);

public static long GetInfo(string drive, out long available, out long total, out long free)
{
return GetDiskFreeSpaceEx(drive,out available,out total,out free);
}

public static DriveInfoSystem GetInfo(string drive)
{
long result, available, total, free;
result = GetDiskFreeSpaceEx(drive, out available, out total, out free);
return new DriveInfoSystem(drive,result,available,total,free);
}

}

public struct DriveInfoSystem
{
public readonly string Drive;
public readonly long Result;
public readonly long Available;
public readonly long Total;
public readonly long Free;

public DriveInfoSystem(string drive, long result, long available, long total, long free)
{
this.Drive = drive;
this.Result = result;
this.Available = available;
this.Total = total;
this.Free = free;
}
}
and then you can use it as
DriveInfoSystem info = DriveInfo.GetInfo(“c:”);

 

OOPS
#1. What are Copy Constructors?

We know that a constructor is a special method that has the same name as the class and returns no value.
It is used to initialize the data in the object we’re creating.

There’s another kind of constructor—the copy constructor. When we copy one object to another, C# will copy the reference to the first object to the new object, which means that we now have two references to the same object. To make an actual copy, we can use a copy constructor, which is just a standard constructor that takes an object of the current class as its single parameter. For example, here’s what a copy constructor for the Student class might look like. Note that we’re copying the name field to the new object.
public Student(Student student)
{
this.name = student.name;
}

Now we can use this constructor to create copies. The copy will be a separate object, not just a reference to the original object.
class Student
{
private string name;

public Student(string name)
{
this.name = name;
}

public Student(Student student)
{
this.name = student.name;
}

public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
}

class Final
{
static void Main()
{
Student student = new Student (“A”);
Student NewStudent = new Student (student);
student.Name = “B”;
System.Console.WriteLine(“The new student’s name is {0}”, NewStudent.Name);
}
}

The new student’s name is A.
#2. What are Read-Only Constants?

There are situations where we would like to decide the value of a constant member at run-time. We may also like to have different constant values for different objects of class. To overcome these shortcomings, C# provides another modifier known as readonly to be used with data members. This modifier is designed to set the value of the member using a constructor method, but cannot be modified later. The readonly members may be declared as either static fields or instance fields. When they are declared as instance fields, they can take different values with different objects. Consider the code below:
class Numbers
{
public readonly int m;
public static readonly int n;
public Numbers (int x)
{
m=x;
}

static Numbers ()
{
n=100;
}
}

The value for m is provided at the time of creation of an object using the constructor with parameter x. This value will remain constant for that object. Remember, the variable n is assigned a value of 100,even before the creation of any objects of Numbers.

Describe the differences between XML and HTML.

It’s amazing how many developers claim to be proficient programming with XML, yet do not understand the basic differences between XML and HTML. Anyone with a fundamental grasp of XML should be able describe some of the main differences outlined in the table below.

Differences Between XML and HTMLXML HTML

User definable tags
Defined set of tags designed for web display

Content driven
Format driven

End tags required for well formed documents
End tags not required

Quotes required around attributes values
Quotes not required

Slash required in empty tags
Slash not required

Describe the role that XSL can play when dynamically generating HTML pages from a relational database.

Even if candidates have never participated in a project involving this type of architecture, they should recognize it as one of the common uses of XML. Querying a database and then formatting the result set so that it can be validated as an XML document allows developers to translate the data into an HTML table using XSLT rules. Consequently, the format of the resulting HTML table can be modified without changing the database query or application code since the document rendering logic is isolated to the XSLT rules.

Give a few examples of types of applications that can benefit from using XML.

There are literally thousands of applications that can benefit from XML technologies. The ball of this question is not to have the candidate rattle off a laundry list of projects that they have worked on, but, rather, to allow the candidate to explain the rationale for choosing XML by citing a few real world examples. For instance, one appropriate answer is that XML allows content management systems to store documents independently of their format, which thereby reduces data redundancy. Another answer relates to B2B exchanges or supply chain management systems. In these instances, XML provides a mechanism for multiple companies to exchange data according to an agreed upon set of rules. A third common response involves wireless applications that require WML to render data on hand held devices.

What is DOM and how does it relate to XML?

The Document Object Model (DOM) is an interface specification maintained by the W3C DOM Workgroup that defines an application independent mechanism to access, parse, or update XML data. In simple terms it is a hierarchical model that allows developers to manipulate XML documents easily Any developer that has worked extensively with XML should be able to discuss the concept and use of DOM objects freely. Additionally, it is not unreasonable to expect advanced candidates to thoroughly understand its internal workings and be able to explain how DOM differs from an event-based interface like SAX.

What is SOAP and how does it relate to XML?

The Simple Object Access Protocol (SOAP) uses XML to define a protocol for the exchange of information in distributed computing environments. SOAP consists of three components: an envelope, a set of encoding rules, and a convention for representing remote procedure calls. Unless experience with SOAP is a direct requirement for the open position, knowing the specifics of the protocol, or how it can be used in conjunction with HTTP, is not as important as identifying it as a natural application of XML.

Can you walk us through the steps necessary to parse XML documents?

Superficially, this is a fairly basic question. However, the ball is not to determine whether candidates understand the concept of a parser but rather have them walk through the process of parsing XML documents step-by-step. Determining whether a non-validating or validating parser is needed, choosing the appropriate parser, and handling errors are all important aspects to this process that should be included in the candidate’s response.

Give some examples of XML DTDs or schemas that you have worked with.

Although XML does not require data to be validated against a DTD, many of the benefits of using the technology are derived from being able to validate XML documents against business or technical architecture rules. Polling for the list of DTDs that developers have worked with provides insight to their general exposure to the technology. The ideal candidate will have knowledge of several of the commonly used DTDs such as FpML, DocBook, HRML, and RDF, as well as experience designing a custom DTD for a particular project where no standard existed.

Using XSLT, how would you extract a specific attribute from an element in an XML document?

Successful candidates should recognize this as one of the most basic applications of XSLT. If they are not able to construct a reply similar to the example below, they should at least be able to identify the components necessary for this operation: xsl:template to match the appropriate XML element, xsl:value-of to select the attribute value, and the optional xsl:apply-templates to continue processing the document.

Extract Attributes from XML Data
Example 1.

<xsl:template match=”element-name”>
Attribute Value:
<xsl:value-of select=”@attribute”/>
<xsl:apply-templates/>
</xsl:template>

When constructing an XML DTD, how do you create an external entity reference in an attribute value?

Every interview session should have at least one trick question. Although possible when using SGML, XML DTDs don’t support defining external entity references in attribute values. It’s more important for the candidate to respond to this question in a logical way than than the candidate know the somewhat obscure answer.

How would you build a search engine for large volumes of XML data?

The way candidates answer this question may provide insight into their view of XML data. For those who view XML primarily as a way to denote structure for text files, a common answer is to build a full-text search and handle the data similarly to the way Internet portals handle HTML pages. Others consider XML as a standard way of transferring structured data between disparate systems. These candidates often describe some scheme of importing XML into a relational or object database and relying on the database’s engine for searching. Lastly, candidates that have worked with vendors specializing in this area often say that the best way the handle this situation is to use a third party software package optimized for XML data.

 

Leave a Reply