New Silverlight Theme - JetPack

Update: This blog has been moved to http://brandonzeider.me/2010/microsoft-net/new-silverlight-theme-jetpack/.

The Silverlight team at Microsoft, in conjunction with Pixel Lab, has released a new theme call JetPack. This theme joins the three existing themes: Cosmopolitan, Accent Color and Windows 7.

JetPack Theme Screenshot

JetPack Theme

Links

Demo of the JetPack theme

Download JetPack Theme - Includes resource dictionaries and Visual Studio project templates

Tim Heuer's blog post detailing the release of JetPack

John Papa and Tsitsi Gora on an episode of Silverlight TV detailing how to customize the Silverlight themes.

 

Bookmark and Share dotnetshoutout
Tags: ,
Categories: Microsoft .NET | Silverlight

Permalink E-mail | Kick it! | DZone it! | del.icio.us Comments (1) Post RSSRSS comment feed

Convert Word to PDF

Update: this blog has been moved to http://brandonzeider.me/2010/microsoft-net/convert-word-to-pdf/.

I recently had a requirement to convert Microsoft Word documents to PDF. I don't mind purchasing libraries for things like this if I have to, as there are several good ones: ABDpdf and Aspose come immediately to mind (there are certainly others). However my preference is always to limit the amount of third party code that I use, so I went in search of a way to do it natively within .NET.

Solution

Pretty simple solution - the sample class below is all you need. You will need to add a reference to the Microsoft.Office.Interop.Word assembly version 12.0.0.0 (or higher) for this to work. Please note that you also need to have Microsoft Word installed on the machine that executes this code. To use, you simply pass in the file path to the Word document that you'd like to convert and the file path where you'd like your PDF to be saved. That's it. You can of course modify this class to fit your needs.

Code

using System;
using Microsoft.Office.Interop.Word;

namespace Framework
{
    public sealed class Conversion
    {
        /// <summary>
        /// Converts the word to PDF.
        /// </summary>
        /// <param name="wordDocumentFilePath">The word document file path.</param>
        /// <param name="pdfFilePath">The PDF file path.</param>
        /// <returns></returns>
        public static bool ConvertWordToPdf(string wordDocumentFilePath, string pdfFilePath)
        {
            return PerformConversion(wordDocumentFilePath, pdfFilePath, WdExportFormat.wdExportFormatPDF);
        }

        /// <summary>
        /// Performs the conversion.
        /// </summary>
        /// <param name="sourceDocPath">The source doc path.</param>
        /// <param name="targetFilePath">The target file path.</param>
        /// <param name="targetFormat">The target format.</param>
        /// <returns></returns>
        private static bool PerformConversion(string sourceDocPath, string targetFilePath, WdExportFormat targetFormat)
        {
            if (!System.IO.File.Exists(sourceDocPath))
                throw new Exception("The specified source document does not exist.");

            Application wordApplication = new Application();
            Document wordDocument = null;

            bool success = false;
            object paramSourceDocPath = sourceDocPath;
            object paramMissing = Type.Missing;
            bool paramOpenAfterExport = false;
            WdExportOptimizeFor paramExportOptimizeFor = WdExportOptimizeFor.wdExportOptimizeForOnScreen;
            WdExportRange paramExportRange = WdExportRange.wdExportAllDocument;
            int paramStartPage = 0;
            int paramEndPage = 0;
            WdExportItem paramExportItem = WdExportItem.wdExportDocumentContent;
            bool paramIncludeDocProps = true;
            bool paramKeepIRM = true;
            WdExportCreateBookmarks paramCreateBookmarks = WdExportCreateBookmarks.wdExportCreateWordBookmarks;
            bool paramDocStructureTags = true;
            bool paramBitmapMissingFonts = true;
            bool paramUseISO19005_1 = false;

            try
            {
                wordDocument = wordApplication.Documents.Open(ref paramSourceDocPath, ref paramMissing, ref paramMissing, ref paramMissing,
                    ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing,
                    ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing);

                if (wordDocument != null)
                {
                    wordDocument.ExportAsFixedFormat(targetFilePath, targetFormat, paramOpenAfterExport, paramExportOptimizeFor,
                        paramExportRange, paramStartPage, paramEndPage, paramExportItem, paramIncludeDocProps, paramKeepIRM, paramCreateBookmarks, paramDocStructureTags,
                        paramBitmapMissingFonts, paramUseISO19005_1, ref paramMissing);

                    success = true;
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                if (wordDocument != null)
                {
                    wordDocument.Close(ref paramMissing, ref paramMissing, ref paramMissing);
                    wordDocument = null;
                }

                if (wordApplication != null)
                {
                    wordApplication.Quit(ref paramMissing, ref paramMissing, ref paramMissing);
                    wordApplication = null;
                }

                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }

            return success;
        }
    }
}

 

Creative Commons License
This work is licensed under a Creative Commons Attribution 3.0 Unported License.

 

Bookmark and Share dotnetshoutout
Tags: ,
Categories: Microsoft .NET

Permalink E-mail | Kick it! | DZone it! | del.icio.us Comments (0) Post RSSRSS comment feed

Design Pattern How-To: Singleton

Update: this blog has been moved to http://brandonzeider.me/2010/design-patterns/design-pattern-how-to-singleton/

The Singleton Design Pattern is one of the easiest design patterns to understand, and also one of the most useful in my opinion. When done correctly, the singleton pattern ensures that one and only one instance of a class is instantiated. In this post we will cover the singleton pattern, how to make it thread safe, and show a simple implementation. If you are new to design patterns, see my introductory post on the Factory pattern for an explanation.

The singleton pattern is a Creational Pattern that deals with how and when objects are created. They have many uses, and are often found as components in other design patterns. The pattern can be used when only one instance of an object is desired, either out of necessity or for performance reasons. For our example, we will create a class to store common data that can be safely accessed from any class on any thread. Please note that there are many ways to accomplish thread-safety, this post shows a simple, proven method.

Steps

1. Create a private field to store an instance of the class you wish to make a singleton.
2. Create a private static readonly object that will be our locking mechanism (lock statement).
3. Create a single private constructor so that other classes do not use the singleton incorrectly.
4. Create a public static property to access the private field we created in step 1.

That's it. The key is in step 4. Again, there are many ways to ensure thread-safety, but for this example (and my preferred implementation) you lock a static object, check to see if the instance is instantiated, then return the instance. 

Now you can add properties to store data.

Example Implementation

namespace SingletonExample
{
	/// <summary>
	/// Class to store common data. Implemented as a thread-safe Singleton.
	/// </summary>
	public sealed class CommonData
	{
		#region Fields

		private static CommonData _instance = null;
		private static readonly object _lock = new object();

		#endregion Fields

		#region Constructors

		/// <summary>
		/// Initializes a new instance of the <see cref="CommonData"/> class.
		/// 
		/// A single private constructor to keep other classes from incorrectly 
		/// instantiating this class. 
		/// </summary>
		private CommonData() { }

		#endregion Constructors

		#region Properties

		/// <summary>
		/// Gets the current instance of this class.
		/// </summary>
		/// <value>The current instance of this class.</value>
		public static CommonData Current
		{
			get
			{
				lock (_lock)
				{
					if (_instance == null)
					{
						_instance = new CommonData();
					}

					return _instance;
				}
			}
		}

		/// <summary>
		/// Gets or sets the user ID.
		/// </summary>
		/// <value>The user ID.</value>
		public string UserID { get; set; }

		/// <summary>
		/// Gets or sets the first name.
		/// </summary>
		/// <value>The first name.</value>
		public string FirstName { get; set; }

		/// <summary>
		/// Gets or sets the last name.
		/// </summary>
		/// <value>The last name.</value>
		public string LastName { get; set; }

		#endregion Properties
	}
}

Using the Singleton

CommonData.Current.UserID = "test";
CommonData.Current.FirstName = "Brandon";
CommonData.Current.LastName = "Zeider";

Download

SingletonExample.zip (51.62 kb)

Creative Commons License
This work is licensed under a Creative Commons Attribution 3.0 Unported License.

 

Bookmark and Share dotnetshoutout
Tags: ,
Categories: Design Patterns | Microsoft .NET

Permalink E-mail | Kick it! | DZone it! | del.icio.us Comments (0) Post RSSRSS comment feed