C# Base64 String to PNG Image

Here’s how you can save a base64 encoded string to image file in C#.

public void SaveImageFile(string filename, string base64Image)
{
    string destinationImgPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + Constants.UserImagesPath+"\\"+filename+".png";
    try
    {
        Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + Constants.UserImagesPath);
    }
    catch (IOException iox)
    {
        Console.WriteLine(iox.Message+" "+iox.Data);
    }
    var bytes = Convert.FromBase64String(base64Image);
    using (var imageFile = new FileStream(destinationImgPath, FileMode.Create))
    {
        imageFile.Write(bytes, 0, bytes.Length);
        imageFile.Flush();
    }
}

How to Zoom Image in WPF app

This post shows how to zoom an image in WPF app. The image can be zoomed by rolling the mouse scroller or by double clicking on the image.

Step 1: Add the ZoomBorder Class to the project

Add the following ZoomBorder class to your project.

public class ZoomBorder : Border
    {
        private UIElement child = null;
        private Point origin;
        private Point start;

        private TranslateTransform GetTranslateTransform(UIElement element)
        {
            return (TranslateTransform)((TransformGroup)element.RenderTransform)
              .Children.First(tr => tr is TranslateTransform);
        }

        private ScaleTransform GetScaleTransform(UIElement element)
        {
            return (ScaleTransform)((TransformGroup)element.RenderTransform)
              .Children.First(tr => tr is ScaleTransform);
        }

        public override UIElement Child
        {
            get { return base.Child; }
            set
            {
                if (value != null && value != this.Child)
                    this.Initialize(value);
                base.Child = value;
            }
        }

        public void Initialize(UIElement element)
        {
            this.child = element;
            if (child != null)
            {
                TransformGroup group = new TransformGroup();
                ScaleTransform st = new ScaleTransform();
                group.Children.Add(st);
                TranslateTransform tt = new TranslateTransform();
                group.Children.Add(tt);
                child.RenderTransform = group;
                child.RenderTransformOrigin = new Point(0.0, 0.0);
                this.MouseWheel += child_MouseWheel;
                this.MouseLeftButtonDown += child_MouseLeftButtonDown;
                this.MouseLeftButtonUp += child_MouseLeftButtonUp;
                this.MouseMove += child_MouseMove;
                this.PreviewMouseRightButtonDown += new MouseButtonEventHandler(
                  child_PreviewMouseRightButtonDown);
            }
        }

        public void Reset()
        {
            if (child != null)
            {
                // reset zoom
                var st = GetScaleTransform(child);
                st.ScaleX = 1.0;
                st.ScaleY = 1.0;

                // reset pan
                var tt = GetTranslateTransform(child);
                tt.X = 0.0;
                tt.Y = 0.0;
            }
        }

        #region Child Events

        private void child_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            if (child != null)
            {
                var st = GetScaleTransform(child);
                var tt = GetTranslateTransform(child);

                double zoom = e.Delta > 0 ? .2 : -.2;
                if (!(e.Delta > 0) && (st.ScaleX < .4 || st.ScaleY < .4))
                    return;

                Point relative = e.GetPosition(child);
                double abosuluteX;
                double abosuluteY;

                abosuluteX = relative.X * st.ScaleX + tt.X;
                abosuluteY = relative.Y * st.ScaleY + tt.Y;

                st.ScaleX += zoom;
                st.ScaleY += zoom;

                tt.X = abosuluteX - relative.X * st.ScaleX;
                tt.Y = abosuluteY - relative.Y * st.ScaleY;
            }
        }

        private void child_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (child != null)
            {
                var tt = GetTranslateTransform(child);
                start = e.GetPosition(this);
                origin = new Point(tt.X, tt.Y);
                this.Cursor = Cursors.Hand;
                child.CaptureMouse();
            }
        }

        private void child_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (child != null)
            {
                child.ReleaseMouseCapture();
                this.Cursor = Cursors.Arrow;
            }
        }

        void child_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.Reset();
        }

        private void child_MouseMove(object sender, MouseEventArgs e)
        {
            if (child != null)
            {
                if (child.IsMouseCaptured)
                {
                    var tt = GetTranslateTransform(child);
                    Vector v = start - e.GetPosition(this);
                    tt.X = origin.X - v.X;
                    tt.Y = origin.Y - v.Y;
                }
            }
        }

        #endregion
    }

Step 2: Use the ZoomBorder class in your XAML page.

Firstly add a reference to the directory in which the ZoomBorder class in located. For example I have added the ZoomBorder class in Utils folder so i add a reference to this folder in the XAML page.

xmlns:utils="clr-namespace:MyProject.Utils"

Next wrap the image inside the ZoomBorder control.

<utils:ZoomBorder x:Name="border" ClipToBounds="True" Background="Gray">
    <Image Source="/myimage.png"/>
</utils:ZoomBorder>

That’s it. Deploy the project to see if it works. 🙂

Using Chromium Web Browser Control in WPF app

WebBroswer control in WPF by default uses IE 7 engine for rendering webpages. This may become an issue while displaying modern websites. There are two alternatives. One is to use browser emulation feature to use a different IE version browser instead of IE 7. How that can be done is explained in this post.

Using Browser Emulation for Web Browser control in WPF app

The other way is to use V8 engine(Chromium) used by Google Chrome. There are various libraries that let you use Chromium browser in your WPF project. We will be using the CefSharp library. You can read more about the various options available for using Chromium engine in WPF app.

CefSharp is a C# import for Cef framework. It is available as a Nuget package too.

Step 1: Install the CefSharp library

Install the CefSharp library using nuget. Here’s the link to the Nuget package.
https://www.nuget.org/packages/CefSharp.Wpf

You could refer to this article if you need assistance in adding a Nuget package to your project in Visual Studio.

Initialize the Cef browser in App.xaml.cs

You need to initialize the browser with some default settings. Here’s the code that you need to add in your project’s App.xaml.cs. This is required because of a known issue (#1634) that makes the screen flicker after the page is loaded.

public App()
{  
    //Perform dependency check to make sure all relevant resources are in our output directory.
    var settings = new CefSettings();
    settings.EnableInternalPdfViewerOffScreen();
    // Disable GPU in WPF and Offscreen examples until #1634 has been resolved
    settings.CefCommandLineArgs.Add("disable-gpu", "1");
    settings.CachePath = "cache";
    
    Cef.Initialize(settings, shutdownOnProcessExit: true, performDependencyCheck: true);
}

Add a reference to CefSharp in MainPage.xaml

Add a reference in MainPage.xaml before you could use it.

xmlns:cefSharp="clr-namespace:CefSharp.Wpf;assembly=CefSharp.Wpf"

Add the Chromium Web Browser control in your page

Now you can add the web browser control in your page. Here’s the code that is required.

<cefSharp:ChromiumWebBrowser
        x:Name="ChromiumWebBrowser"
        Address="http://www.google.com" />

That’s it you are done. Try deploying the app to see if it works.

How to Scan an Image using Interop.WIA in a WPF app

This post shows how to scan an image using a scanner in a WPF app.

Step 1: Add a Reference to WIA dll

Firstly, you need a reference to Interop.WIA.dll in the project. Download the dll file from the following link.

Download Interop.WIA.dll

Once you have downloaded the dll file add a reference to it by right click on the project name and selecting Add > Reference.

Add a reference to Interop.WIA.dll

Step 2: Add the ScannerService class to the project

Here’s the complete code for the ScannerService class that you can directly include in your project.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using WIA;

namespace WPF_Example.Services
{
    public class ScannerService
    {
        public static void Scan()
        {
            try
            {
                CommonDialogClass commonDialogClass = new CommonDialogClass();
                Device scannerDevice = commonDialogClass.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, false, false);
                if (scannerDevice != null)
                {
                    Item scannnerItem = scannerDevice.Items[1];
                    AdjustScannerSettings(scannnerItem, 600, 0, 0, 1010, 620, 0, 0);
                    object scanResult = commonDialogClass.ShowTransfer(scannnerItem, WIA.FormatID.wiaFormatPNG, false);
                    if (scanResult != null)
                    {
                        ImageFile image = (ImageFile)scanResult;
                        SaveImageToJpgFile(image, Constants.ScannedImageLocation);
                     }
                }
            }
            catch (System.Runtime.InteropServices.COMException)
            {
                MessageBox.Show("Problem with scanning device. Please ensure that the scanner is properly connected and switched on", "Inweon Grain Management System");
            }
        }

        private static void AdjustScannerSettings(IItem scannnerItem, int scanResolutionDPI, int scanStartLeftPixel, int scanStartTopPixel,
            int scanWidthPixels, int scanHeightPixels, int brightnessPercents, int contrastPercents)
        {
            const string WIA_HORIZONTAL_SCAN_RESOLUTION_DPI = "6147";
            const string WIA_VERTICAL_SCAN_RESOLUTION_DPI = "6148";
            const string WIA_HORIZONTAL_SCAN_START_PIXEL = "6149";
            const string WIA_VERTICAL_SCAN_START_PIXEL = "6150";
            const string WIA_HORIZONTAL_SCAN_SIZE_PIXELS = "6151";
            const string WIA_VERTICAL_SCAN_SIZE_PIXELS = "6152";
            const string WIA_SCAN_BRIGHTNESS_PERCENTS = "6154";
            const string WIA_SCAN_CONTRAST_PERCENTS = "6155";
            const string WIA_SCAN_BIT_DEPTH = "4104";
            SetWIAProperty(scannnerItem.Properties, WIA_HORIZONTAL_SCAN_RESOLUTION_DPI, scanResolutionDPI);
            SetWIAProperty(scannnerItem.Properties, WIA_VERTICAL_SCAN_RESOLUTION_DPI, scanResolutionDPI);
            SetWIAProperty(scannnerItem.Properties, WIA_HORIZONTAL_SCAN_START_PIXEL, scanStartLeftPixel);
            SetWIAProperty(scannnerItem.Properties, WIA_VERTICAL_SCAN_START_PIXEL, scanStartTopPixel);
            //SetWIAProperty(scannnerItem.Properties, WIA_SCAN_BIT_DEPTH, 48);
            SetWIAProperty(scannnerItem.Properties, WIA_SCAN_BRIGHTNESS_PERCENTS, brightnessPercents);
            SetWIAProperty(scannnerItem.Properties, WIA_SCAN_CONTRAST_PERCENTS, contrastPercents);
        }

        private static void SetWIAProperty(IProperties properties, object propName, object propValue)
        {
            Property prop = properties.get_Item(ref propName);
            prop.set_Value(ref propValue);
        }

        private static void SaveImageToJpgFile(ImageFile image, string fileName)
        {
            ImageProcess imgProcess = new ImageProcess();
            object convertFilter = "Convert";
            string convertFilterID = imgProcess.FilterInfos.get_Item(ref convertFilter).FilterID;
            imgProcess.Filters.Add(convertFilterID, 0);
            SetWIAProperty(imgProcess.Filters[imgProcess.Filters.Count].Properties, "FormatID", WIA.FormatID.wiaFormatJPEG);
            image = imgProcess.Apply(image);
            image.SaveFile(fileName);
        }
    }
}

Use the Scan function

To use ScannerService simply use the following code.

ScannerService.Scan();

How to Print an Existing Excel File Using C#

In this tutorial I will show you how to print a Excel file using a WPF app. You might also want to look at a related post.

Create and Download Excel File Using PHP

Step 1: Add a reference to Excel Interop in your Project

Add a reference to Microsoft.Office.Interop.Excel in your project by right clicking on References, Add Reference from the Solution Explorer. Next choose Microsoft.Office.Interop.Excel from the Extensions tab under Assemblies.

Add a using statement at the top of the page in which you want to add the print XlS function.

using Excel= Microsoft.Office.Interop.Excel;

Step 2: Define Public Variables for Excel

Define the following variables before the class constructor.

public Excel.Application APP = null;
public Excel.Workbook WB = null;
public Excel.Worksheet WS = null;
public Excel.Range Range = null;  

Step 3: Add the Method to Print Excel

The following function opens a Excel file to print it and then closes it again.

void PrintMyExcelFile()
{
    this.APP = new Microsoft.Office.Interop.Excel.Application(); 

    // Open the Workbook:
    this.Open("C:\\Users\\maska\\Documents\\MyExcel.xlsx", 1);

    // Get the first worksheet.
    // (Excel uses base 1 indexing, not base 0.)
    WS = (Excel.Worksheet)WB.Worksheets[1];

    // Print out 1 copy to the default printer:
    WS.PrintOut(
        Type.Missing, Type.Missing, Type.Missing, Type.Missing,
        Type.Missing, Type.Missing, Type.Missing, Type.Missing);

    // Cleanup:
    GC.Collect();
    GC.WaitForPendingFinalizers();

    Marshal.FinalReleaseComObject(WS);

    WB.Close(false, Type.Missing, Type.Missing);
    Marshal.FinalReleaseComObject(WB);

    APP.Quit();
    Marshal.FinalReleaseComObject(APP);
}

That’s it. Call this method to print an existing excel file.

How to Execute a Command in C# ?

This article will help you to execute a command in C#, just like we execute a command using the Windows command prompt

The code given below creates a process i.e. a command process and then invokes the command that we want to execute. The result of the command is stored in a string variable, which can then be used for further reference. The command execution can happen in two ways, synchronously and asynchronously. In the asynchronous command execution, we just invoke the command execution using a thread that runs independently.

Below is the code to execute the command synchronously:

/// <span class="code-SummaryComment"><summary></span>
/// Executes a shell command synchronously.
/// <span class="code-SummaryComment"></summary></span>
/// <span class="code-SummaryComment"><param name="command">string command</param></span>
/// <span class="code-SummaryComment"><returns>string, as output of the command.</returns></span>
public void ExecuteCommandSync(object command)
{
     try
     {
         // create the ProcessStartInfo using "cmd" as the program to be run,
         // and "/c " as the parameters.
         // Incidentally, /c tells cmd that we want it to execute the command that follows,
         // and then exit.
    System.Diagnostics.ProcessStartInfo procStartInfo =
        new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);

    // The following commands are needed to redirect the standard output.
    // This means that it will be redirected to the Process.StandardOutput StreamReader.
    procStartInfo.RedirectStandardOutput = true;
    procStartInfo.UseShellExecute = false;
    // Do not create the black window.
    procStartInfo.CreateNoWindow = true;
    // Now we create a process, assign its ProcessStartInfo and start it
    System.Diagnostics.Process proc = new System.Diagnostics.Process();
    proc.StartInfo = procStartInfo;
    proc.Start();
    // Get the output into a string
    string result = proc.StandardOutput.ReadToEnd();
    // Display the command output.
    Console.WriteLine(result);
      }
      catch (Exception objException)
      {
      // Log the exception
      }
}

The above code invokes the cmd process specifying the command to be executed. The option procStartInfo.RedirectStandardOutput is set to true, since we want the output to be redirected to the StreamReader. The procStartInfo.CreateNoWindow property is set to true, as we don’t want the standard black window to appear. This will execute the command silently.

Below is the code to execute the command asynchronously:

/// <span class="code-SummaryComment"><summary></span>
/// Execute the command Asynchronously.
/// <span class="code-SummaryComment"></summary></span>
/// <span class="code-SummaryComment"><param name="command">string command.</param></span>
public void ExecuteCommandAsync(string command)
{
   try
   {
    //Asynchronously start the Thread to process the Execute command request.
    Thread objThread = new Thread(new ParameterizedThreadStart(ExecuteCommandSync));
    //Make the thread as background thread.
    objThread.IsBackground = true;
    //Set the Priority of the thread.
    objThread.Priority = ThreadPriority.AboveNormal;
    //Start the thread.
    objThread.Start(command);
   }
   catch (ThreadStartException objException)
   {
    // Log the exception
   }
   catch (ThreadAbortException objException)
   {
    // Log the exception
   }
   catch (Exception objException)
   {
    // Log the exception
   }
}

If we observe carefully, the asynchronous execution of the command actually invokes the synchronous command execution method using a thread. The thread runs in the background making the command execution asynchronous in nature.