.NET SQL Functions Class

If you use Entity Framework you will enjoy learning about the SQL Functions Class. The SQL function class provides a way to call common database functions in your Entity Framework LINQ queries.

There are too many functions provided by this class to cover them all. You will find some classic SQL functions like Stuff and GetDate. You will also find mathematical functions such as PI and Log.

It is important to note that these functions can only be called within the context of the LINQ to Entity queries. An example of how you would use these functions is as follows:

var results = _testContext.Persons
.Where(x => x.CreateDate >= SqlFunctions.GetDate())
.ToList();

Assert.AreEqual(1, results.Count);
Assert.AreEqual("Sam", results.First().Name);

More Information

You can explore the many functions provided by the SQLFunctions class on MSDN. This class will not be avaliable in the .NET Core project. To see a list of libraries that will be avalible in the .NET Core project check out the corefx-progress GitHub repository.

Roslyn Diagnostic Analyzer Talk

I am giving a talk today at the 23 Boston Code Camp! I will presenting on the new Visual Studio 2015 Roslyn Diagnostic Feature. There are going to a lot of great talks there today so be sure to check them out.

Slides

You can find the slides at http://ow.ly/KCoba and the source for the demo analyzer here.

Resources

More Information

Thanks to everyone who came out today and a special thanks to the sponsers of the event!

.NET Secure String

Today we are going to take a look in the System.Security namespace to learn how to create secure strings in .NET Framework. The standard .Net string is stored in managed memory giving you no way to control when it is destroyed. This is not ideal for applications that need to work with sensitive information such as Social Security Numbers or Credit Card numbers. If your application works with this type of data it might be worth taking some time to evaluate the SecureString class.

The SecureString class will automatically encrypt the data when it is stored in memory. It also implements the IDisposable interface so that you can control when the string is destroyed. Even better than just freeing memory, the Dispose method writes binary zeros to the allocated memory before it is freed. This ensures that the string is not readable after it’s memory is done being used.

Another feature of SecureString is the string created is mutable until you tell the string to be read-only. This means it can be manipulated over time, where as the standard string class is immutable. Since it is not related to the standard string class it does not have some of the same methods to compare or convert the string. The documentation states this is to help prevent any accidental/malicious exposure and suggests using the Marshal class.

To use it:

//  Could take input from console or another api
var secureString = new SecureString();

secureString.AppendChar('s');
secureString.AppendChar('e');
secureString.AppendChar('c');
secureString.AppendChar('u');
secureString.AppendChar('r');
secureString.AppendChar('e');

IntPtr secureStringPointer = IntPtr.Zero;
try
{
  // copy to unmanaged memory and decrypt
  secureStringPointer = Marshal.SecureStringToGlobalAllocUnicode(secureString);

  // use the pointer with a function like Win32 API logon
  // Full example at https://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.securestringtoglobalallocunicode(v=vs.110).aspx
  // returnValue = LogonUser(userName, domainName, secureStringPointer, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref tokenHandle);
}
finally
{
  Marshal.ZeroFreeBSTR(secureStringPointer);
}

More Information

A few .NET Api’s that use the SecureString class are:

You can find out more information on the MSDN SecureString page. The original announcements on the the .NET Security Blog has good information on why SecureString is designed the way it is.

I did use it in some the samples but you will find that I don’t have to many real world examples. From my current understanding, taking the input from a string or moving the the value into a string when done would defeat the purpose since we would be giving up control over the value to the Garbage Collector. Using existing API’s such as the password input from a WPF form and then encrypting a X509 Certificate seems to be one of the few useful scenarios available today. If you have any good examples on how to use this class I would love to get some feedback.

.NET DNS Class

Continuing with the theme of the last post, which covered the IPAddress class, this week we will take a look at the DNS class. The DNS class also lives in the System.Net namespace and helps simplify working with DNS servers to resolve IP addresses and hostnames. Whether you need to know the IP Address from the hostname, or you have a hostname and you need to know the IP Address, the DNS class will help make DNS resolution simple.

To retrieve IP addresses via the hostname:

IPAddress[] ipAddresses = Dns.GetHostAddresses("jamessturtevant.com");

Assert.AreEqual("162.255.119.254", ipAddresses.First().ToString());

To get the host namevia the IP address:

// May fail if IP changes
IPHostEntry hostEntry = Dns.GetHostEntry("192.30.252.131");

Assert.AreEqual("github.com", hostEntry.HostName);

More Information

The above functions show how to make synchronous calls but the DNS class has recently been given asynchronous support. You can find the asynchronous version and more information about the DNS class on the MSDN page. You can also find runnable examples on my .NET Framework Tour GitHub repository.

.Net IPAddress Class

This week for the .NET Framework Tour, we are going to take a brief look at the the IPAddress Class which lives in the System.Net namespace. The IPAddress class helps a developer work with IP addresses. It can parse IPv4 and IPv6 strings and returns an IPAddress object that give us helpful information. The class also helps with the manipulation of IP addresses.

To parse an IP address:

IPAddress address;

Assert.IsTrue(IPAddress.TryParse("10.2.12.123", out address));
Assert.IsFalse(IPAddress.TryParse("10.2.12.1234", out address));

IPAddress ipv6Address = IPAddress.Parse("2001:0db8:85a3:0000:0000:8a2e:0370:7334");
Assert.AreEqual(AddressFamily.InterNetworkV6 , ipv6Address.AddressFamily);

To convert an IPv4 address to IPv6 address (and vice versa):

IPAddress ipv4Address = IPAddress.Parse("10.3.5.156");

IPAddress ipv6Address = ipv4Address.MapToIPv6();
Assert.AreEqual(AddressFamily.InterNetworkV6, ipv6Address.AddressFamily);

More Info

The class can do a lot more than just parse strings so check out MSDN for more information about the IPAddress class. There is also a samples project on GitHub so you can play with the class to learn a bit more.

The class is schedule to come over to the open source .NET Core Libraries. See all items currently planned to move to the new open source library here.