Obelink.ToString()

My random thoughts on software development

Tag: Visual Basic .NET (page 2 of 2)

Use LINQ to compare two sequences in Visual Basic .NET

One of the smartest ways to verify if two sequences of the type List(Of T) are equal, is to use LINQ. Or more specific, the extension method SequenceEqual(). It will compare both list in exact order and it returns a Boolean value, indicating if both lists are exactly the same.

Continue reading

Year first date literals in Visual Basic .NET

Since I write on a daily base unit tests, I’m wondering more and more why there is not an easy – and especially unambiguous – way to provide a hardcoded date to a variable or procedure argument. Do you know, without any doubt, what this date actually means?

Dim thisYearsBirthday As Date = #5/6/2015#

Was I born on the 5th of June or the 6th of May? Visual Basic .NET will support now a good ISO-standard, which starts with the year. It follows the convention of ‘yyyy-MM-dd’ and you can even use slashes as separators. You can also provide the time if you want.

Dim todayDateWithDash = #2015-02-13#
Dim todayDateWithSlash = #2015/2/13#
Dim nowDateTime24 = #2015-02-13 19:59:00#
Dim nowDateTime12 = #2015-02-13 7:59:00 PM#

Console.WriteLine(todayDateWithDash.ToLongDateString())
Console.WriteLine(todayDateWithSlash.ToLongDateString())
Console.WriteLine(nowDateTime24.ToString("yyyy-MM-dd HH:mm:ss"))
Console.WriteLine(nowDateTime12.ToString("yyyy-MM-dd hh:mm:ss"))

The results are shown in the screenshot below. Please note that you can specify the time part as 24-hour format as well as the 12-hour format. The ToLongDateString() extension methods formats the dates to the Dutch language, but I’m sure that you will understand the concept.

vb2015yearfirstliteralnoshadow_thumb

BTW… for the people who are still doubting about my birthdate… I was born on a 6th of May!

Show generated SQL of Entity Framework in Visual Basic .NET

When you are writing LINQ queries against an Entity Framework context, you don’t have to worry about the SQL which is generated and executed. However, in some cases you may be interested in this SQL. It’s quite easy to switch on a logging mechanism which will be display all executed SQL in your Debug window. You have to provide an Action to the DbContext.Database.Log property. You provide a lambda with the functionality you want. If you want you can log this output also to a file or for example the Clipboard.

Continue reading

Query a CSV file with LINQ and Visual Basic .NET

Once in a while I’m still surprised by the functionality of LINQ. I saw a question on the Internet from a developer who asked if it is possible to query against Comma Separated Values (CSV) in a file. Based on one of the answers I wrote this post, because it’s really great what you can do with so less source code. As you probably already knew, I’m a big fan of LINQPad, which I will use to demo my examples. One of the nice features is the extension method .Dump(). As you can imagine, this will dump (or write) the data to the Results window of LINQPad. It works only in LINQPad, so, if you want to try this source in Visual Studio, you have to remove the .Dump() statements and write your own code to display the results.

Dim path = GetAndCreateFilePath()
 
Dim results = (From line In File.ReadAllLines(path).Dump("Lines read")
               Let value = line.Split(",").
                                Skip(1). ' Skip the RowNumber
                                Select(Function(x) Integer.Parse(x))
               Select New With {.MinimumValue = value.Min(),
                                .MaximumValue = value.Max(),
                                .Average = value.Average(),
                                .RowTotal = value.Sum()}).ToList().
                                                          Dump("Statistics")
  
File.Delete(path)

As you can see in the VB.NET code above, first we create a file, then we read and query this file and in the last statement we delete this temporary file. Before diving more deep in this code, you have to see what we are writing to disk in the GetAndCreateFilePath() procedure. The lines starts with a row number and four numeric values.

Private Function GetAndCreateFilePath() As String
 
    Dim filePath = Path.GetTempFileName()
 
    Dim stringBuilder As New StringBuilder
    With stringBuilder
        .AppendLine("1, 309, 88, 125, 825")
        .AppendLine("2, 458, 258, 198, 189")
        .AppendLine("3, 87, 587, 675, 136")     
    End With
 
    File.WriteAllText(filePath, stringBuilder.ToString())
 
    Return filePath
 
End Function

In the first code snippet we querying a LINQ statement against a List(Of String), the line variable. With help of the Split() function, we divide this line into an array of String, with in each element a value from the line. Because we are not interested in the first value, the Row Number, we skip this value with Skip(1). As a side note it’s good to mention that starting from Visual Basic.NET 2015 you can use inline comments. In this example it really helps to explain why we are skipping the first element of the array. If we have selected the correct range of data, we can easily project this data, and calculations on it to an anonymous type. And as earlier said, the Dump() method writes the data to the Results window of LINQPad. You can use this method more than once in one LINQ statement. First we are writing the actual lines read and at the end the statistics of the data. The power of LINQ is really amazing!

querycsvwithlinqandvisualbasicnet

Loop in batches trough an IEnumerable in Visual Basic .NET

Sometimes you need to handle data in batches. With help of this extension method, all collections derived from an IEnumerable are easy to populate in batches. Note that this code needs to be placed in a static class, so in terms of VB.NET in a module.

Continue reading

Left Outer Join in LINQ with Visual Basic .NET

Many developers encounters problems when trying to mimic the functionality of a Left Outer Join in LINQ. To be honest, the needed code is on first sight a bit strange. You can use a Group Join … Into .. and the DefaultIsEmpty() method. Let’s start with a regular (Inner) Join example. It uses the NorthWnd database and will retrieve all customers with at least one order.

Continue reading

Use a custom connectionstring in Entity Framework

For a customer I needed to customize the way an Entity Framework 6 database-first project connects to a SQL Server database. Normally you specify the connectionstring including some metadata about the model in the app.config file. You can choose either to use Windows Authentication or SQL Authentication. If you want to use SQL Authentication you must provide the username and password. These are by default not encrypted and my customer did not like the idea that users who have access to the application can open the configuration file with for example Notepad, and can read and in a worst scenario misuse these credentials. To help secure information in configuration files there are alternatives, but all are very hard to implement and will still ask you to write custom code for Entity Framework. As often, more ways lead to Rome, but I came with the following solution. I build manually the connectionstring in the constructor of the DbContext. First I added these keys in the section of the config file. You can choose your own encryption method to encrypt one or more keys.

Continue reading

Using serialization to store your configuration

Today a member of the VBcentral.nl community asked a question in one of our news groups. He was wondering if is there is a smart way to store configuration data in a file. I promised him to make a small sample how to use XmlSerialization to store data in a Xml-file. And of course, how to read it back from that file.

Continue reading

Newer posts

© 2021 Obelink.ToString()

Theme by Anders NorenUp ↑