Creating a proprietary invoice editor

In this post we will show how to create an invoice editing application (using MindFusion.Reporting) for the end users of an organization. The source code of the sample is available for download from here:

https://mindfusion.eu/_samples/ReportingInvoiceEditor.zip

Introduction
We start off by creating a new Windows Forms Application in Visual Studio 2010 or later. Change the target framework of the application to “.NET Framework 4” (or later). The ReportEditor component that will be used as an in-place invoice editor requires at least .NET 4.

Add the ReportEditor component to the main form, set its Dock to Fill.

The invoice template
The invoice template displayed by the application is stored in an XML file. The original template is created beforehand and is located in Invoice.xml. All modifications to the template done by the end users will be stored back to the XML file upon exiting the application. Add the following line to the main form’s constructor to load the invoice template when the main form is constructed:

reportEditor1.OpenReport(@"Invoice.xml");

Adding the data source
From the “Data -> Add New Data Source…” menu in Visual Studio create a new data source from the nwind.mdb database. Select the Orders table and the Invoices query in the Data Source Configuration Wizard. In the XML Schema (nwindDataSet.xsd) ensure that there is a relation between the Orders and Invoices table adapters. The relation should link the OrderID fields of the two tables and should be named “Orders_Invoices”. Build the application so that Visual Studio creates the classes for the data set and the selected table adapters. Go back to the main form designer and add nwindDataSet, InvoicesTableAdapter, and OrdersTableAdapter components to the form. In the constructor of the form, add the following lines in order to fill the data set with the data from the source database:

invoicesTableAdapter1.Fill(nwindDataSet1.Invoices);
ordersTableAdapter1.Fill(nwindDataSet1.Orders);

In addition, we need to register the two tables as data sources in the report editor. This is essential because these data sources are used by the invoice report. It is also important that the data sources are registered before the report is initially loaded through the OpenReport method.

reportEditor1.AddDataSource(nwindDataSet1.Orders, "Orders");
reportEditor1.AddDataSource(nwindDataSet1.Invoices, "Invoices");

Saving the template
Override the OnClosing event of the form and add the following line to ensure that all changes to the invoice template are written back to the XML file:

reportEditor1.SaveReport(@"Invoice.xml");

Adding the menu
Create a menu strip for the application with the following structure:

  • File
    • Print
    • Print Preview
    • Exit
  • Edit
    • Undo
    • Redo

Add the following event handlers for the menu items:

private void printToolStripMenuItem_Click(object sender, EventArgs e)
{
	var printer = new ReportPrinter();
	printer.Report = reportEditor1.Report;
	printer.Report.Run();
	printer.Print();
}

private void printPreviewToolStripMenuItem_Click(object sender, EventArgs e)
{
	var printer = new ReportPrinter();
	printer.Report = reportEditor1.Report;
	printer.Report.Run();

	var preview = new PrintPreviewForm();
	preview.Document = printer;
	preview.ShowDialog();
}

private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
	Close();
}

private void undoToolStripMenuItem_Click(object sender, EventArgs e)
{
	reportEditor1.Undo();
}

private void redoToolStripMenuItem_Click(object sender, EventArgs e)
{
	reportEditor1.Redo();
}

The image below illustrates the running application:

reporting-invoiceeditor

The MindFusion.Reporting component can be downloaded from here:

https://www.mindfusion.eu/ReportingTrial.zip

Enjoy!

MindFusion Controls on NuGet

All MindFusion components for WinForms, WPF and Silverlight are now available as NuGet packages. The following table lists the NuGet IDs of the individual products:

Product NuGet ID
MindFusion.Charting for WinForms
MindFusion.Diagramming for WinForms
MindFusion.Gauges for WinForms
MindFusion.Pack for WinForms
MindFusion.Reporting for WinForms
MindFusion.Scheduling for WinForms
MindFusion.Spreadsheet for WinForms
MindFusion.Charting
MindFusion.Diagramming
MindFusion.Gauges
MindFusion.Pack
MindFusion.Reporting
MindFusion.Scheduling
MindFusion.Spreadsheet
MindFusion.Charting for WPF
MindFusion.Diagramming for WPF
MindFusion.Gauges for WPF
MindFusion.Pack for WPF
MindFusion.Reporting for WPF
MindFusion.Scheduling for WPF
MindFusion.Spreadsheet for WPF
MindFusion.Charting.Wpf
MindFusion.Diagramming.Wpf
MindFusion.Gauges.Wpf
MindFusion.Pack.Wpf
MindFusion.Reporting.Wpf
MindFusion.Scheduling.Wpf
MindFusion.Spreadsheet.Wpf
MindFusion.Charting for Silverlight
MindFusion.Diagramming for Silverlight
MindFusion.Gauges for Silverlight
MindFusion.Pack for Silverlight
MindFusion.Reporting for Silverlight
MindFusion.Scheduling for Silverlight
MindFusion.Charting.Silverlight
MindFusion.Diagramming.Silverlight
MindFusion.Gauges.Silverlight
MindFusion.Pack.Silverlight
MindFusion.Reporting.Silverlight
MindFusion.Scheduling.Silverlight

The complete list of MindFusion products on NuGet can be found here: https://www.nuget.org/profiles/MindFusion.

The NuGet manager is available for Visual Studio 2010, Visual Studio 2012, and Visual Studio 2013 and can be downloaded from here: https://www.nuget.org/.

To install a package, run the following command in the Package Manager Console (accessible from the Visual Studio menu: Tools → NuGet Package Manager → Package Manager Console):

PM> Install-Package 

Where <id> is the NuGet ID of the package. For example, to install MindFusion.Diagramming for WinForms, use:

PM> Install-Package MindFusion.Diagramming

Enjoy!

MindFusion.Gauges: Creating a Stopwatch

This blog will demonstrate how to create a simple stopwatch based on the OvalGauge component (part of MindFusion.Charting for WinForms and MindFusion.Pack for WinForms).

Introduction
We start off by creating a new Windows Forms Application in Visual Studio and adding an OvalGauge control to the main form. Set the gauge’s Dock property to Fill and its Name to “stopwatch”.

Setting up the scales
The stopwatch will contain two scales – a bigger one, which should display the seconds, and a smaller one – for the minutes. The minute scale will be positioned in the upper half of the gauge area. The scales can be created and configured in design-time – through the property grid – or in code. In the Property grid navigate to the Scales property of the OvalGauge control and click the ‘…’ button or hit F4 to open the OvalScale Collection Editor. In this editor, add two scales by pressing the ‘Add’ button. Edit the following properties of the second scale:

Name = "SecondsScale"
StartAngle = -90
EndAngle = 270
StartWidth = 0
EndWidth = 0
Stroke = Color=Black, Width=0

MinorTickSettings.ShowTicks = True
MinorTickSettings.Count = 4
MinorTickSettings.Stroke = Color=(85, 85, 85), Width=0
MinorTickSettings.TickShape = Line
MinorTickSettings.TickWidth = 5%
MinorTickSettings.TickAlignment = OuterInside

MiddleTickSettings.ShowLabels = False
MiddleTickSettings.Count = 5
MiddleTickSettings.Stroke = Color=(0, 0, 0), Width=0
MiddleTickSettings.TickShape = Line
MiddleTickSettings.TickWidth = 8%
MiddleTickSettings.TickAlignment = OuterInside

MajorTickSettings.Count = 12
MajorTickSettings.FontFamily = "Calibri"
MajorTickSettings.FontSize = 20%
MajorTickSettings.FontStyle = Regular
MajorTickSettings.LabelOffset = 9%
MajorTickSettings.LabelRotation = None
MajorTickSettings.ShowMaxValueTick = Never
MajorTickSettings.Stroke = Color=(0, 0, 0), Width=2
MajorTickSettings.TickShape = Line
MajorTickSettings.TickWidth = 12%
MajorTickSettings.TickAlignment = OuterInside

In addition, add four custom intervals to the MajorTickSettings.CustomIntervals collection, representing the intervals [0-0], [15-15], [30-30], and [45-45] respectively. Set the Fill property of each custom interval to (187, 31, 33). These objects indicate that the labels inside the corresponding intervals will be colored in red.

For simplicity, the properties of the minute scale are omitted. They are similar to those of the second scale, the main difference being that the minute scale is positioned and sized through the ScaleRelativeCenter and ScaleRelativeRadius properties.

Adding pointers

In the OvalScale Collection Editor dialog add a pointer to each of the two scales. To do this, select the scale, navigate to the Pointers property in the grid and press the ‘…’ button or F4. This will open the Pointer Collection Editor dialog. Name the pointer of the minute scale “MinutesPointer” and the one in the second scale – “SecondsPointer”. We will use these names later in code to identify and search for the pointers. Set the width of the two pointers to 30% and 20% respectively. Then close all editors. We will custom draw the pointers so there is no need to specify any more properties.

To draw the pointers, handle the PrepaintPointer event of the OvalGauge class. This event is raised for each pointer in the gauge individually before the pointer is painted by the control. The event can be used to cancel the default pointer drawing by setting the CancelDefaultPainting to true. A simplified version of the event handler that paints the two pointers is listed below.

private void stopwatch_PrepaintPointer(object sender, PrepaintEventArgs e)
{
    e.CancelDefaultPainting = true;

    Brush fill = new SolidBrush(Color.FromArgb(175, 8, 9));

    GraphicsState state = e.Graphics.Save();
    e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
    e.Graphics.ScaleTransform(e.Element.RenderSize.Width, e.Element.RenderSize.Height);

    if (e.Element.Name == "SecondsPointer")
    {
         var polygon = new PointF[]
         {
             new PointF(0.1f, 0.35f),
             new PointF(1, 0.45f),
             new PointF(1, 0.55f),
             new PointF(0.1f, 0.65f)
         };
         var ellipse1 = new RectangleF(0, 0, 0.2f, 1f);

        // Draw the pointer itself
        e.Graphics.FillPolygon(fill, polygon);
        e.Graphics.FillEllipse(fill, ellipse1);
    }
    else if (e.Element.Name == "MinutesPointer")
    {
        var polygon = new PointF[]
        {
            new PointF(0.15f, 0.35f),
            new PointF(1, 0.45f),
            new PointF(1, 0.55f),
            new PointF(0.15f, 0.65f)
        };
        var ellipse1 = new RectangleF(0, 0, 0.3f, 1f);

        e.Graphics.FillPolygon(fill, polygon);
        e.Graphics.FillEllipse(fill, ellipse1);
    }

    e.Graphics.Restore(state);
    fill.Dispose();
}

Activating the stopwatch

Now we need means to start, stop, and reset the stopwatch. First, declare two member variables in the form – startTime and elapsedTime, of type DateTime and TimeSpan respectively. The first variable will store the time when the stopwatch was most recently started. The second variable will store the total elapsed time.

Go to the Visual Studio designer, select the form, navigate to the Padding property and change its value to “0, 0, 0, 50”. The gauge will shrink, leaving some space at the bottom. Add two buttons to the form, below the gauge, and set their texts to “Start” and “Reset” respectively. In addition to the buttons, add a Timer component to the form. When the stopwatch is started, we will use this timer to update the pointers. Handle the Click events of the two buttons. The first button will start/stop the stopwatch. The second button will reset the stopwatch. Here is the event handlers of the two buttons:

private void button1_Click(object sender, EventArgs e)
{
    if (timer1.Enabled)
    {
        UpdateTime();
        UpdatePointers();

        timer1.Stop();
        button1.Text = "Start";
    }
    else
    {
        button1.Text = "Stop";
        startTime = DateTime.Now;
        timer1.Start();
    }
}

private void button3_Click(object sender, EventArgs e)
{
   elapsedTime = TimeSpan.Zero;
   UpdatePointers();
}

Depending on the current state of the application, the first button will either start or stop the timer. The second button will set the elapsed time to 0:00, effectively resetting the stopwatch. Both buttons rely on the method UpdatePointers, which adjusts the gauge pointers according to the currently elapsed time. This method uses the GetElementByName method of the gauge to access the pointers by name and update their values:

private void UpdatePointers()
{
    var minutesPointer = (Pointer)stopwatch.GetElementByName("MinutesPointer");
    var secondsPointer = (Pointer)stopwatch.GetElementByName("SecondsPointer");
    minutesPointer.Value = (float)elapsedTime.TotalMinutes;
    secondsPointer.Value = (float)Math.Round((float)(elapsedTime.TotalSeconds % 60), 1);
}

Finally, handle the Tick event of the timer.

private void timer1_Tick(object sender, EventArgs e)
{
    UpdateTime();
    UpdatePointers();
}

The image below illustrates the running stopwatch:

gauge-stopwatch

The source code of the sample is available for download from here:
https://mindfusion.eu/_samples/GaugesStopwatch.zip

The MindFusion.Charting for WinForms component can be downloaded from here:
https://www.mindfusion.eu/ChartWinFormsTrial.zip

About MindFusion.Charting for WinForms: A professional programming component for WinForms, which lets you create remarkable charts and gauges fast and easy. The tool supports all major chart types – line, pie, radar and bar – and numerous variations of them – column, area, bubble, polar, doughnut etc, as well as oval and linear gauges.

MindFusion.Spreadsheet: Formatted Text

Starting with version 1.2, MindFusion.Spreadsheet adds support for formatted text. The control can import, create, display and export formatted texts. In this blog we will demonstrate how to create formatted text in a cell.

Introduction

As with all previous blogs we start off by creating a new Windows Forms Application in Visual Studio and adding a WorkbookView control to the main form. The WorkbookView displays a Workbook with a single worksheet.

Creating the formatted text

Formatted texts are created programmatically by instantiating from the FormattedText class. The class provides a constructor, which can initialize the formatted text from a markup string, similar to HTML. The string supports the following tags: <fontname=”fontname“>, <fontsize=”fontsize“>, <i>, <b>, <u>, <s>, and <color=”#rrggbb“>. The following code creates several formatted texts:

worksheet.Cells["A1"].Data = new FormattedText("The meeting is <color=\"#ff0000\">important</color=\"#ff0000\">!");
worksheet.Cells["A2"].Data = new FormattedText("<fontsize=\"18\">A title <fontsize=\"8\">(1994)");
worksheet.Cells["A3"].Data = new FormattedText("This text contains some keywords that are highlighted.");</fontsize=\"8\"></fontsize=\"18\">

Exporting

The formatted texts are exported to all supported formats, including HTML, PDF, XLSX, ODS, image, and so on. The following image illustrated the formatted texts created earlier exported to HTML:

spreadsheet-formattedtext

The source code of the sample is available for download from here:

https://mindfusion.eu/_samples/SpreadsheetFormattedTexts.zip

The trial version of MindFusion.Spreadsheet for WinForms can be downloaded from here:

Download MindFusion.Spreadsheet for WinForms Trial Version

About MindFusion.Spreadsheet for WinForms: A powerful .NET spreadsheet component with great capabilities for editing, styling and formatting large amounts of data.

MindFusion.Spreadsheet: Convert XLSX to PDF

In this blog we will discuss how to convert an existing XSLX file to PDF using MindFusion.Spreadsheet for WinForms.

Introduction

As with all previous blogs we start off by creating a new Windows Forms Application in Visual Studio and adding a WorkbookView control to the main form. The WorkbookView displays a Workbook with a single worksheet.

Importing the XLSX file

In MindFusion.Spreadsheet XLSX files are imported using instances of the ExcelImporter class. For the purposes of this blog we will import an existing report.xlsx file, contained in the zip of the sample. To import this file, use the following code:

var importer = new ExcelImporter();
importer.Import(Path.Combine(path, "report.xlsx"), workbook1);

Creating the PDF

To create a PDF file from the imported worksheet, create an instance of the PdfExprter class and call its Export method:

var exporter = new PdfExporter();
exporter.EnableGridLines = true;
exporter.Export(workbook1.Worksheets[0], Path.Combine(path, "report.pdf"));

The following image illustrates the result of the conversion:

spreadsheet-pdfexport

The source code of the sample is available for download from here:

https://mindfusion.eu/_samples/SpreadsheetConvertPdf.zip

The trial version of MindFusion.Spreadsheet for WinForms can be downloaded from here:

Download MindFusion.Spreadsheet for WinForms Trial Version

About MindFusion.Spreadsheet for WinForms: A powerful .NET spreadsheet component with great capabilities for editing, styling and formatting large amounts of data.