Report creation with .NET’s various reporting options

Posted on May 14th, 2008 in .Net by Ashish  Tagged
Developers often cringe when they have to create reports, but there are numerous options available with .NET to simplify the process. Tony Patton offers you a look at .NET’s various reporting options.
Data is the lifeblood of the enterprise and almost every application you develop will tap data in some manner. With all that data, users eventually want to view it in a report.

Many novice developers foolishly tackle reporting by creating custom forms—but this legwork is not necessary, as there are plenty of options with .NET for creating reports by dragging and dropping or a custom object model. In addition, reporting solutions offer additional functionality like PDF generation and charting that is hard to duplicate with custom code. .NET’s choices include readily available options, third-party products, and open source solutions. Let’s take a closer look at the reporting options available with .NET by category.

Readily available reporting options
I was very excited when I first encountered .NET with Visual Studio .NET. My enthusiasm stemmed from the inclusion of Crystal Reports within the environment. That’s right, no more purchasing and installing the product (although a standalone version is still available). My excitement was quickly extinguished as I tackled my first product utilizing Crystal Reports functionality. Its documentation is arcane and getting everything working properly is a bit mind-numbing. As time as passed, a few books have appeared on the subject and there are numerous Web resources as well. One in particular that I would recommend is Crystal Reports .NET Programming by Brian Bischof.

While Crystal Reports is readily available, the Microsoft Office Suite is seemingly everywhere as well. You may utilise Excel or Word functionality in a Windows client application or use the Office Web Components for browser clients. The different applications are readily accessible via your .NET code. Or, your enterprise may opt for another suite such as StarOffice or OpenOffice. Whatever the product, you can take advantage of it in your application. If these products are not a viable option, there are plenty of third-party products available.

Third-party products
Here is a sampling of third-party .NET reporting solutions. Free trial versions are available for most products, so you can give it a test run before making a commitment. Of course, there are open source options available as well.

  • ActiveReports for .NET: A managed implementation of the popular ActiveReports engine and report viewer. It provides complete code integration with the Visual Studio .NET environment. It supports both Web and Windows clients and allows exporting to PDF, Excel, RTF, HTML text, and TIFF images. The documentation is thorough and the drag-and-drop interface is straightforward.
  • ComponentOne Studio for .NET: It includes two tools: the report component, which generates Access-style database reports, and its companion Report Designer for report layout. It also includes tools for migrating Crystal Reports to their environment.
  • OOReport.NET: This product provides reports for Web-based clients. It also includes controls for assembling repots.
  • Visual Reports: This may be used with pre-.NET Visual Studio projects. It also includes an interactive report designer for proper layout. Report properties and such are accessed via COM interface.
  • Windward Reports: This product facilitates report design and creation via Microsoft Word. Open source reporting options

In the past, the term open source would never be uttered when discussing Microsoft-based development, but the .NET Framework’s acceptance and use of (some) standards has fueled several great open source solutions for .NET. And, reporting has a number of options.

Charting capabilities are provided by NPlot. One of the great features of .NET is the lack of adherence to one particular language, so you can use other products that are not .NET-based. While this may be beyond many .NET developers, open source solutions like the Java-based JasperReports can provide clean and simple reports.

Don’t overlook SQL Server
I would be remiss not to mention SQL Server’s Reporting Services. Microsoft describes it as “a comprehensive, server-based reporting solution designed to help you author, manage, and deliver both paper-based and interactive Web-based reports.” It is an excellent solution where SQL Server is readily available. It was first introduced as an add-on for SQL Server 2000, but it is also included with SQL Server 2005. It includes a report builder for simplifying report creation. SQL Server 2005 Reporting Services does not require Visual Studio .NET like its predecessor, but it may be utilised.

Make the data presentable
Where there is data there is a need to make sense of it, and reporting is one tool to aid users in this chore. Luckily, the .NET Framework includes various options ranging from the inherent Crystal Reports to open source alternatives. Your choices may depend on cost, but each product offers plenty of features to enhance your application.

.NET and serviced components

Posted on May 14th, 2008 in .Net by Ashish  Tagged

The .NET Framework provides enterprise services for building highly scalable solutions, but the implementation can be tricky. Learn when and where these services should be used.

One of the biggest mistakes architects can make when designing Enterprise Services is to assume that its sole purpose is to provide wrappers for existing unmanaged COM+ and MTS functionality. It’s a common assumption, given that the current Enterprise Services implementation provides little more than a managed interface to unmanaged COM+.

However, Microsoft views Enterprise Services quite differently. In its eyes, Enterprise Services is the replacement for COM+ and MTS. Going forward, Microsoft has two primary goals for new versions of the .NET Framework, starting with release 1.1 that’s due with Windows .NET Server 2003. First, all existing COM+ functionality will move to managed code. Second, all new distributed systems management functionality will be implemented in Enterprise Services in .NET. In fact, COM+ version 1.5 (released with Windows XP) will likely be the last version of COM+ available as an unmanaged release.

What is Enterprise Services?
Given Microsoft’s emphasis on Enterprise Services as its distributed systems development platform, you need to understand exactly what services Microsoft is talking about. Enterprise Services supports resource management in a distributed environment. This functionality includes support for distributed transactions, role-based security and packaging of objects, object pooling, just-in-time-activation (JITA), queued components, and loosely coupled events. When used together, these functions give architects the tools to implement a complete server application process model.

One of the most confusing aspects of Enterprise Services is when to use them. If your existing systems use COM+ extensively, you’ll naturally want to use Enterprise Services when porting your applications to .NET. But if you don’t use COM+ today, how do you get started and what’s the benefit?

Implementing transaction support
To understand how you can get started with Enterprise Services, let’s look at how you implement transaction support in three different scenarios: traditional distributed applications, Web services, and ASP.NET applications. It’s important to differentiate between how developers handle transactions in the COM+ world vs. .NET. In COM+, developers manually start a transaction and then check conditions to determine whether the transaction should be committed or aborted. But .NET lets you handle transaction commits and aborts automatically by using declarations exposed through attributes. In other words, you can think of distributed transactions as automatic or declarative transactions in .NET. (Developers still have the option of coding commits and aborts manually if they need that granular level of control.)

Traditional distributed applications
For a traditional distributed application, the developer needs to create a server object and then code the client to call the server object. Here’s a simple implementation of a server object implemented in C#:

using System;
using System.EnterpriseServices;
[assembly : ApplicationName("TxDemo")]

[Transaction]
public class Account : ServicedComponent {
[AutoComplete]
public void Credit() {
// do some work
} }

We should note three important items from this sample. First, the statement, using System.EnterpriseServices; gives you access to attributes in the Enterprise Services namespace. Second, the Account class inherits from the existing ServicedComponent class, where it gets its ability to be managed by EnterpriseServices. Finally, the Transaction and AutoComplete attributes make objects instantiated from this class transactional. The AutoComplete attribute tells EnterpriseServices to commit the work done in the Credit function unless an error occurs, in which case it should abort. You still can catch exceptions and swallow them (i.e., not Throw them up the call stack) with AutoComplete committing the transaction.

Here’s the code required to use the Credit object from a client application:

public Class AccountClient {
private void Transactions_Click() {
Account account = New Account();
order.Credit()
} }

Notice that the client has no idea that the server object uses transaction management.

Web Services
If your users need to consume resources managed by Enterprise Services but access them through a Web Services interface, you can expose those resources using parameters on the WebMethod attribute declaration. For example, the code below allows the WebMethod DeleteAuthor to create a new transaction before attempting to delete the author passed in by the user of the Web service:

[WebMethod(TransactionOption=
TransactionOption.RequiresNew)]
public int DeleteAuthor(string lastName) {
//…
}

Any other business objects called by this WebMethod automatically inherit its transaction context as long as they are marked to either Support or Require a transaction.

ASP.NET applications
Using transactions from ASP Pages is simple, as well. You add a page-level directive like this:


The Required setting allows this page to initiate a new transaction if it’s not already participating in an existing one. Any components called by this page will participate in the same transaction context.

What’s the benefit of Enterprise Services?
Before we look at the benefit of Enterprise Services, let’s first consider the widely discussed downside: performance. It’s true that calling serviced components is slower than calling other objects. This is because creating context and crossing context boundaries imposes overhead on your applications. But calling serviced components hosted in library applications (these run in-process with the application) is nearly as fast as calling nonserviced components. Server applications have a higher call time due to crossing process or machine boundaries. You determine whether components run as library or server applications when you install them in COM+.

But here’s the real issue: In most real-world applications, the performance cost of the infrastructure required to support Enterprise Services is minimal compared to the cost of the actual work that the component does. Moreover, if you didn’t use the features provided by serviced components, your code will likely have to do additional work to get the same functionality.

So when should you use serviced components? In general, if your application architecture can benefit from the services (like guaranteed transactions) provided by Enterprise Services, serviced components are worth the performance cost. You should also consider the ease of development and future expansion benefits of developing with serviced components. Development is simpler with serviced components. If you use a SqlTransaction object or OleDbTransaction object to manage transactions, you’ll have to manage the transaction yourself. With Enterprise Services, you simply add a Transaction attribute to your object(s). Enterprise Services ensures that transactions managed between multiple objects happen logically and consistently. For example, you won’t have to add any special logic to determine whether an object is the root of a transaction.

Future expansion is easier to accomplish if you code systems using serviced components from the start. Suppose you create an order management system that includes inventory tables managed as part of the overall order transaction. What if, in the future, the inventory tables move to a separate database? What if the inventory object is moved to a remote server? What if one of the objects wants to dispatch to a transactional message queue? If you built the system with manual transaction management, you’ll have to rewrite it in order to make it work in a distributed environment. Had you built the system using Enterprise Services, you could make these deployment decisions without requiring changes to the underlying application.

It will take time to learn how to implement serviced components correctly. And you may not need to use them for many of your smaller applications. But employing their functionality correctly for distributed applications will pay off in the long term because they allow you to make deployment decisions without regard for design decisions you made during development.

Improve data access in ASP.NET applications

Posted on May 12th, 2008 in .Net by Ashish  Tagged
Perhaps the two best examples of this axiom are the data-bound control from Visual Basic 3.0 and the Visual Interdev Design Time Control (DTC). The VB3 data-bound control made great demos, but its performance effects on the underlying database had even Microsoft’s own consulting services group recommending against its use in a production application.

Interdev DTCs are legendary for the number of developers who were suckered into using them for a simple application, only to find that they had to rewrite the functionality from scratch when they wanted to extend them or modify their output because the DTC was neither modifiable nor extensible. Consequently, when I first saw the .NET DataSet object, I was cautiously optimistic. Unfortunately, many developers chose not to be cautious at all.What’s wrong with the DataSet?
I’m not saying that there’s anything inherently wrong with the DataSet object. But it’s like any other tool—you need to understand how to use it appropriately. Although it’s a useful tool for Windows Forms applications, it’s much less useful for Web application development.

Let’s look at a simple example. Suppose you use a DataSet to return a set of 1,000 products to display in a DataGrid on a form. Since you might want to sort or filter the data later, you choose to save the DataSet in a session variable. Not knowing any better, you also leave the default page ViewState turned on. When a user navigates to this page, there are three copies of the data somewhere in memory. It’s on the server saved in a session-level variable. It’s in the ViewState stored as the contents of the DataGrid. And it’s in the rendered HTML stream in the form of HTML table directives that render the table. Now multiply the server memory by the number of users to assess impact on server memory, and multiply the two copies of the data by the number of users to assess the impact on bandwidth utilisation. You can quickly overload a server and its available network bandwidth on a high-traffic site.

The answer: Use the DataReader
Though not as sexy, the DataReader is much more functional for a Web application. Because the DataSet object’s cursor is designed to iterate in a forward-only, read-only fashion over the results of a query, it’s very fast. Moreover, the DataReader only holds the current record in memory at any one time—never the entire results set. The DataSet object can be bound to ASP.NET Server Controls (like the DataGrid). More importantly, server resources and connection resources are released as soon as you’re finished traversing them. Build your data-bound pages using DataReaders to retrieve data from an underlying database whenever it’s important for the data to be as fresh as possible.

When should I use the DataSet?
The only time I recommend using the DataSet in a Web application is when the underlying data changes on an occasional basis. For example, if you have a series of drop-down boxes or checklist items that come from a database but rarely change, it may make sense to load them in a DataSet in the Application_OnStart event and put them into the cache so that any page that needs to get the values will have them immediately available. This not only makes data retrieval faster for each page but also minimises the number of hits to the underlying database. You can get an additional speed boost by caching the Web pages, which rely on the cached DataSet for their values.

By setting a dependency between the cached Web pages and the cached DataSet, the Web pages will be regenerated whenever the DataSet changes. To make sure the DataSet is always current, you should create Update, Insert, and Delete triggers on the tables in the DataSet that modify a control file on the site. Then set a dependency between the cached DataSet and the control file. Whenever the control file changes, the DataSet in the cache will be invalidated. Add code to the Session_OnStart event to check for the cached DataSet, regenerate it if necessary, and place it back in the cache. Then whenever the underlying tables change, the cached DataSet will be regenerated.

Using the right tool for the right job is the best way to create optimised Web applications. Now you have some general guidelines for the right time to use the DataReader and the DataSet in your ASP.NET applications.

Design .NET assemblies with deployment in mind

Posted on May 12th, 2008 in .Net by Ashish  Tagged
When designing .NET assemblies, you can take several potential approaches to managing the granularity of your software development and deployment strategy. Let’s look at a few of the alternatives and their advantages and disadvantages.

.NET assembly represents both a deployment and a loadable unit of code and metadata. To develop systems that can be deployed efficiently, system architects must consider the proper location for each component in a .NET application. Unfortunately, there are no hard and fast rules.

Many times I would consider an assembly boundary to be the boundary between the tiers (presentation, business, and data) of an application as well, but there are just as many cases where I would break the processing tasks handled by a specific tier into two assemblies in order to accommodate a technical requirement.

One component per assembly or project
Unless the component is incredibly complex—which isn’t a good thing anyway—this level of granularity makes development projects difficult to manage. Developers working on even a moderately sized project would find it difficult to code between all of the component files. Moreover, it becomes a deployment and support nightmare since you must deal with versioning issues caused as new versions are introduced into the production environment. Visual Basic developers have grown up working this way since versions of VB that came out before .NET only supported a single class per file. But now that developers using any .NET language can manage multiple classes per file, it makes more sense to group related classes together. The one component per assembly approach also makes the application more resource-intensive at runtime. More components mean longer load times, and more memory and processing overhead to manage them.

One assembly for each tier in an application
For many small to medium-size projects, it makes sense to put all of the components related to an application tier into the same assembly. The logical separation between presentation layer, the business logic layer, and the data access layer is basically an architectural way to minimise the amount of additional work necessary to add features to any layer that can be consumed by another layer. It would seem to make sense to physically separate the components into assemblies that represent each tier of the application. While this sounds good from a theoretical perspective, there are operational reasons against it.

You should consider locating the presentation layer and business logic or business logic and data access layers in the same assembly where it’s required, to ease deployment and systems management concerns. For example, this distribution of functionality will almost always be a requirement in tightly coupled, highly transactional environments where the decrease in an applications’ execution speed created by separating the business logic from the database logic would keep the application from meeting the business need for efficient transaction processing. By deploying separate assemblies for the business and database tiers, you incur the additional overhead of calling cross process and (in a physical three-tier deployment) cross machine, both of which take a considerable toll on the overall speed of the system. Placing two of the three tiers in the same assembly and on the same machine eliminates both of these bottlenecks.

Assemblies by function rather than by tier
In more complex applications, it sometimes makes sense not to create assemblies based on tiers, but instead to create the separation based on function. For example, you should consider grouping business logic and its associated data access logic for a subsystem of a larger solution in a single shared enterprise services package. This way, you run the presentation logic or a business facade on one machine and then consume this subsystem from another machine. Breaking up functions this way also allows the subsystems to be reused in multiple applications more easily than sharing just a data access layer.

When designing your application, take the time to consider how you’ll design assemblies to match your deployment objectives. I’ve seen many cases where the architect makes wise design decisions on how to compartmentalize the functionality of the components in a system, only to have the application fail because of a lack of proper deployment planning.

Secure your ASP.NET applications

Posted on May 12th, 2008 in .Net by Ashish  Tagged

Despite improvements over previous standards, ASP.NET still has its fair share of vulnerabilities. Use these tips from to help secure your ASP.NET applications

From a security standpoint, ASP.NET represents a big improvement over previous incarnations of ASP. With the new platform, developers have easy methods to programmatically validate user input and access to built-in features that lock down an application. Additionally, the .NET runtime’s support of garbage collection and safe strings largely negates the success of traditional attacks. A properly secured .NET application is not only hardened against an attack, but it also limits the amount of damage that an occasional breech can create.

But despite these significant gains, ASP.NET is certainly no security panacea. Security analyst H.D. Moore, who presented three fairly major security holes in ASP.NET at the CanSecWest conference in April, says all these wonderful new features don’t amount to a hill of beans unless developers use them. Moore recommends the following simple security tips for bulletproofing your ASP.NET applications.

Exercise a little configuration control
As a general rule, never place anything in the Web root that you aren’t absolutely comfortable letting a hacker see. The exception here is any file extension that’s mapped to an ISAPI handler, which restricts access to files with extensions like .aspx, .cs, and .vb. On the other hand, files ending in .txt, .csv, and .xml are not automatically protected and can be accessed by anyone browsing the site.

Before placing any new application in production, be sure to disable tracing and debugging support, and make sure the customErrors tag in the web.config file is not set to “off.” These safeguards will help to prevent possible leaks of information such as filenames and paths, and possibly even source code, to the outside world when an error occurs in the application.

Also, clean up your project directories before putting an application in production. When deploying a new application, make sure you remove all of the Visual Studio project and temporary files in the application directory. The .sln and .slo files are not mapped to the ISAPI access filter and can consequently be accessed from the Internet if someone can guess the name of your project, which is usually a trivial task.

Avoid cookieless session management
One of the glaring problems that Moore uncovered during his evaluation of ASP.NET involved a “hijack” vulnerability in applications using the “cookie-less session management” scheme. This scheme embeds a session identifier into every URL to let the server identify a particular client. The trouble is that when a server using this feature receives a previously unknown but otherwise valid session identifier, it creates a new session to go along with it. A clever attacker can take advantage of this by “feeding” a legitimate user a URL containing a known, valid session identifier, which the attacker can use to access the system after it authenticates the duped user.

This is an insidious attack, says Moore, because the URL fed to the user would never look suspicious because only the session ID would be bogus. He recommends that developers simply avoid using cookieless session management until Microsoft removes this vulnerability.

Stay in the sandbox
While the .NET runtime’s managed environment would seem to make traditional attacks like a buffer overrun impossible to pull off, Moore points to the overflow problem he found in the StateServer class as an example of the impossible becoming possible. It appears that there’s a call to unmanaged code somewhere in StateServer with input that isn’t being correctly bounds-checked.

Moore says that developers should stick with .NET’s managed “sandbox” API whenever possible, since any call to unmanaged code could carry similar risks. However, sometimes you need that native code functionality, which brings us to our next tip.

Validate, validate, validate
Despite all the fancy new plumbing, the same old rules regarding validation of user input still apply. Developers should take full advantage of the powerful Validator controls, created by extending the System.Web.UI.Validator interface, to sanitise user input before using it internally. If you’ve never heard of .NET’s validators, you owe it to yourself to read up on them.

Use a cast
When using numeric fields in a database-driven application, make sure you actually cast those variables to an appropriate numeric type before using them. Doing so will prevent SQL insertion attacks by throwing an exception if a user places something nonnumeric into that field. With a little more work, the error handler could be configured to fire off an alert, or write to a log file, almost like a mini application-level intrusion detection system.

Less than trustworthy?
If you must install a Web application on your system that may not be entirely trustworthy, take advantage of the settings available in web.config to run that application under a different user account and then restrict what that account can access. Additionally, you can use the Internet Services Manager to configure the trust level for an application to provide a bit more security. Selecting Low Trust will run an application in its own process space, so that it theoretically will not be able to adversely affect the rest of the system or other Web apps if it is compromised or were to crash for some reason.

.NET attributes are more than decoration

Posted on May 12th, 2008 in .Net by Ashish  Tagged
Among the most confusing and misunderstood elements of the .NET framework are the purpose and uses of attributes. Read this article to see why attributes are a good thing.

Since attributes are new to both C++ and VB developers, there’s no context for easy comparisons to familiar language elements. But the addition of attributes to the Common Language Runtime (CLR) gives developers new abilities to associate information with their classes via an annotation mechanism, which the CLR can then use to operate on the objects at runtime.

Attributes can be used to document classes at design time, specify runtime information (such as the name of an XML field to be used when serialising information from the class), and even dictate runtime behavior (such as whether the class should automatically participate in a transaction). More importantly, you can develop your own attributes that specify architectural standards and enforce their use. In this article, we’ll look at how the CLR uses standard attributes and how and why you should create your own attributes.

What is an attribute?
Many .NET developers get their first exposure to attributes when using templates provided in the Visual Studio environment. For example, when a VB developer creates a new XML Web Service, they get back sample code that defines the Web Service to the CLR using attributes like this:

 _
Public Class Service1
Inherits System.Web.Services.WebService

The class Service1 is said to have been “decorated” with the WebService attribute, and the NameSpace variable has been assigned the value of http://tempuri.org/. The WebService and WebMethod attributes signal the compiler that these attributes should be accessible using the SOAP protocol. As you can see from this example, the purpose of .NET attributes is to signal a compiler or the runtime to generate MSIL or to operate on the MSIL generated, based on metadata representing the attribute. There are many other examples of using attributes to instruct the compiler how to generate the appropriate MSIL, including:

  • Using MarshalAsAttribute to tell the compiler how to marshal method parameters when interoperating with native code.
  • Using COMClassAttribute to mark components as COM so the Visual Basic compiler will generate code allowing a .NET component to be called from COM.
  • Using attributes to describe the resulting assembly with title, version, or description information. The version information is especially important when using signed assemblies and the Global Assembly Cache because you can force the runtime to load only particular versions of assemblies and avoid the COM DLL Hell problem.
  • Mapping class members to specific XML node types when defining XML serialisation.

When compiled, attributes are saved with the metadata of the finished assembly. At runtime, the CLR or your own programs can still use any attributes used by the compiler to control code generation by using reflection to query the assembly for the values specified by an attribute. The feature that makes attributes most powerful, however, is their ability to add additional capabilities to any language hosted within the .NET runtime without making changes to the language compilers.

Adding language capabilities
Attributes are not language specific. Just as we can decorate the HelloWorld method in VB with the WebMethod attribute, there’s a similar implementation for C#:

[WebMethod]
public string HelloWorld()
{
return “Hello World”;
}

Since attributes are language independent, you can define new functionality by creating attributes that inherit from the System.Attribute class. You can then apply that functionality to programs written in any language by simply decorating the appropriate classes, methods, or properties at design time.

For example, one company that I’m working with has defined its own extensions to the CLR that implement metering via performance counters and dynamically created usage statistics. The company has implemented the functionality by creating a set of attributes that can be applied at the module, class, method, event, or property level at design time. Once these attributes are applied, the compiler can include their code to implement this functionality at compile time and the CLR can use reflection to collect the information defined by the attributes at runtime. Using this mechanism allows the company to implement standard metering and usage statistics functionality across all its .NET systems.

Attributes are a good thing
The implementation I’ve discussed here is just one example of how companies are using .NET attributes to standardise operations across their development efforts. .NET Architects who take the time to examine and apply this new technology will undoubtedly find other ways to use it in the applications they design.