Serge's Technology View

Talk about Technologies, Software Architecture and Management

Posts Tagged ‘c#’

How to set default file name for export from CrystalReportViewer in ASP.Net

I have had nice discussion about a new Crystal Reports based web-site today. And everything seems to be fine… Except users want to see a proper default name for the exported files…

Environment:

  • Crystal Reports 2008 engine
  • IIS 7
  • ASP.Net 3.0 page with CrystalReportViewer (CRV) being used to show report passed by parameter

When trying export as PDF (just an example), CRV defaults the name of the file to CrystalReportViewer1.pdf.
Not very nice since associated RPT name is MyVeryOwnReport.rpt and I have many other which I would expect export file at least inherit.

One would expect that Viewer would have a property allowing specify default export name. Not so fast… there is no such thing today exists.

After some head scratching and research, it just happen that Default Export File Name is actually based of the ID property value of the CRV which is still named as CrystalReportViewer1.

Options?

  1. Rename ID value of the control as something else. Still, if we use just one page and load reports dynamically, then it would not help much.
    // ReportPreview.aspx file
    <CR:CrystalReportViewer ID="MyVeryOwnExportFile" />
  2. Another option is to populate Default Export file name in the code
    // ReportPreview.aspx.cs file
    protected void Page_Init(object sender, EventArgs e)
    {
         ...
        // Load report here
        ...
        CrystalReportViewer1.ID = "MyVeryOwnExportFile";
    }

    It is important to have it set before any code would use it to manipulate a page view state and create references.

  3. Trying manually set export options for the Report instance, would not help much unfortunately since viewer would disregard it.
  4. Off course there is always an option of coding export functionality yourself and bypass built-in logic…

This concludes another Crystal Reports dance session.

File locks or when garbage collection goes bad

With introduction of garbage collection (System.GC name space) in .Net, life of the Windows programmer become easy – no need to worry about releasing objects, code become simpler, etc.
In “old” time one would need to use Interfaces to achieve similar functionality and it does have some advantage even over GC – immediate garbage collection or release of allocated resources/objects.

When writing code in .Net some of us take many things for granted and not always keep in mind that many operations are performed in the context of the unmanaged code or in the “old way”…

File operations or legacy code wrappers are perfect example.
Just because library is available as managed code, it does not mean that everything has ability to “self-heal”.
For example in code file is open for edit with lock being placed.
If the file in not closed explicitly, it would be a responsibility of the owner process to release the lock at the time of releasing associated resources – when process is destroyed.

With garbage collection, just because we are no longer using/owning the process/object, it does not mean that it has been destroyed immediately after. GC management core will release object when it “feels” fit, therefore introducing latency into the process.

Off course, proper way would be to be more careful within the code and make sure any locks are released in managed and predictable way: Open/Close, Lock/Unlock, … Easy solution, but not always accessible, especially when working with 3rd party libraries.

So instead, we can force GC manager to “collect garbage” in-place with the following small code:

// See code follow up below
System.GC.Collect();
System.GC.WaitForPendingFinalizers();

What does it do?
First call will instruct GC manager to start the process (1), while second (2) will make sure that we wait for process to be completed.

In the case of the file locks, only after GC has released process which placed the lock in the first place, we can manipulate with the file (ex. delete, rename, move).

Assert is your friend… not an end-user’s

As a long time Delphi and C# programmer one become used to some features of the language and may not go deep into “philosophical” thinking about such features. This often happen with Asserts

What is Assert or Assertion?

By its definition Assert:

  • state categorically
  • affirm: to declare or affirm solemnly and formally as true
  • insist: assert to be true
  • In Computing (wiki): “an assert is a predicate (i.e., a true–false statement) placed in a program to indicate that the developer thinks that the predicate is always true at that place”

In general, using assert in the code proven to be useful in many situations because it “checks for a condition and outputs the call stack if the condition is false” and it could help to debug some strange situations in the code.

Assert is your friend

This method is for programmers to use. But what happen often when something is convenient, it started to be used excessively. Why it is happening?

Let’s look at the declaration of Assert in C# (3.x). There are two versions of the Assert(): Debug.Assert() and Trace.Assert(), both in System.Diagnostics namespace.

// Checks for a condition and outputs the call stack
// if the condition is false

[ConditionalAttribute("TRACE")]
public static void Assert(bool condition)

[ConditionalAttribute("TRACE")]
public static void Assert(bool condition, string message)

[ConditionalAttribute("DEBUG")]
public static void Assert(bool condition)

[ConditionalAttribute("DEBUG")]
public static void Assert(bool condition, string message)

As we can see from above code, Assert is to be used for Testing and Debugging and therefore should not be used as a way to present any information to the end-user.

Helping yourself

As useful as it seems, even then Assert infrastructure may not be used to full extend. In the sample declarations above we can see that logic can be invoked with and without providing any additional information.
Imagine how useful is a message “Project raised an Assert in line X” compare to “Project raised an Assert with the Message in line X”.
First option gives you idea where something failed, where second actually tells you what went wrongand where. Let’s use power of the tool-set and provide ourselves with useful information.

Assert is NOT for an end-user

I was asked recently (this seems to be a ongoing discussion) – “Why a programmer should not be using asserts as a regular approach in code conditions validation even when it comes to a production code?”

By default, Assert would show a message box with some information and the current Call Stack. This information, while being helpful to the developer, would not tell much to the user.

With custom TraceListener introduced, message can be hidden from the user and information could be stored, but it is not how it should be used by definition.

If information is expected to be presented to the user in any form, it could be achieved in a form not an exceptional, intended for debugging, situation, but by using regular methods: message box, application log, Windows event log, etc.
Even in the case of component development it is desired to use exceptions (raise/throw) to “bubble” proper message to the error handling layer.

The throw statement is used to signal the occurrence of an anomalous situation (exception) during the program execution.

Assert is a conditional logic

Last, final and probably major concern here is that in Release environment Debug and even Trace functionality would be disabled and therefore, any code/logic which depend on Assert() would be suppressed and all the nice validations became worthless (see declaration above)… and Access Violation errors starting pop up unexpectedly.

ASP.Net/WF : New built-in .Net Charting control

I was always for a “built-in” support of features in modern development environment. Even if it comes in basic form, we, as programmers, should have ability to do “basic” stuff without 3rd party involvement.

There are plenty of 3rd party solutions on the market which would help you include some kind of charting support with your ASP pages and WinForms applications – ChartFX, ComponentArt’s Charting, Dundas Chart - these are just few from many available on the market today.

As it turned out, Microsoft has decided to add out-of-the-box support for Charting as well - <asp:chart runat=”server”/>.
Read about it here - New ASP.NET Charting Control: <asp:chart runat=”server”/> by Scott Guthrie – everything you need to know about the .Net 3.5 framework new addition.

For  additional information also visit Alex Gorev’s blog.

Note 1: Even though caption says it is ASP.Net solution, in the original you would find link to WinForms sample as well.
Note 2: Do not worry about Dundas copyright – “Microsoft acquired Dundas Data Visualization Intellectual Property in April 2007.”

Valid XHTML 1.0 Transitional  Valid CSS!