C# – Convert txt to xps

When I tried to display a text file on DocumentViewer I met a problem that the DocumentViewer component only supports Fixed Document such as XPS document. This problem put me before a mission to convert my text file into XPS document. I think it may be simple because Microsoft surely supports so that man can convert all types of text file into XPS. Microsoft has created this format, he can not put his developers into trouble but I am wrong. After searching with Google I found out that there is no easy way, for example with one line of code, to convert text file to XPS document so I must find out a walk-around to solve it.
Instead of converting text file to XPS document, I decide to create a new XPS document and insert the content of text file into it. To create XPS document, we should understand a little about its structure as I illustrate with very basic concept in figure bellow

As described in figure above, to create a XPS document, we will follow these steps:
– Create a package and XPS document
– Create document sequence of this package and add fixed document to to document sequence
– For each document, add pages and these pages contains our content.
– During creating pages, we must insert relevant resources, for example Fonts, Images, …
Following these steps I used following code snippet

1. Create a package and XPS document

using (Package pckXPS = Package.Open(strDestFile))
	XpsDocument xdDocument = new XpsDocument(pckXPS);

2. Create document sequence of this package and add fixed document to to document sequence

IXpsFixedDocumentSequenceWriter ifdswDocumentSequence = xdDocument.AddFixedDocumentSequence();
IXpsFixedDocumentWriter ifdwDocument = ifdswDocumentSequence.AddFixedDocument();

3. For each document, add pages and these pages contains our content

IXpsFixedPageWriter ifpwPage = ifdwDocument.AddFixedPage();
dictResources = AddResourcesToPage(ifpwPage);
	lstLineSet[nIndex], dictResources);

4. Add content to page and set font

List<XpsResource> xpsFonts = lstResources["XpsFont"];
// Element are indented for reading purposes only
writerXML.WriteAttributeString("Width", cnst_nPageWidth.ToString());
writerXML.WriteAttributeString("Height", cnst_nPageHeight.ToString());
writerXML.WriteAttributeString("xml:lang", "en-US");

for(int nIndex=0; nIndex < strLine.Length; nIndex++)
	writerXML.WriteAttributeString("Fill", "#ff000000");
		"FontUri", xpsFonts[0].Uri.ToString());
	writerXML.WriteAttributeString("FontRenderingEmSize", "18");
	writerXML.WriteAttributeString("OriginX", cnst_nStartXOffset.ToString());
	writerXML.WriteAttributeString("OriginY", (cnst_nStartYOffset + nIndex*cnst_nLineSpacing).ToString() );
	writerXML.WriteAttributeString("UnicodeString", strLine[nIndex]);

I can convert text file to XPS document with code above but there are a lot of bugs to be solved for example encoding and line overflowing as in figure below

The complete source code of this tool you can download here “Txt To XPS“. I will try to solve the bugs above, if you know how man can solve them then don’t hesitate to share it here.

.Net Reflector Pro is out

Although I gave up .net reversing for a long time to concentrate on .net programming technique, I always follow all valuable progress made by all reverser around the world. Today I was really shocked with new version of .net reflector released by Red Gate. This version called pro version and we must pay to use. What makes me really impressed are following features.

.NET Reflector Pro is an add-in to Visual Studio that lets you debug third-party code and assemblies, even if you don’t have the source.
* Integrates the power of .NET Reflector into Visual Studio
* Decompile third-party assemblies from within VS
* Step through decompiled assemblies and use all the debugging techniques you would use on your own code

More details you can read here http://www.red-gate.com/products/reflector/ . I believe that after this release, many .net application will be put in risk. I still do not know how this add-in handle obfuscated or protected assembly. For example an assembly whose code was encrypted and decrypted at run-time how will .net reflector work? There is a trial version but I am now pretty lazy to test.

A video tutorial you can find here http://www.red-gate.com/products/reflector/video_pro.htm

Update 23.02.2010
A FREE (NOT PRO) newest version you can download here http://downloads.red-gate.com/reflector.zip

C# – Create Excel file from DataTable without using Excel Object

Microsoft Excel is beloved tool to work with tables. Therefore it is really valuable for end user if an application can export its data into Excel. However today a lot of business application are web application which cause a problem with Excel because the Excel is not installed on web server. Export data to Excel with COM Remote Control of Excel Object Model does not always work fast and reliable.

Continue reading C# – Create Excel file from DataTable without using Excel Object

C#, WPF – Play swf in wpf application

When I was trying to extract the first frame of SWF file into image I discovered that there is a small problem when we try to host a SWF file in WPF application because WPF does not allow us to integrate ActiveX control directly in its application. To enable interaction through ActiveX control, we must do a walkthrough with WindowsFormsHost. In this small example below I would like to guide you step by step to host a SWF file in your WPF application.

1. In Visual Studio, File –> New –> Project –> Windows Forms Control

2. Set Platform target to x86

3. In Visual Studio, right click on Toolbox window, then “Choose Items”

4. Navigate to COM components tab and choose Shockwave Flash Object. Press OK.

5. Drag “Schockwave Flash Object” from Toolbox to our UserControl and change its name to axShockwaveFlash. Rename our UserControl to FlashAxControl and add following code to it.

public partial class FlashAxControl : UserControl
	public FlashAxControl()

	public new int Width
		get { return axShockwaveFlash.Width; }
		set { axShockwaveFlash.Width = value; }

	public new int Height
		get { return axShockwaveFlash.Height; }
		set { axShockwaveFlash.Height = value; }

	public void LoadMovie(string strPath)
		axShockwaveFlash.LoadMovie(0, strPath);

	public void Play()

	public void Stop()

6. Build our UserControl. Start new WPF Application and reference to our UserControl, System.Windows.Forms and WindowsFormsIntegration as following

7. Set Platform Target to x86

8. Add following code to play SWF in our application

string strFilePath = @"e:\temp.swf";
SWFFileHeader swfFile = new SWFFileHeader(strFilePath);
this.Width = swfFile.FrameSize.WidthInPixels;
this.Height = swfFile.FrameSize.HeightInPixels;

WindowsFormsHost host = new WindowsFormsHost();
FormFlashLibrary.FlashAxControl player = new FormFlashLibrary.FlashAxControl();

//the Windows Forms Host hosts the Flash Player
host.Child = player;

//the WPF Grid hosts the Windows Forms Host

//set size
player.Width = (int) this.Width;
player.Height = (int) this.Height;

//load & play the movie

The grdMain is the grid of WPF Application. The complete source code you can download at “Form Flash Library” and “WPF Play SWF”.
If you want to play SWF in Windows Form Application, you can read at this blog “C# – How to play a .swf file?”

C#, WPF – Hit Testing Example

When we create interactive 2D drawing applications in WPF, we can deal directly with the user’s
interaction with the graphics objects using mouse event handlers. However, WPF provides powerful hit-
testing for graphics objects through the static VisualTreeHelper.HitTest method.
In order to use this advanced hit-testing feature, we need to create a callback. The VisualTreeHelper
will then walk through your visuals from top to bottom. Whenever it finds a match, it calls the callback
with the details. We can then choose to stop the search or to continue until no more visuals remain
The following example will illustrate how to use this advanced feature. In this example we have many rectangles overlapping with each other, when we click on a point on windows there is a popup telling us at point how many rectangles are locating.
Use Microsoft Expression Blend to draw many overlapped rectangle as proposed as below.

Name our grid as grdMain and add handler for MouseLeftButtonDown.

<Grid x:Name="grdMain" MouseLeftButtonDown="cvMain_MouseLeftButtonDown">

In the function cvMain_MouseLeftButtonDown, we define the hit area and call the function VisualTreeHelper.HitTest to find out the intersection area between our hit area and painted rectangle

private void cvMain_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
	Point ptCurrent = e.GetPosition(grdMain);
	m_egHitArea = new EllipseGeometry(ptCurrent, 1, 1);
	VisualTreeHelper.HitTest(grdMain, null, new HitTestResultCallback(HitTestCallback), new GeometryHitTestParameters(m_egHitArea));
	if (m_lstHitList.Count > 0)
		MessageBox.Show("You hit " + m_lstHitList.Count + " rectangles");

We have expanded our hit-test area using an EllipseGeometry. When the user clicks on the grid, the program starts the hit-test process by calling HitTestCallback. The VisualTreeHelper will then walk through visuals from top to bottom. If it hits any rectangle,the rectangle will be added to m_lstHitList.

public HitTestResultBehavior HitTestCallback(HitTestResult htrResult)
	IntersectionDetail idDetail = ((GeometryHitTestResult)htrResult).IntersectionDetail;
	switch (idDetail)
		case IntersectionDetail.FullyContains:
			return HitTestResultBehavior.Continue;
		case IntersectionDetail.Intersects:
			return HitTestResultBehavior.Continue;
		case IntersectionDetail.FullyInside:
			return HitTestResultBehavior.Continue;
			return HitTestResultBehavior.Stop;

Usually, the HitTestResult object provides just a single property (VisualHit), but we can cast it to one of two derived types, depending on the type of hit-test we’re performing.
If we’re hit-testing a point, we can cast HitTestResult to PointHitTestResult, which provides a
PointHit property that returns the original point you used to perform the hit-test. If you are hit-testing a
Geometry object (or shape), as you are in this example, you can cast HitTestResult to
GeometryHitTestResult and get access to the IntersectionDetail property as example above.

The complete source code of this example you can download “Hit Testing Example

This example I extracted from book “Practical WPF Charts and Graphics“. Password: 4aedF0xFZN0BBPE