Monday, May 28, 2018

c# string concatenation beyond StringBuilder

I compared in a race with 1 million iterations the execution times of

  1. StringBuilder with an Action call to "Append" a single character (as string)
  2. StringBuilder with a function call to "Append" a single character (as string)
  3. direct string = string + character (as string)
  4. StringBuilder with an Action called to "Append" a single character (as string) but initialized with 1M+1 size
  5. StringBuilder with a direct call to "Append" a single character (as string) initialized
  6. like 5 but a single character is added as a character.

Here the results in ms:


                V5 13
                V4 20
                V6 29
                V2 35
                V1 57
                V3 839343

As we see in V4/5/6 the initialization of a string builder without the need of reallocation is the absolute performance gain by far. The indirection using an action I would consider to be a cheap operation (see 4 vs 5). 

Using a StringBuilder, in this case, is a MUST as we can see it on the scoreboard. 

Interesting is that adding a character instead of a string doubles the execution time.

Comparing 1 and 4 makes it obvious how expensive the allocation of further storage is. 

In V3 garbage collection is called constantly.

While these results differ heavily (especially the numbers of the execution time) from run to run even on the same machine, they differ even more on different machines. Nevertheless, the statements derived are valid.

windows services - installation / deinstallation toggle script

Tried to find a script that installs a windows service if it is not installed and is capable to deinstall it if needed. Finally, I created myself the following:

sc query SERVICENAMEif %errorlevel% equ 0 (                echo uninstall                goto uninstall) else (                echo install                goto install)

Check if it is installed: if so uninstall, if not install. 

in :install call:

  • sc create SERVICENAME binpath=%cd%\Service.exe displayname="the service" start=demand 
    • if you need to set credentials for the startup then set: obj and password
    • %cd% is the current directory
  • sc start SERVICENAME


in :uninstall call:
  • sc stop SERVICENAME
  • sc delete SERVICENAME
    • delete can already be called even if the service is still in "stopping" state so in a script it works the right way even with some timing issues

Saturday, May 26, 2018

Printing web pages to pdf

As an extremely lazy person I started automating a lot of tasks... so many that I started writing the results (successful execution / failed execution) into the database to query for errors. Then I started writing the logs and execution times into db. It became so huge that we wrote a dashboard application to check state.

Today I want to forward this dashboard to some colleagues without granting them access to the platform... solution: mailing a pdf. I asked myself if there is a way to convert the html page into a pdf easily and found the following solution with chrome. The following snippets shows a batch script for windows.

@echo  %time%
@"C:\Users\{user}\AppData\Local\Google\Chrome\Application\chrome.exe" --headless --disable-gpu --print-to-pdf=c:\{outputFolder}\output.pdf file:///{pathToIndex}/index.html
@echo  %time%
@pause


Keep an eye on the fact that the screenshot is taken after onload is executed which can take several seconds.


Saturday, May 5, 2018

minimal .NET core web api

Hi,

today I tried to create a minimal .NET core web API application which returns a result as a foundation for a micro-service approach...

Here the code that works (pasted into main):


            WebHost.CreateDefaultBuilder(args)
                .Configure(app =>
                {
                    app.Run(async context =>
                    {
                        using (StreamWriter writer = new StreamWriter(context.Response.Body))
                        {
                            await writer.WriteAsync(await Task.FromResult("this works..."));
                        }
                    });
                })
                .Build()
                .Run();



Thursday, May 3, 2018

sql server local time and utc time

Hi,

there is a nice way to make a local DateTime value to a UTC DateTime value. First, I thought I can add a fixed amount of hours, but this is unfortunately not ok because change summer- to winter-time made the calculation invalid. So I found a very nice trick on StackOverflow...

http://sqlfiddle.com -> SQL Server

select getdate() as localtime, getutcdate() as utctime, datediff(hour, getdate(), getutcdate())

We can check the local time and the UTC time and add the delta as the offset to the local time. This is unfortunately only true if the local time value is in the same timezone as you are currently, but for my case it worked...

kr,
Daniel

Saturday, February 3, 2018

changing command prompt in windows 10

Hi,

today I tried something nerdy and wanted to improve my cmd - ux in windows (using windows 10).

First of all the useless stuff:

color a0

introducing a nice matrix look and feel.

Probably you remember the quote "follow the white rabbit", so I added a bunny in the prompt:

prompt $_       _$_      (\\                                  $_       \$B$B$_     __(_";$_    /    \$_   {}___)\)_                                             $_$P>

with cls (clear screen) you see the bunny up there and it appears after any command entered... funny for about 2 minutes... then really annoying... removed it...

sticking to the original output and add date and time turned out to be more useful

prompt $D $T$_$P$G

to much space, to few info...

prompt $D $T $C%USERDOMAIN%\%USERNAME%$F$_$P$G

more info!

ipconfig|for /f "tokens=12 delims=: " %G in ('findstr /i ipv4') do ( echo %G ) > ip.txt
set /p ip=<ip.txt
prompt $D $T $C%USERDOMAIN%\%USERNAME%$F IP: %ip%$_$P$G

linux / bash style:
prompt %username%@%userdomain%: $P $T$$

but best experience with simple stuff

prompt $P $T$G

kr,
Daniel

Tuesday, December 19, 2017

T4 Generation Templates VS 2017

Hi,

It took me a lot of time to find good resources about T4 (even if there are no real alternatives built-in for visual studio). Here a small template to create multiple files easily...

I used following resources exists using archive.org:

Further resources:


kr,
Daniel

<#@
template debug="false" hostspecific="true" language="C#" #><#@

assembly name="System.Core" #><#@

import namespace="System.Linq" #><#@
import namespace="System.Text" #><#@
import namespace="System.IO" #><#@
import namespace="System.Collections.Generic" #><#@

output extension=".log" #><#
CleanOutputFolder();

string propertyName = "Prop";
           
Enumerable.Range(1,3).ToList().ForEach(id => {

StringBuilder builder = new StringBuilder();
builder.AppendLine("public class Data" + id.ToString("00"));
builder.AppendLine(" {");
Enumerable.Range(1,3).ToList().ForEach(propId => {
builder.AppendLine(" public int "+propertyName+propId+" { get; set; }");
});
builder.AppendLine(" }");

CreateClass("Data"+id.ToString("00")+".cs", builder.ToString());
});


#><#+
public void CleanOutputFolder()
{
string templateDirectory = Path.GetDirectoryName(Host.TemplateFile);
string outputFolder = Path.Combine(templateDirectory, "output/");
foreach(var file in Directory.GetFiles(outputFolder))
{
File.Delete(file);
}
}

public void SaveOutput(string outputFileName)
{
      string templateDirectory = Path.GetDirectoryName(Host.TemplateFile);
      string outputFilePath = Path.Combine(templateDirectory, "output/", outputFileName);
      File.WriteAllText(outputFilePath, this.GenerationEnvironment.ToString());

      this.GenerationEnvironment.Remove(0, this.GenerationEnvironment.Length);
}

public void CreateClass(string fileName, string content)
{
#>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Test
{
<#= content #>
}

<#+
SaveOutput(fileName);
}
#>