Friday, August 28, 2015

Things learned from C# in Depth

I recently finished reading through C# in Depth , and I learned a ton about language features that I haven't been using. Many of these features allow for cleaner code and less code, which both make my job easier. 

Automatic property initializer
public string MyString
{ get; set;}
Easier object initialization
new MyClass()
     new Product   {name=value},
     new Product()
Named arguments
public method(int a)
call like Method(a:5)
Lambda expression – these basically remove the nastiness of using delegates
products.Sort(delegate(Product x, Product y)    
                            return x.Name.CompareTo(y.Name); 
                       } );

Using lambda
products.Sort((x, y) => x.Name.CompareTo(y.Name));
Extension methods – you know how you have global utility class? Extensions methods make it look like a method is part of the class calling it, which clarifies intent.
static void DoStuff(this MyClass mc, string me)
{ = me }

In the calling code...
Mc = new MyClass();

Enumerable has a lot of extension methods available.

Nullable types and the null coalescing operator (??) – these features make parsing database results a lot easier.
int? A = null
int B = 5
int C = a ?? b
C would be set to B, because A is null

Optional parameters – so you don’t have to have a whole bunch of overloads
public void DoStuff(int a, int b = 2)

caller can then do DoStuff(1) or DoStuff(1, 3)
Implicitly typed local variables using ‘var’
var m = new MyClassWithAReallyLongName();

LINQ is a huge feature, that really improves the way you handle data processing. To me, it allows you write SQL-like statements in C# for any data source (objects, database, xml).

I knew of this before, but just haven’t used it. One of the huge benefits of LINQ that I can put into practice right away is replacing raw SQL queries with LINQ-to-SQL.
var query = from user in userList           
                    select user;

this gets transformed by the compiler to the following:

var query = userList .Select(user => user);

You can type either statement.

LINQ-to-XML – putting this here separately from LINQ.

Working with XML programmatically has always been awkward, am I right? Well, LINQ-to-XML makes it feel natural. The statements you type pretty much look exactly like the resulting XML doc!
new XElement("root",    
        new XElement("person",      
                new XElement("job", "coder")),   
        new XElement("other-person"));

Would generate this
</ person > 
  <other-person />

dynamic keyword – declare a type without the type being known at compile time. This is excellent for interop. I don’t think I’ll use this often.

To boil it down into one sentence: this removes a lot of the tediousness when writing asynchronous code
Anonymous type

These are good when you don’t want to take the time to create a fullblown class for a simple data container class.
var spot = new { Name = "Spot"}; 
var rex = new { Name = "Rex”};

Anonymous methods

When a method wants a delegate, you can pass it an anonymous method. This is awesome, because then you don’t have to type out the method somewhere else. Programmers just hate typing!
x.ForEach(n => Console.WriteLine(Math.Sqrt(n));

Namespace alias

Useful when you don’t feel like typing out the full namespace, or ya know, when you want to clarify intent.
using WinForms = System.Windows.Forms; 
Monitor.Enter(lock, ref wasAcquired) 

This can be used to do the Enter call in a try-catch, then release the lock in the finally if the lock was acquired. Better than Monitor.Enter(lock).

Wednesday, August 26, 2015

Dynamics GP - Cannot insert the value NULL into column 'ColumName', table 'DATABASE.dbo.TABLENAME'; column does not allow nulls. INSERT fails.

I'm doing an INSERT and not specifying all the columns, which should then use the default value. Instead i'm getting the error:
Cannot insert the value NULL into column 'ColumName', table 'DATABASE.dbo.TABLENAME'; column does not allow nulls. INSERT fails.

In my case the table is missing the default bindings. Just run this:

EXEC [dbo].[smBindTableDefaults] 0

Friday, August 14, 2015

My shift key appears to be stuck

My shift key appears to be stuck. Every time i try to type a number it outputs the symbol above the number instead. Example: @ when i press 2


  1. Start button -> search for "Ease of Access Center"
  2. Click "Start On-Screen Keyboard."
  3. Click the left SHIFT key on and off
  4. Click the right SHIFT key on and off
  5. Close the "Start On-Screen Keyboard"


Thursday, August 13, 2015

Executing SQL from PowerShell

For some reason when I upgraded to SQL Server 2012, SSMS boots very slowly. Well, if I want to just execute a quick query I don't want to have to wait. Programmers don't do well when they have to wait for results :). I always have Powershell ISE open, so I figured being able to execute SQL queries from that would be nice and efficient.

$sql = "SELECT * FROM Table"
Invoke-Sqlcmd -Query $sql -ServerInstance "server\instance" -Database "database" | ft


Thursday, August 6, 2015

Using named capture groups in regex C#

This will parse a string in the format of:
Key3:10:00:01 pm

            Regex regex = new Regex(@"(?<key>\w+):(?<value>.*)\r\n");
            MatchCollection matchCollection = regex.Matches(input);
            foreach (Match match in matchCollection)
                string key = match.Groups["key"].Value;
                string value = match.Groups["value"].Value;

Monday, August 3, 2015

Quick reference - SQL_FormatStrings()

 "SQL_FormatStrings() function which will double up single quote characters and also surround the string with starting and ending single quotes. This will avoid the issues caused by a single quote in the data terminating a string early". says Developing for GP

Use this when doing passthrough SQL when you need to specify string values.

local text sql;
sql = "SELECT * FROM myTable WHERE Field = " + SQL_FormatStrings("Hello");

That will turn into SELECT * FROM myTable WHERE Field = 'Hello'