2018-02-16

Print WPF controls

This post will explain how to print WPF controls.

Create Custom Print button

Start with creating a UserControl with only print button on it.

<UserControl x:Class="PrintButton.PrintControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d" 
             d:DesignHeight="20" d:DesignWidth="50">
    <Grid>
        <Button x:Name="Print"  
                Content="Print"                 
                Height="20"
                Width="50"                 
                Click="Print_Click" VerticalAlignment="Top" />
    </Grid>
</UserControl>



With code behind

using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
 
namespace PrintButton
{
    /// <summary>
    /// Interaction logic for PrintButton.xaml
    /// </summary>
    public partial class PrintControl : UserControl
    {
        public PrintControl()
        {
            InitializeComponent();
        }
 
        public Visual ControlToPrint { getset; }
 
        private void Print_Click(object sender, RoutedEventArgs e)
        {
            var printDialog = new PrintDialog();
            if (printDialog.ShowDialog() != true)
                return;
 
            Print.Visibility = Visibility.Hidden;
            printDialog.PrintVisual(ControlToPrint, "Print");
            Print.Visibility = Visibility.Visible;
        }
    }
}

I hide button when we print something. In that way button will not be part of print document.

Use PrintControl

Next step is to use this UserControl in place where you want to print.

<Window x:Class="PrintButton.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:PrintButton"
        mc:Ignorable="d"
        Title="Print button demo" Height="200" Width="300">
    <Grid>
        <Grid.ColumnDefinitions >
            <ColumnDefinition Width="Auto" MinWidth="214" />
            <ColumnDefinition Width="Auto" MinWidth="15" />
        </Grid.ColumnDefinitions>
        
        <Grid x:Name="GridForPrint" Grid.Column="0">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>
            <Label Grid.Row="0" Content="Header" HorizontalAlignment="Left" VerticalAlignment="Top" FontSize="14" FontWeight="Bold"/>
            <TextBlock Grid.Row="1"><Run Text="More text to print"/></TextBlock>
        </Grid>
 
 
        <local:PrintControl x:Name="Print"  
                            Grid.Column="1" 
                            HorizontalAlignment="Right" 
                            Margin="0,10,1,10" 
                            Width="50"  
                            ControlToPrint="{x:Reference Name=GridForPrint}" />
 
 
    </Grid>
</Window>
 
 
 

All we need to do is to give a name to the component that we want to print.
Then call our PrintControl referencing that component.

   <local:PrintControl  
          ControlToPrint="{x:Reference Name=GridForPrint}" />

Now each time print is clicked, Grid "GridForPrint" will be printed.

2015-01-20

Visual Studio Visualizers

VS Visualizers are great way to visualize objects when debugging your code. I created some visualizers that I can share with you on this page.

DataSet visualizer 

Difference between default DataSet visualizer and my is that I added following:

  • Export DataSet to Xml
  • Export DataTable to Xml
  • Show Parent/child rows based on DataSet Relations of selected cells
  • Filter on selected cells




Image visualizer

Shows image from variable.





















Color visualizer

Shows more info about a color.


2014-11-04

Dependency Injection - Hello World

Here is a simple implementation of Dependency Injection. UnityContainer is initialize in code but you can use configuration file if you like.


using System;
using Microsoft.Practices.Unity;
 
namespace DependencyInjectionSample
{
    public interface IUnityClass
    {
        void HelloWorld();
    }
 
    public class UnityClass : IUnityClass
    {
        public void HelloWorld()
        {
            Console.WriteLine("Hello!");
        }
    }
 
    /// <summary>
    ///     This class is used to manage dependency injection using Unity.
    ///     It Manages containers and configurations.
    /// </summary>
    internal static class DependencyInjection
    {
        private static IUnityContainer InitUnityContainer()
        {
            IUnityContainer myContainer = new UnityContainer();
 
            //Register types
            myContainer.RegisterType(typeof (IUnityClass), typeof (UnityClass));
            //...
 
            return myContainer;
        }
 
 
        public static T Resolve<T>()
        {
            IUnityContainer myContainer = InitUnityContainer();
         
            return (T) myContainer.Resolve(typeof (T));
        }
    }
 
 
    public class HelloWorld
    {
        public HelloWorld()
        {
            var di = DependencyInjection.Resolve<IUnityClass>();
            di.HelloWorld();
        }
    }
}

2014-10-21

How to draw a grid in c#

Grids are often needed when we design or measure something. Here is example of a such grid.


Code for it:


using System;
using System.Drawing;
using System.Windows.Forms;
 
namespace WinFormDemo
{
    public partial class FormGrid : Form
    {
        public FormGrid()
        {
            InitializeComponent();
        }
 
 
        private void OnPanelPaint(object sender, PaintEventArgs e)
        {
            e.Graphics.PageUnit = GraphicsUnit.Millimeter;
            DrawHelpGrid(e.Graphics);
        }
 
 
        private void DrawHelpGrid(Graphics graphic, int width = 100int height = 100)
        {
            int max = Math.Max(width, height);
            var pen1 = new Pen(Brushes.LightGray, 0.1f);
            var pen2 = new Pen(Brushes.LightGreen, 0.1f);
            bool mainLine = true;
 
            for (int index = 0; index < max; index += 5)
            {
                Pen pen = mainLine ? pen2 : pen1;
 
                // Make main line little longer
                int ext = mainLine ? 2 : 0;
 
                if (index <= height)
                {
                    graphic.DrawLine(pen, 0, index, width + ext, index);
                    if (mainLine)
                    {
                        graphic.DrawString(index + "", 
                            SystemFonts.MenuFont, 
                            Brushes.Blue, 
                            width + 5, index - 2);
                    }
                }
 
                if (index <= width)
                {
                    graphic.DrawLine(pen, index, 0, index, height + ext);
                    if (mainLine)
                    {
                        graphic.DrawString(index + "", 
                            SystemFonts.MenuFont, 
                            Brushes.Blue, 
                            index - 3, height + 5);
                    }
                }
                mainLine = !mainLine;
            }
        }
    }
}
And Designer conde

namespace WinFormDemo
{
    partial class FormGrid
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;
 
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }
 
        #region Windows Form Designer generated code
 
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.panel1 = new System.Windows.Forms.Panel();
            this.SuspendLayout();
            // 
            // panel1
            // 
            this.panel1.BackColor = System.Drawing.Color.White;
            this.panel1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.panel1.Location = new System.Drawing.Point(00);
            this.panel1.Name = "panel1";
            this.panel1.Size = new System.Drawing.Size(590428);
            this.panel1.TabIndex = 1;
            this.panel1.Paint += new System.Windows.Forms.PaintEventHandler(this.OnPanelPaint);
            // 
            // FormGrid
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(590428);
            this.Controls.Add(this.panel1);
            this.Name = "FormGrid";
            this.Text = "Grid";
            this.ResumeLayout(false);
 
        }
 
        #endregion
 
        private System.Windows.Forms.Panel panel1;
    }
}
 

2014-02-18

How to show row count always in first column in devexpress asp.net mvc GridView

Your partial view with gridview control may look something like this:

@using MyWebApplication.Controllers
@{    var gridHelper = new GridViewHelper();
    var grid = Html.DevExpress().GridView(settings =>
    {
        settings.Name = "MyGridView";
        settings.SettingsBehavior.ColumnResizeMode = ColumnResizeMode.Control;
        settings.Columns.Add("col1");
        settings.Columns.Add("col2");
        settings.Columns.Add("col3");
        settings.Settings.ShowFooter = true;
        settings.HtmlFooterCellPrepared = gridHelper.ShowRowCountInFirstColumn;
    });
}@grid.Bind(Model).GetHtml()



And in here is definition of class GridViewHelper



public class GridViewHelper{   public void ShowRowCountInFirstColumn( object sender,  ASPxGridViewTableFooterCellEventArgs args)   {      if (args.Column.VisibleIndex != 1)        return;       ASPxGridView grid = sender as ASPxGridView;       foreach (ASPxSummaryItem item in grid.TotalSummary)       {         if (item.SummaryType == DevExpress.Data.SummaryItemType.Count)         {            args.Cell.Text = string.Format("{0:n0} rows",grid.GetTotalSummaryValue(item));
           return;
         }
        }
 
       var countSummary = grid.TotalSummary.Add(DevExpress.Data.SummaryItemType.Count, "#");
       args.Cell.Text = string.Format("{0:n0} rows",grid.GetTotalSummaryValue(item));
       return;     }
}

2012-09-26

Change access right on directory for Users group or current user

If you need set some access right to specific folder I can get idea from this code how to do that.



    public static void AllowModifyOnDirectory(string directoryPath)
    {
      ifstring.IsNullOrWhiteSpacedirectoryPath ) || !Directory.ExistsdirectoryPath )  )
      {
        return;
      }
 
      try
      {
        // Get the access rules of the specified files (user groups and user names that have access to the directory)
        var rules = File.GetAccessControl(directoryPath).GetAccessRules(truetruetypeof (SecurityIdentifier));
 
        // Get the identity of the current user and the groups that the user is in.
        var groups = WindowsIdentity.GetCurrent().Groups;
        string sidCurrentUser = WindowsIdentity.GetCurrent().User.Value;
 
        // Check if modifieng is allowed
        bool allowModify =
          rules.OfType<FileSystemAccessRule>().Any(
            rule =>
            (groups.Contains(rule.IdentityReference|| rule.IdentityReference.Value == sidCurrentUser&&
            rule.AccessControlType == AccessControlType.Allow &&
            (rule.FileSystemRights & FileSystemRights.Modify== FileSystemRights.Modify);
 
 
        if (allowModify)
        {
          return;
        }
 
        
        DirectoryInfo di = new DirectoryInfo(directoryPath);
        DirectorySecurity directorySecurity = di.GetAccessControl();
        bool modified;
        
        try
        {
          // Try to add modify rights to all users in Users 
          FileSystemAccessRule fileSystemAccessRule = new FileSystemAccessRule("Users"FileSystemRights.Modify,
                                                                               AccessControlType.Allow);
          directorySecurity.ModifyAccessRule(AccessControlModification.SetfileSystemAccessRuleout modified);
        }
        catch
        {
          // Try to add modify rights to curent user
          string identity = Environment.UserDomainName + "\\" + Environment.UserName;
          FileSystemAccessRule fileSystemAccessRule = new FileSystemAccessRule(identityFileSystemRights.Modify,
                                                                               AccessControlType.Allow);        
          directorySecurity.ModifyAccessRule(AccessControlModification.SetfileSystemAccessRuleout modified);
        }
      }
      catch
      { }
 
    }

2012-01-26

How to execute an .SQL script file using C#

If you need to execute TSQL script inside C# code using only standard libs then you can use this.





FileInfo file = new FileInfo(@"E:\someSqlScript.sql");
string script = file.OpenText().ReadToEnd();


  // split script on GO command
  IEnumerable<string> commandStrings = Regex.Split( script, "^\\s*GO\\s*$", RegexOptions.Multiline );

  Connection.Open();
  foreach( string commandString in commandStrings )
  {
    if( commandString.Trim() != "" )
    {
      new SqlCommand( commandString, Connection ).ExecuteNonQuery();
    }
  }     
  Connection.Close();