C#, WPF – Windows 7 Thumbnail Toolbar

During learning to develop myself a gadget for Windows 7, I would like to use some features of Windows 7 for my application. One of these features is enabling thumbnail of our application on toolbar as following

You can see in image above that I have a custom beautiful thumbnail with 4 buttons to navigate through the image gallery. To apply this feature in our application, I need a library called Microsoft API Code Pack http://code.msdn.microsoft.com/WindowsAPICodePack . In download package you can find a lot of examples relevant to many interesting features of Windows 7. The example below is extracted from this package but I made some modifications so that it works better.

1. Create a WPF application, add a StackPanel and 2 children: Image and ListBox control. The list box item template was also changed to contain an Image and a TextBlock. The TextBlock is set by the name of the image.

2. Add reference to Microsoft.WindowsAPICodePack.dll and Microsoft.WindowsAPICodePack.Shell.dll.
3. Test if I am running on Windows 7

public Window1()
{
	if (!TaskbarManager.IsPlatformSupported)
	{
		MessageBox.Show("This demo runs only on Windows 7");
		Application.Current.Shutdown();
	}
	InitializeComponent();
}

4. Add images to list box through data binding. The data was taken from ViewModel.

<ListBox x:Name="ImageList" ItemsSource="{Binding AllImages}" ItemTemplate="{DynamicResource ItemImageTemplate}" ItemsPanel="{DynamicResource PanelImageTemplate}" Height="167" />

5. Add 4 thumbnail toolbar button when window loads. These buttons will be used for navigating our gallery in thumbnail as shown in image above.

private void Window_Loaded(object sender, System.Windows.RoutedEventArgs e)
{
	// TODO: Add event handler implementation here.
	m_btnToolbarFist = new ThumbnailToolbarButton(Properties.Resources.FirstImage, "First Image");
	m_btnToolbarFist.Enabled = true;
	m_btnToolbarFist.Click += new EventHandler<ThumbnailButtonClickedEventArgs>(m_btnToolbarFist_Click);

	m_btnToolbarPrev = new ThumbnailToolbarButton(Properties.Resources.PreviousImage, "Previous Image");
	m_btnToolbarPrev.Enabled = true;
	m_btnToolbarPrev.Click += new EventHandler<ThumbnailButtonClickedEventArgs>(m_btnToolbarPrev_Click);

	m_btnToolbarNext = new ThumbnailToolbarButton(Properties.Resources.NextImage, "Next Image");
	m_btnToolbarNext.Enabled = true;
	m_btnToolbarNext.Click += new EventHandler<ThumbnailButtonClickedEventArgs>(m_btnToolbarNext_Click);

	m_btnToolbarLast = new ThumbnailToolbarButton(Properties.Resources.LastImage, "Last Image");
	m_btnToolbarLast.Enabled = true;
	m_btnToolbarLast.Click += new EventHandler<ThumbnailButtonClickedEventArgs>(m_btnToolbarLast_Click);

	TaskbarManager.Instance.ThumbnailToolbars.AddButtons(new WindowInteropHelper(this).Handle, new ThumbnailToolbarButton[] { m_btnToolbarFist, m_btnToolbarPrev, m_btnToolbarNext, m_btnToolbarLast });
}

6. Add some code lines for navigating images in list. For example, the code handle to navigate to the last image in list.

void m_btnToolbarLast_Click(object sender, ThumbnailButtonClickedEventArgs e)
{
	ImageList.SelectedIndex = ImageList.Items.Count - 1;
	ImageList.Focus();
	if (ImageList.SelectedItem != null)
		ImageList.ScrollIntoView(ImageList.SelectedItem);
}

7. I would like to use the current selected image as our thumbnail. Therefore let’s take a snapshot of Image control and set it to taskbar through SetThumbnailcClip function.

void PictureBox_LayoutUpdated(object sender, EventArgs e)
{
	Vector vtPict = VisualTreeHelper.GetOffset(PictureBox);
	TaskbarManager.Instance.TabbedThumbnail.SetThumbnailClip(new WindowInteropHelper(this).Handle, new System.Drawing.Rectangle((int)vtPict.X, (int)vtPict.Y, (int)PictureBox.RenderSize.Width, (int)PictureBox.RenderSize.Height));
}

What I am still concerning is try to build the program exactly according to MVVM pattern. The complete source code you can download “WPF Win7 Thumbnail Demo

MVVM – ListView SelectedItem and DataBinding

UPDATE: I recommend a new version of this post at following link C# – WPF MVVM DataBinding 2014

On studying how to use MVVM pattern in WPF I found out that the ListView or ListBox control doesn’t support ICommand interface and therefore I can not bind a command to a ListView. After searching on Internet I saw that man can use Prism extensions framework http://www.codeplex.com/CompositeWPF to add custom command to our ListView control. The example below guides step by step how to get SelectedItem of ListView in MVVM pattern using command.

Continue reading MVVM – ListView SelectedItem and DataBinding

ASP.NET – Show image from database

One of my friends asks me for an example of reading image from database and showing it on web form in ASP.NET. I send him a link for such tutorial http://www.microsoft.com/germany/msdn/solve/knowhow/howto/allgemein/WieKannIchBilderInEineDatenbankSchreibenUndWiederAuslesen.mspx but it was written in German and he can not follow these steps therefore I decide to translate it to English. I don’t know if there is an English version of this tutorial, I just translate it for my friend in step by step tutorial. I only translate main idea so that you can make the example run. I do not translate word by word, I catch the concept and rewrite it according to my style. If you want to understand more details of this article, please use Google translate.

Continue reading ASP.NET – Show image from database

C# – Insert many tables/images successively into Word/current Word document

Today I read a thread on mycsharp.de asking about how man can insert many tables successively into Word. I think it’s very simple to do that with some Google search but when I begin to write a demo for myself I found out that it’s not easy as I think. There are some new concepts which I am still not clear, for example Range or a function with lot of arguments with ref-keyword. So I lost a lot of time to understand how the classes work.
To work with a Word document, what all we need to do is add a reference to assembly Microsoft.Office.Interop.Word. You can choose version 11 or 12 whatever you want. To add tables to Word, let’s following these steps.

1. We need to create a Word application instance

Application objWord = new Application();

2. Create a Word document

object objMissing = System.Reflection.Missing.Value;
Document objDocument = objWord.Documents.Add(ref objMissing, ref objMissing, ref objMissing, ref objMissing);

Did you see the objMissing appearing so many times in calling function Documents.Add. It’s really insane when writing such a code but we can quickly create a new blank document.

3. Add tables into document

object oEndOfDoc = "\\endofdoc";
Range objRange;
Table objTable;
Paragraph objParagraph;
object objRangePara;
for (int nIndex = 0; nIndex < 3; nIndex++)
{
	objRange = objDocument.Bookmarks.get_Item(ref oEndOfDoc).Range;
	objTable = objDocument.Tables.Add(objRange, 5, 2, ref objMissing, ref objMissing);                                     
	objRangePara = objDocument.Bookmarks.get_Item(ref oEndOfDoc).Range;
	objParagraph = objDocument.Content.Paragraphs.Add(ref objRangePara);                  
	objParagraph.Range.Text = Environment.NewLine;   
}

We’ll try to find out where is the end of our document and set range from the current position until end. Then we add our table with 5 rows and 2 columns. What important is that we must insert a blank line between tables. If we don’t do so, all tables will merge into one. I really lost a lot of time at this point. From the beginning, I did not add any blank line therefore the tables were always automatically merged into one. I thought that when we add new table, document object will insert table from new line or in new paragraph but the truth is that it doesn’t.

4. Save our file

object objFileName = @"E:\temp.doc";
objDocument.SaveAs(ref objFileName, ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing);
((Microsoft.Office.Interop.Word._Application)objWord).Quit(ref objMissing, ref objMissing, ref objMissing);

The complete source code of example you can download here “Insert table into word document

UPDATE 06.08.2012
To insert images into current opening Word document, you can use listing below

private static void InsertImages()
{
	Application wordApp;
	Document doc = null;
	try
	{
		wordApp = (Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
	}
	catch (Exception ex)
	{
		wordApp = new Application();
		wordApp.Documents.Add();
		wordApp.Visible = true;
	}

	for (int index = 0; index < wordApp.Windows.Count; index++)
	{
		object a = index + 1;
		Window winWord = wordApp.Windows.get_Item(ref a);
		if (winWord.Active)
		{
			doc = wordApp.ActiveDocument;
			break;
		}
	}

	List<string> fileNames = new List<string>()
				{
					@"D:\Temp\Files\20120619-1216_37_73.jpg",
					@"D:\Temp\Files\20120619-1201_37_65.jpg",
					@"D:\Temp\Files\20120619-1200_37_64.jpg",
					@"D:\Temp\Files\20120619-1215_37_72.jpg",
					@"D:\Temp\Files\20120427-1430_22_2.jpg",
				};
	foreach (string filename in fileNames)
	{				
		doc.InlineShapes.AddPicture(filename, Type.Missing, Type.Missing, Type.Missing);
	}

	//wordApp.Quit();
}

We call API GetActiveObject to get all instances of Word application and make a loop through all of their windows. Only one of them will be active and it’s the last one that we visited. After locating the “active” window, we get the current document and insert images at current cursor through function Document.InlineShapes.AddPicture()

Silverlight – Sending data between Silverlight applications with LocalMessage API

In Silverlight 3, Microsoft allows us to sending data between local Silverlight-based applications through defined channel. To use this feature we’ll apply the classes in namespace System.Windows.Messaging. In next example I would like to illustrate how we can build this local channel.

Continue reading Silverlight – Sending data between Silverlight applications with LocalMessage API