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);
}
#>


Monday, December 18, 2017

Dumping objects in c#

Hi,

I had a look at different possibilities to .net objects. First I was like: "just serialize that stuff and everything will be fine", but the more I thought about it, the more I realized that I needed more...

First of all: LinqPad did a great job with its functionality to dump objects, which was very inspiring to me...

see:



... so what might be a good solution to embed into our code...?

Good fitting solution seemed to be ObjectDumper (unfortunately you can find different solutions with the same name in google):

ObjectDumper (version: stone-age)



ObjectDumper (version: old)



ObjectDumper (not a single-file-solution anymore, Options to ignore fields)



ObjectDumper (Finally the current version without a single commit in the last 2 years... same version as CodePlex?)



So I started further testing with the github version:


  • installation: copy Dumper.cs and DumperOptions
  • DumperOptions can be removed easily... only 1 line must be patched (the rest is just handover of the options object into the recursive call)


IEnumerable<FieldInfo> fields = XY ? Enumerable.Empty<FieldInfo>() : type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

you can replace XY by a constant or a static field, so even the github version can be a single file solution again.

  • alternatively nuget is available (as already mentioned)
  • its a simple recursive solution based on GetFields and GetProperties
  • can read private data using reflection but can not handle static members
  • Every reference type is pushed into an object of class ObjectIDGenerator generating making it easy to make cross-references of objects (e.g.: backing field and property)
    • not a feature I really need, so I tried to delete it, but found out that it is a perfect solution to remove circular stepping into the code, so it is not only for printing purpose.
For me it works perfectly.

The following Test shows a first impression:

        public class Data
        {
            private int secret = 15;
            private string secondSecret = "15";
            public static string staticData = "123";
            public int Public => secret * 2 + 3;
            public string Something => "something";
            public int StoredData { get; set; }
            public string StoredData2 { get; set; }
            public Data()
            {
                this.StoredData = 1;
                this.StoredData2 = "1";
            }
            public Data2 data2 = new Data2();
            public class Data2
            {
                public bool IsData { get; set; } = false;
            }
        }

Dumped:

#1: data [DumpTester.Program+Data]
{
   properties {
      Public = 33 [System.Int32]
      #2: Something = "something" [System.String]
      StoredData = 1 [System.Int32]
      #3: StoredData2 = "1" [System.String]
   }
   fields {
      secret = 15 [System.Int32]
      #4: secondSecret = "15" [System.String]
      <StoredData>k__BackingField = 1 [System.Int32]
      <StoredData2>k__BackingField = "1" [System.String] (see #3)
      #5: data2 [DumpTester.Program+Data+Data2]
      {
         properties {
            IsData = False [System.Boolean]
         }
         fields {
            <IsData>k__BackingField = False [System.Boolean]
         }
      }
   }
}
you see:
  • no static info
  • AutoProperties with Backing-Fields
  • For reference-auto-properties you see the linkage between Prop and Field (see #3)
  • ValueTypes have no reference
  • Types in the system namespace are not dumped


kr,
Daniel

Thursday, November 9, 2017

benchmarking

Found a cool benchmarking nuget-package. It is called nbench and unfortunately I am not sure if the project is dead or not, but nevertheless the current state can add to the functional unit test the non-functional performance test which is quite cool.

It can be used for .net and .net core projects with a variety of possibilities. This project fills one of the gaps of a nightly compile run and might be helpful in many cases to keep quality high.

see: https://github.com/petabridge/NBench

IIS development and exceptions

In a production environment it is often a good idea to hide some errors of e.g.: a web-page to be able to work on the root cause of the error in the background that finally the customer will not identify some strange behavior as a bug.

Exactly the opposite is true for developers and testers. Find bugs! Don't cover them with any UI candy or stuff... and exactly in this trap I fell into...

see customErrors on msdn: https://msdn.microsoft.com/de-at/library/h0hfz6fc(v=vs.110).aspx

and for web api 2 see: https://msdn.microsoft.com/en-us/library/system.web.http.filters.exceptionfilterattribute(v=vs.118).aspx
https://docs.microsoft.com/en-us/aspnet/web-api/overview/error-handling/exception-handling

see also AppDomain.UnhandledException, Application.ThreadException / Application.SetUnhandledExceptionMode (for WinForms), DispatcherUnhandledException (for WPF), Application_Error (IIS Global asax)

Be careful to disable stuff that makes it hard to find bugs during testing :-)