Friday, June 28, 2019

WinForms: How To Add a Border To a Panel Control

To add a border to a Panel control, extend the control with the following class:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
 
class MyPanel : Panel
{
    private Color colorBorder = Color.Transparent;
 
    public MyPanel() : base()
    {
        this.SetStyle(ControlStyles.UserPaint, true);
    }
 
    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        e.Graphics.DrawRectangle(
            new Pen(
                new SolidBrush(colorBorder), 2), e.ClipRectangle);
    }
 
    public Color BorderColor
    {
        get { return colorBorder; }
        set { colorBorder = value; }
    }
}
You can then use the new BorderColor property to set the border to any color you like.

Thursday, June 27, 2019

Useful Visual Studio Extensions and Addons

JetBrains ReSharper
ReSharper extends Visual Studio with over 1700 code inspections for C#, VB.NET, ASP.NET, JavaScript, TypeScript and other technologies. For most inspections, ReSharper provides quick-fixes (light bulbs) to improve code in one way or another.

SubMain GhostDoc
GhostDoc is a free Visual Studio extension that automatically generates XML documentation comments for methods and properties based on their type, parameters, name, and other contextual information.

HideShow Comments (Visual Studio 2010, 2012,2013)
Hides comments and replaces them with a callout icon. The comments are shown as tooltip and when editing them.

Visual Studio Spell Checker (Visual Studio 2013, 2015)
An editor extension that checks the spelling of comments, strings, and plain text as you type or interactively with a tool window. Extra options are available to control how elements and attributes in XML and MAML files are spell checked.

Ref12 (Visual Studio 2013, 2015, 2017, 2019)
This extension lets you press F12 or use Go To Definition command to open the source code for anything in the .Net framework. You can easily jump to the actual source for things linq LINQ or WinForms or ASP.Net and see how they're implemented, including original comments. Just place the cursor on any class, function, or constant in the .Net framework and press F12 to open your default browser. No more “From Metadata” tabs!

SpecFlow
Use SpecFlow to define, manage and execute automated acceptance tests from business-readable specifications. SpecFlow acceptance tests follow the BDD paradigm: define specifications using examples understandable to business users as well as developers and testers. SpecFlow integrates with Visual Studio, but can be also used from the command line (e.g. on a build server).

Visual Studio Favorites (Visual Studio 2015, 2017, 2019)
Add a Favorites menu to Visual Studio to keep track of locations in Source Control or files in a Solution.

Wednesday, June 26, 2019

Tuesday, June 25, 2019

WPF: How To Remove The Min, Max and Close Buttons On a WPF Window

WPF doesn’t have a built-in property to hide the title bar’s Min, Max and Close buttons, however, you can do it with a few lines of P/Invoke.

First, add these declarations to your Window class:
private const int GWL_STYLE = -16;
private const int WS_SYSMENU = 0x80000;
[DllImport("user32.dll", SetLastError = true)]
private static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll")]
private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);

Then put this code in the Window’s Loaded Event:
private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
{
    var hwnd = new WindowInteropHelper(this).Handle;
    SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) & ~WS_SYSMENU);
}

No more window buttons. You also won’t have a window icon on the left side of the title bar, which means no System menu, even when you right-click the title bar – they all go together.

Note that Alt+F4 will still close the Window. If you don’t want to allow the window to close before the background thread is done, then you could also override OnClosing and set Cancel to true.

Saturday, June 22, 2019

Simple Code For (Un)Installing An Assembly To The GAC

The Microsoft tool GacUtil.exe could be in one of many places depending on what version of .Net is installed.
Rather than have a user try to find it, we can leverage the .Net Framework directly to perform GAC (un)install.
This is ideal for use in a Console application to (un)install a specific file.

Microsoft Links
Publish.GacInstall Method
Publish.GacRemove Method

Example:
Simple installer class that is installing the MyAssembly.dll assembly into the GAC.
ToDo: This may be more useful if it accepts the file name as a parameter.

using System;
using System.IO;
using System.EnterpriseServices.Internal; 
 
class GACInstaller
{
    static void Main(string[] args)
    {
        string assemblyName = "MyAssembly.dll";
        Console.WriteLine();
        Publish objPublish = new Publish();
        string file = Path.Combine(Directory.GetCurrentDirectory(), assemblyName);
 
        if (File.Exists(file))
        {
            try
            {
                objPublish.GacInstall(file);
                Console.WriteLine($"'{assemblyName}' successfully added to the cache");
            }
            catch (Exception error)
            {
                Console.WriteLine($"Error encountered when adding '{assemblyName}' to cache: {error.Message}");
            }
        }
        else
        {
            Console.WriteLine($"Cannot find specified '{assemblyName}' in current directory");
        }
    }
}

Wednesday, June 5, 2019

C#: Convert List<long> to List<string> and Vice Versa

List listOfNumbers = new List() { 1, 2, 3 };
List listOfStrings = listOfNumbers.ConvertAll(n => n.ToString());
listOfNumbers = listOfStrings.ConvertAll(long.Parse);

Tuesday, June 4, 2019

SQL: Concatenate Fields From Multiple Rows In SQL

In SQL Server 2005 and up you can use the following SQL code to concatenate fields from multiple rows.

Sample Data:
declare @YourTable table
(
    RowID int,
    HeaderValue int,
    ChildValue varchar(5)
)

insert into @YourTable values (1, 1, 'CCC')
insert into @YourTable values (2, 2, 'BBB')
insert into @YourTable values (3, 2, 'AAA')
insert into @YourTable values (4, 3, '123')
insert into @YourTable values (5, 3, 'A & Z')
RowID HeaderValue ChildValue
1     1           CCC
2     2           BBB
3     2           AAA
4     3           123
5     3           A & Z
The Concatenation Code:
set nocount off

select
    t1.HeaderValue,
stuff(
        (select ', ' -- delimiter
           + t2.ChildValue
         from @YourTable t2
         where t1.HeaderValue=t2.HeaderValue
         order by t2.ChildValue
         for xml path(''), TYPE).value('.','varchar(max)'),
       1, 2, '') as ChildValues
from @YourTable t1
group by t1.HeaderValue
Output:
HeaderValue ChildValues
----------- -------------------
1           CCC
2           AAA, BBB
3           123, A & Z

Monday, June 3, 2019

Visual Studio: Ignore Whitespace During Compare

Visual Studio, by default, will include whitespace in its comparison when comparing two files.

This is a workaround that seems to get around the problem.

In Visual Studio, select Tools / Options / Source Control / Visual Studio Team Foundation System and click the Configure User Tools button.

In the dialog, Add an item with the following settings:
  • Extension: .*
  • Operation: Compare
  • Command: C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\diffmerge.exe
  • Arguments: %1 %2 %6 %7 %5 /ignorespace

Depending on your Visual Studio version and installation path (x64/x86), the command option may be…

VS2010: C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\diffmerge.exe
VS2012: C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\diffmerge.exe
VS2013: C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\vsDiffMerge.exe
VS2015: C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\vsDiffMerge.exe
VS2017: C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\vsDiffMerge.exe
VS2019: C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\vsDiffMerge.exe

In the argument option leave it with the same number of arguments as the VS suggests and just add /ignorespace in the end. For example, in the VS2015 it will be:
%1 %2 /ignorespace
You can configure older versions of Visual Studio to use the latest Visual Studio compare tool using this method as well. Just set the path for the Compare tool in the older version to point to the path of the newer version.

Sunday, June 2, 2019

C#: Convert string[] to int[]

Given an array of integers in string form:
var myStrings = new string[] {"1", "2", "3"};
Convert the array of strings into an array of integers:
var myInts = Array.ConvertAll(myStrings, int.Parse);
An alternative way is to use LINQ, however that would require an extra call to ToArray to get an array:
var myInts = myStrings.Select(int.Parse).ToArray()

Saturday, June 1, 2019

Handy Online Tools For Developers

The following is a list of helpful online tools.

SQL Fiddle
If you do not know SQL or basic database concepts, this site is not going to be very useful to you. However, if you are a database developer, there are a few different use-cases of SQL Fiddle intended for you:

You want help with a tricky query, and you’d like to post a question to a Q/A site like StackOverflow. Build a representative database (schema and data) and post a link to it in your question. Unique URLs for each database (and each query) will be generated as you use the site; just copy and paste the URL that you want to share, and it will be available for anyone who wants to take a look. They will then be able to use your DDL and your SQL as a starting point for answering your question. When they have something they’d like to share with you, they can then send you a link back to their query.

You want to compare and contrast SQL statements in different database back-ends. SQL Fiddle easily lets you switch which database provider (MySQL, PostgreSQL, MS SQL Server, Oracle, and SQLite) your queries run against. This will allow you to quickly evaluate query porting efforts, or language options available in each environment.

You do not have a particular database platform readily available, but you would like to see what a given query would look like in that environment. Using SQL Fiddle, you don’t need to bother spinning up a whole installation for your evaluation; just create your database and queries here!

.Net Fiddle
Online .Net compiler (C#, VB.Net, F#)

Diff Now
DiffNow lets you compare text files, documents, binary files, and archives up to 2048KB in size. 

XPath Generator
The Xpath generator will help you automatically generate xpaths. Paste in your xml and place the cursor in the element you need the xpath to and it will generate an xpath. The xpath will be shown in the xpath results text area.

Online regex tester and debugger: JavaScript, Python, PHP, and PCRE
Free PCRE-based regular expression debugger with real time explanation, error detection and highlighting.

Binary Hex Decimal Ascii Converters
Easily convert bin, hex, decimal, and ascii numbers to each other. All you need is to open the conversion pair page and type the number in the relevant box.

Tables Generator
Generate tables, with data, in various formats; such as Markdown Tables for use with docuwiki. 

P/Invoke.Net
PInvoke.net is primarily a wiki, allowing developers to find, edit and add PInvoke* signatures, user-defined types, and any other information related to calling Win32 and other unmanaged APIs from managed code (written in languages such as C# or VB.NET).

.Net Reference Source Code
Browse the .NET Framework source code online, with search and navigation powered by Roslyn.

Collection Of Input Output Tools
The Online Tools site has a large list of online tools, including the following:
Hash
File Hash
Encode
Decode
Misc
CRC-16 CRC-16 Base32 Base32 Syntax Highlight
CRC-32 CRC-32 Base32 File Base32 File
MD2 MD2 Base64 Base64
MD4 MD4 Base64 File Base64 File
MD5 MD5 HTML HTML
SHA1 SHA1 URL URL
SHA224 SHA224
SHA256 SHA256
SHA384 SHA384
SHA512 SHA512
SHA512/224 SHA512/224
SHA512/256 SHA512/256
SHA3-224 SHA3-224
SHA3-256 SHA3-256
SHA3-384 SHA3-384
SHA3-512 SHA3-512
Keccak-224 Keccak-224
Keccak-256 Keccak-256
Keccak-384 Keccak-384
Keccak-512 Keccak-512
Shake-128 Shake-128
Shake-256 Shake-256

Performance: Linking a List of Child Objects To a List of Parent Objects

Many a time I've had to build a relationship where a parent object has a list of child objects linked to it, where the parent itself als...