Code Simplified – Viral Sarvaiya

Code Simplified – Viral Sarvaiya, Web Developer Friends, dot net Developer, Sql Server Developer

Archive for the ‘WPF’ Category

Using BackgroundWorker with WPF

Posted by Viral Sarvaiya on March 26, 2012

When one process take so much long time and UI thread needs to stay responsive while process is running, the most common method to place a long running process on a separate thread.

In WPF there are mostly use technique is  Backgroundworker. Backgroundworker is mostly use in multithreading applications.

Here I show a small example of backgroundworker.

In WPF application I call WCF service function directly not asynchronies, so that function take time get response and at that time user can’t see what happen. so we have to integrate busyindicater while service call.

Busyindicater comes with WPF extended toolkit.

private void OKButton_Click(object sender, RoutedEventArgs e)
MyService myservice = new MyService();
MyServiceResponse Myserviceresponce = new MyServiceResponse();
Myserviceresponce = myservice.CallMyFunction(int Para1, string para2);

here when user click to OK Button, CallMyFunction() take so much long time and end user confuse what to do at that time and he/she click more than one time to that button and application will crashed.

so we put busy indicator in our code and calling this function asynchronies with backgroundworker.

<extToolkit:BusyIndicator x:Name="_busyIndicator" >

and in CS page

private void OKButton_Click(object sender, RoutedEventArgs e)
_busyIndicator.IsBusy = true;

MyServiceResponse Myserviceresponce = new MyServiceResponse();

BackgroundWorker worker = new BackgroundWorker();

//this is where the long running process should go
worker.DoWork += (o, ea) =>
MyService myservice = new MyService();
Myserviceresponce = myservice.CallMyFunction(int Para1, string para2);

worker.RunWorkerCompleted += (o, ea) =>
_busyIndicator.IsBusy = false;

//Continue other statment of this function...

So this will display busyindicator while service call complete.
Hope this will helps you.


Posted in .Net, Visual Studio, WCF Services, WPF | Tagged: , , , , , , , , | 2 Comments »

The “CreateRiaClientFilesTask” task failed unexpectedly

Posted by Viral Sarvaiya on February 14, 2012

Some day ago, when i build my project i get unexpected error.

Error 3 The “CreateRiaClientFilesTask” task failed unexpectedly.
System.Web.HttpException (0x80004005): Could not load file or assembly ‘FileHelpers.DataLink’ or one of its dependencies. Access is denied. —> System.Configuration.ConfigurationErrorsException: Could not load file or assembly ‘FileHelpers.DataLink’ or one of its dependencies. Access is denied. —> System.IO.FileLoadException: Could not load file or assembly ‘FileHelpers.DataLink’ or one of its dependencies. Access is denied……….

Sometime that happen when Visual studio cannot access files. so have to remove Temporary file.

I get simple solution from goggling, just close visual studio and reopen, and if Visual studio has no administrator rights then please right click to visual studio icon and choose “Run as a Administrator”.

Then re-build project and problem solved.


Posted in .Net, ASP.NET, RIA WCF, Silverlight, Visual Studio, WCF Services, WPF | Tagged: , , , , , | 4 Comments »

Check printer status in .net

Posted by Viral Sarvaiya on August 1, 2011


Today i get new thing from my current projet, how to check the status of the printer means wether the printer is connected to PC or not.

For that we have to add reference of the “System.Management”

Here it is code for check status of the printer.

using System.Management;

class PrinterOffline
private static void Main(string[] args)
// Set management scope
ManagementScope scope = new ManagementScope("\\root\\cimv2");
// Select Printers from WMI Object Collections
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Printer");
string printerName = "";
foreach (ManagementObject printer in searcher.Get()) {
printerName = printer("Name").ToString().ToLower();
if (printerName.Equals("Name_Of_Printer")) {
Console.WriteLine("Printer = " + printer("Name"));
if (printer("WorkOffline").ToString().ToLower().Equals("true")) {
// printer is offline by user
Console.WriteLine("Your Plug-N-Play printer is not connected.");
} else {
// printer is not offline
Console.WriteLine("Your Plug-N-Play printer is connected.");


thanks and enjoy coding…

Posted in .Net, ASP.NET, feature, Visual Studio, WPF | Tagged: , , , , , , , | 6 Comments »

Print dynamically generated controls in WPF

Posted by Viral Sarvaiya on May 19, 2011


From my previous post we see how to print page with wpf and with fit to printing page,

But what if we want to print dynamically generated control?

Because printdialog’s PrintVisual method print only visual controls.

Here I demonstrate that how to print controls that dynamically generated.

void PrintOnClick(object sender, RoutedEventArgs args)
PrintDialog dlg = new PrintDialog();
if ((bool)dlg.ShowDialog().GetValueOrDefault())
// Create Grid panel.
Grid grid = new Grid();
// Define 5 auto-sized rows and columns.
for (int i = 0; i < 5; i++)
ColumnDefinition coldef = new ColumnDefinition();
coldef.Width = GridLength.Auto;

RowDefinition rowdef = new RowDefinition();
rowdef.Height = GridLength.Auto;

// Give the Grid a gradient brush.
grid.Background = new LinearGradientBrush(Colors.Black, Colors.White, new Point(0, 0), new Point(1, 1));
// Every program needs some randomness.
Random rand = new Random();

// Fill the Grid with 25 buttons.
for (int i = 0; i < 25; i++)
Button btn = new Button();
btn.FontSize = 12 + rand.Next(8);
btn.Content = "Button No. " + (i + 1);
btn.HorizontalAlignment = HorizontalAlignment.Center;
btn.VerticalAlignment = VerticalAlignment.Center;
btn.Margin = new Thickness(6);
Grid.SetRow(btn, i % 5);
Grid.SetColumn(btn, i / 5);

// Size the Grid.
grid.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));

Size sizeGrid = grid.DesiredSize;

// Determine point for centering Grid on page.
Point ptGrid =  new Point((dlg.PrintableAreaWidth - sizeGrid.Width) / 2, (dlg.PrintableAreaHeight - sizeGrid.Height) / 2);

// Layout pass.
grid.Arrange(new Rect(ptGrid, sizeGrid));
// Now print it.
dlg.PrintVisual(grid, Title);

thanks and enjoy coding…

Posted in .Net, WPF | Tagged: , , , , | Leave a Comment »

Printing in WPF with fit to printing page.

Posted by Viral Sarvaiya on May 17, 2011

Here is the code for the print in WPF.

It is very simple to print a page in comparison with normal window application. Just make a object of the PrintDialog Class and just call function PrintVisual as below

PrintDialog printDlg = new System.Windows.Controls.PrintDialog();
if (printDlg.ShowDialog() == true)
printDlg.PrintVisual(this, "First WPF Print");

This code will print the page. That will take automatically margin to the printing page

What if you want to print page with fit to the printing page?

Here are the steps to print page with fit to printing page.

Step 1: Add the reference of the ReachFramework.dll
Step 2: Add the reference of the System.Printing.dll
Step 3: Get selected Printer’s capability
Step 4: calculate scale of the printer
Step 5: Get printable area of Paper.
Step 6: Update visual layout
Step 7: Print Visual
Here is the code for the above procedure

private void btnPrint_Click(object sender, RoutedEventArgs e)
PrintDialog Objprint = new System.Windows.Controls.PrintDialog();
if (Objprint.ShowDialog() == true)
//get selected printer capabilities
System.Printing.PrintCapabilities capabilities = Objprint.PrintQueue.GetPrintCapabilities(Objprint.PrintTicket);

//get scale of the print wrt to screen of WPF visual
double scale = Math.Min(capabilities.PageImageableArea.ExtentWidth / this.ActualWidth, capabilities.PageImageableArea.ExtentHeight / this.ActualHeight);

//Transform the Visual to scale
this.LayoutTransform = new ScaleTransform(scale, scale);

//get the size of the printer page
Size size = new Size(capabilities.PageImageableArea.ExtentWidth, capabilities.PageImageableArea.ExtentHeight);

//update the layout of the visual to the printer page size.
this.Arrange(new Rect(new Point(capabilities.PageImageableArea.OriginWidth, capabilities.PageImageableArea.OriginHeight), size));

//now print the visual to printer to fit on the one page.
Objprint.PrintVisual(this, "Print in WPF with fit to printing page");


Posted in .Net, WPF | Tagged: , , , | 2 Comments »

Linkbutton in WPF

Posted by Viral Sarvaiya on May 13, 2011


Today i learn new thing from my current project,

i have to use the linkbutton in wpf, there are no control like linkbutton as like control in wpf

we can use the button and set style as like link button…

here is the xaml code for set button as a linkbutton.

<Button Margin="5" Content="Test" Cursor="Hand" Name="BtnTest" Click="BtnTest_Click">
<ControlTemplate TargetType="Button">
<TextBlock TextDecorations="Underline">
<ContentPresenter />
<Style TargetType="Button">
<Setter Property="Foreground" Value="Blue" />
<Trigger Property="IsMouseOver" Value="true">
<Setter Property="Foreground" Value="Red" />

now u can see the button is look like a link button

Enjoy coding…

Posted in .Net, ASP.NET, WPF | Tagged: , , , | 2 Comments »

Multilanguage Application in WPF

Posted by Viral Sarvaiya on May 7, 2011

From this 2 link we can get batter idea of Globalization and Localization,

Here i demostrate very simple way for multiple language application in WPF.

here i make a simple login form in wpf with 2 language English and French Button.
Step 1:  Open Visual studion, Create New Project of WPF give name “WPFMultiLanguage”.

so now you have 2 .xaml file App.xaml and MainWindow.xaml,

Step 2: New we add new folder named “Resources” for Multiple Language.

Step 3: Add resource files

To add resource file named “StringResources.xaml”, right click to Resource folder => Add => Resource Directory (See Image below)

So your file is as like

<ResourceDictionary xmlns=""
xmlns:x="" >


I have added one namespace which points to mscorlib, and named it as system and now add resource string to StringResources.xaml

so StringResources.xaml as below

<ResourceDictionary xmlns=""

<system:String x:Key="Username">Username</system:String>
<system:String x:Key="Password">Password</system:String>
<system:String x:Key="close">close</system:String>
<system:String x:Key="login">login</system:String>
<system:String x:Key="French">French</system:String>
<system:String x:Key="English">English</system:String>


Now add another resource directory for French language named “”

put there French string resuouce and give same key name as per above file,

so as below.

<ResourceDictionary xmlns=""

<system:String x:Key="Username">Nom d'utilisateur</system:String>
<system:String x:Key="Password">Mot de passe</system:String>
<system:String x:Key="close">Fermer</system:String>
<system:String x:Key="login">connexion</system:String>
<system:String x:Key="French">Française</system:String>
<system:String x:Key="English">En anglais</system:String>


Step 4: Add Resource file to window.

Now its time to add resource file to Mainwindow page.

for that in the MainWindow.xaml file design the login page and put 2 button for the language transfer.

For display content and text from resource file, use DynamicResource.

for that i have made 1 function that add dictionaries directly to window resources and in click event of the button for language transfer i set culture for that.

so MainWindow.xaml as below.

<Window x:Class="WPFMultiLanguage.MainWindow"
Title="MainWindow" Height="350" Width="525">
<Grid Background="Beige" >

<TextBlock Name="Username" Text="{DynamicResource Username}" VerticalAlignment="Center" HorizontalAlignment="Right" Margin="0,24,18,38"></TextBlock>
<TextBox Name="txtuser" Width="100" Height="30" Grid.Column="1" Grid.Row="0" VerticalAlignment="Center" HorizontalAlignment="Left"></TextBox>
<TextBlock Name="Password" Text="{DynamicResource Password}" Grid.Column="0" Margin="0,24,18,38" Grid.Row="1" VerticalAlignment="Center" HorizontalAlignment="Right"></TextBlock>
<PasswordBox Name="txtpass" Width="100" Height="30" Grid.Column="1" Grid.Row="1" HorizontalAlignment="Left" VerticalAlignment="Center" />

<Button x:Name="btnLogin" Width="100" Height="40" VerticalAlignment="Top" HorizontalAlignment="Right"
Click="btnLogin_Click" Content="{DynamicResource login}" Grid.Row="2" Grid.Column="0" Padding="10" />
<Button x:Name="btnClose" Width="100" Height="40" VerticalAlignment="Top" HorizontalAlignment="Left"
Click="btnClose_Click" Content="{DynamicResource close}" Grid.Row="2" Grid.Column="1" Padding="10" />

<Button x:Name="btnEnglish" Width="100" Height="40" VerticalAlignment="Bottom" HorizontalAlignment="Right"
Click="btnEnglish_Click" Content="{DynamicResource English}" Grid.Row="3" Grid.Column="0" Padding="10" />

<Button x:Name="btnFrench" Width="100" Height="40" VerticalAlignment="Bottom" HorizontalAlignment="Left"
Click="btnFrench_Click" Content="{DynamicResource French}" Grid.Row="3" Grid.Column="1" Padding="10" />

and MainWindow.xaml.cs as below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using System.Threading;
namespace WPFMultiLanguage
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
public MainWindow()

private void SetLanguageDictionary()
ResourceDictionary dict = new ResourceDictionary();
switch (Thread.CurrentThread.CurrentCulture.ToString())
case "en-US":
dict.Source = new Uri("..\\Resources\\StringResources.xaml", UriKind.Relative);
case "fr-CA":
dict.Source = new Uri("..\\Resources\\", UriKind.Relative);
dict.Source = new Uri("..\\Resources\\StringResources.xaml", UriKind.Relative);

private void btnLogin_Click(object sender, RoutedEventArgs e)
if (txtuser.Text.Trim() == "")
MessageBox.Show("Please Enter Username");
//If u want to set resource from code behind then use below code
//FindResource("<Resource Key Name>").ToString()
if (txtpass.Password.Trim() == "")
MessageBox.Show("Please Enter Password");
if (txtuser.Text.Trim() == txtpass.Password.Trim())


private void btnClose_Click(object sender, RoutedEventArgs e)

private void btnEnglish_Click(object sender, RoutedEventArgs e)
System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo("en-US");
Thread.CurrentThread.CurrentCulture = cultureInfo;

private void btnFrench_Click(object sender, RoutedEventArgs e)
System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo("fr-CA");
Thread.CurrentThread.CurrentCulture = cultureInfo;

Now run the solution

english is by default so first time when you run code it display in english language
and then click to French button it display in French.


Posted in .Net, Silverlight, Visual Studio, WPF | Tagged: , , , , , | 4 Comments »

%d bloggers like this: