Category: .NET Core

TILT–Some improvements-part 23

I wanted to have a share on TILTs, instead of a clipboard copy. Discovered that browser navigator has a native share – https://developer.mozilla.org/en-US/docs/Web/API/Navigator/share .

Implementation very simple ( not so good, )

private share(str:string): boolean{
if ('share' in navigator) {
    navigator
    .share({
    title: 'TILT!',
    text: str,
    url: environment.url + 'AngTilt/tilt/public/'+this.profileForm.controls['url'].value
    })
    .then(() => {
    console.log('Callback after sharing');
    })
    .catch(console.error);
    return true;
} else {
    return false;
}
}
  1. Added .NET Tools to have data about the outdated and more
feat: dot net tools
e0fd82f
{
  "version": 1,
  "isRoot": true,
  "tools": {
    "dotnet-project-licenses": {
      "version": "2.4.0",
      "commands": [
        "dotnet-project-licenses"
      ]
    },
    "dotnetthx": {
      "version": "0.2.0",
      "commands": [
        "dotnet-thx"
      ]
    },
    "powershell": {
      "version": "7.2.6",
      "commands": [
        "pwsh"
      ]
    },
    "dotnet-depends": {
      "version": "0.6.1",
      "commands": [
        "dotnet-depends"
      ]
    },
    "dotnet-outdated-tool": {
      "version": "4.1.0",
      "commands": [
        "dotnet-outdated"
      ]
    },
    "run-script": {
      "version": "0.4.0",
      "commands": [
        "r"
      ]
    }
  }
}

Tools used

Visual Studio

Visual Studio Code

CLI

TILT- TimeZone -part 22

To see if two TILTS are in the same day, it is not enough to see if the difference is less than one day. Could be less than 1 day in UTC – but in Europe/Bucharest can be the next day ( suppose that I put one TILT at 23:59:59 local time – the next TILT could be in 2 seconds )

In JavaScript one can have the IANA codes ( https://en.wikipedia.org/wiki/List_of_tz_database_time_zones ) by

Intl.DateTimeFormat().resolvedOptions().timeZone

In C# there I am receiving this and convert to TimeZoneInfo

var tz = TimeZoneInfo.FindSystemTimeZoneById(timeZone);
if (tz == null)
    return NotFound("cannot find timezone:" + timeZone);
var ser = tz.ToSerializedString();

Also, now we can verify to see that the time zone difference is ok

var tz = TimeZoneInfo.FromSerializedString(timezone);
if (tz == null)
    throw new TimeZoneNotFoundException(" cannote deserialize " + timezone);

var localTimeNow= TimeZoneInfo.ConvertTimeFromUtc(dateNowUTC, tz);

And the fact that I was thinking later – that means

  1. Database modification ( alter table , update )

  2. Backend verifications modified

  3. Sending data modified

  4. Tests added

And , of course, does not work in production . Added Hellang.Middleware.ProblemDetails to can debug more easy the error ( instead of 500 )

That comes from updating the existing database with default values

So reverting to the default timezone ( e.g. Europe/Bucharest) and now the tests are failing into CI ( that has not the time zone , being a stripped linux)

Adding to the CI

- name: Setup timezone
    uses: zcong1993/setup-timezone@master
    with:
    timezone: Asia/Shanghai

and now it works

Tools used

Visual Studio

Visual Studio Code

SSMS

Hellang.Middleware.ProblemDetails

zcong1993/setup-timezone@master

Vintage Development part 2 si RX

Pe   13 septembrie 2022, ora 19:30 ,  va fi un nou meetup ADCES despre

“Vintage Development part 2 si RX”

Details

Prezentare 1:
Vintage development part 2 – VB6.0, Classic ASP, Windows NT Server, Visual SourceSafe
Prezentator: Julian Atanasoae, https://www.linkedin.com/in/julianatanasoae/

Prezentare 2:
Reactive Extensions in .NET si JavaScript cu multe exemple in Angular
Prezentator: Andrei Ignat, http://msprogrammer.serviciipeweb.ro/
Descriere: In cadrul prezentarii o sa fie

  1. o introducere in Reactive Extensions

  2. citeva exemple despre ce inseamna Observables si cum se combina ele
  3. Va arata citeva exemple practice despre cum va ajuta Reactive Extensions sa programati mai usor call-urile de API
  4. Site-uri utile ( unul in Azure ) unde puteti incerca marbles

Va astept aici: https://www.meetup.com/bucharest-a-d-c-e-s-meetup/events/288197700/  , 13 septembrie 2022, ora 19:30
Multumesc
Andrei

TILT-AMS – about my software-part 21

One of the most related are data that fill the database for developer – and do not fill into production

AMS ( About My Software) could help . It generates an unique class that inherits

public class AboutMySoftware
{

public string Authors { get; set; }

public bool IsInCI { get; set; }

public string SourceCommit { get; set; }

public string CISourceControl { get; set; }

public string AssemblyName { get; set; }

public DateTime DateGenerated { get; set; }

public string CommitId { get; set; }

public string RepoUrl { get; set; }

}
    

The IsInCI recognizes if it is build on CI( deployed to prod lately ) or without (in the dev PC)

So I use like this

bool IsBuildFromCI = new XAboutMySoftware_78102118871091131225395110108769286().IsInCI;
if (IsBuildFromCI)
{
    hc.AddSqlServer(builder.Configuration["ConnectionStrings:DefaultConnection"],name:"database SqlServer");
}
else
{
    hc.AddSqlite(cnSqlite, name: "database Sqlite");
}

if (!IsBuildFromCI)
{
    using (var scope = app.Services.CreateScope())
    {
        if (File.Exists("Tilt.db"))
            File.Delete("Tilt.db");

        var dbcontext = scope.ServiceProvider.GetRequiredService<ApplicationDBContext>();
        dbcontext.Database.EnsureCreated();

        //seed db
        dbcontext.TILT_URL.Add(new TILT_URL()
        {
            Secret = "Andrei",
            URLPart = "TestAddWithNoData"
        });
        dbcontext.TILT_URL.Add(new TILT_URL()
        {
            Secret = "test",
            URLPart = "ClickToSeeMyTILTS"
        });
        await dbcontext.SaveChangesAsync();
}

Tools used

Visual Studio

AMS ( About My Software) – https://github.com/ignatandrei/RSCG_AMS/

TILT-Angular 14 and small updates-part 20

It is always good to have the latest version of NuGet packages – if it does not break the application, of course. Easy task when you have some automated test -and Visual Studio is doing this for you.

However, to update an Angular application where the version is fixed – a nightmare. I will do in a full time.

Also, being deployed to Azure, a few clicks on AppInsights and you have monitoring the application without instrumenting the code.

Also, added a feature to the application – you can add now a link to your TILT. This small modification went also when to display the TILT – keep remembering that any modification that you will do to the model will reflect in more than 1 place in the GUI.

Also, modifying the interface – show first the TILTs in a list, rather than in a calendar format.

Now the Angular 14 is on market – see https://blog.angular.io/angular-v14-is-now-available-391a6db736af. I was impressed by Title and NgMOdel onPush

So – update the cli ( npm update -g @angular/cli ) and crating a new app (ng new ) and adding Angular (ng add @angular/material)

So now it is time to bring the code to

  1. Fix the versions

  2. Add the code from the Ang13 app

  3. Add the title

For 1:

Fix the versions in package.json

Delete the npm_modules

npm i

For 2: I use WinMerge with a custom filter to exclude node_modules

Added missing npm packages from the previous application

Fix again the versions

For 3:

This is the code for TILT:

import { Injectable, NgModule } from '@angular/core';
import {
  RouterModule,
  RouterStateSnapshot,
  Routes,
  TitleStrategy,
} from '@angular/router';
import { LoginUrlGuard } from './login-url.guard';
import { LoginUrlComponent } from './login-url/login-url.component';
import { MyTiltComponent } from './my-tilt/my-tilt.component';
import { OnePublicTiltComponent } from './one-public-tilt/one-public-tilt.component';
import { PublicTiltsComponent } from './public-tilts/public-tilts.component';
import { TiltMainComponent } from './tilt-main/tilt-main.component';

const routes: Routes = [
  {
    path: 'tilt/public',
    component: PublicTiltsComponent,
    title: 'List of public tilts',
  },
  { path: 'tilt/public/:id', component: OnePublicTiltComponent },
  { path: '', redirectTo: '/tilt/public', pathMatch: 'full' },
  {
    path: 'tilt/my',
    component: MyTiltComponent,
    canActivate: [LoginUrlGuard],
    title: 'My tilts',
  },
  {
    path: 'loginURL',
    component: LoginUrlComponent,
    title: 'Login to add a tilt',
  },
];

@Injectable()
export class TemplatePageTitleStrategy extends TitleStrategy {
  override updateTitle(routerState: RouterStateSnapshot) {
    const title = this.buildTitle(routerState);
    if (title !== undefined) {
      document.title = `TILT! - ${title}`;
    } else {
      var arr = routerState.url.split('/');
      if(arr.length==0)
        document.title = `TILT! - AAA`;
      else
        document.title = `TILT! - tilts for ` + arr[arr.length-1];
    }
  }
}

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  providers: [{provide: TitleStrategy,  useClass: TemplatePageTitleStrategy}],
})
export class AppRoutingModule {}

Tools used

npm

ng

Visual Studio Code

WinMerge

TILT-Server Timing in Browser-part 19

For see fast what is happening with your server, you can use the Server Timing API.

One of the implementations for .NET is https://github.com/tpeczek/Lib.AspNetCore.ServerTiming .

Not a big deal – implemented separately with AOPMethodsCommon – but I think it is a good idea to use it.

The implementation was straightforward

builder.Services.AddScoped<ServerTiming>();
var app = builder.Build();
app.UseServerTiming();

And then use DI to get the instance of the class.

With this occasion , look how is different calling same method twice

vs

If you do not realize, there are 50 ms vs 1 ms . That difference is from caching

private async Task<TILT_Note_Table[]?> privateLatestTILTs(string urlPart, int numberTILTS)
{
    if (cache.TryGetValue<TILT_Note_Table[]>(urlPart, out var result))
    {
        return result;
    }
//code
}

Nice, right ? See the timing right in your browser.

Tools used

https://github.com/tpeczek/Lib.AspNetCore.ServerTiming

https://github.com/ignatandrei/AOP_With_Roslyn/

TILT-caching- part 17

If you want to read about, see https://docs.microsoft.com/en-us/azure/architecture/patterns/cache-aside

So , the public TILTS must be cached. Also, when a user makes a new TILT, the cache should be destroyed

The code for Memory Cache is very simple:

  1. Add to services
builder.Services.AddMemoryCache();
  1. Add an MemoryCache cache to the constructor
public MyTilts(IMemoryCache cache, 
  1. add caching to the function
 if (cache.TryGetValue<TILT_Note_Table[]>(urlPart, out var result))
            {
                return result;
            }
            
//code to retrieve
cache.Set(urlPart, ret,DateTimeOffset.Now.AddMinutes(10));
return ret;
  1. add destroy cache
await insert.InsertTILT_Note(noteOrig);
note.CopyFrom(noteOrig);
cache.Remove(url);   
  1. Modify tests to see this feature

TILT- cosmetic–part 16

The user must know something about the site. One of easy way is to display an intro – and I have choosed https://github.com/shipshapecode/shepherd

Also

  • display number of chars when putting a TILT

  • display a text area instead of an input
  • display links to my TILTS

Added also https://codescene.io/ . Can be valuable – but I should understand more how to use it.

Display latest date when it was deployed / compiled with AMS and the repo name. Added also links to Swagger and Blockly Automation

To see the progress , it is good to have a calendar.Discovered angular-calendar – to show events.

The exemaple at https://mattlewis92.github.io/angular-calendar/#/kitchen-sink is pretty self explanatory.

However, another 3 hours passed to have the display.

The ( quasy – final ) result can be seen below ( taken from http://tiltwebapp.azurewebsites.net/AngTilt/tilt/public/ignatandrei )


Tools

Tools Used

https://github.com/shipshapecode/shepherd

VSCode

https://github.com/ignatandrei/RSCG_AMS

Visua Studio

angular-calendar

TILT- GUI–part 15

Now the easy way for me is to create a web interface with Angular.

Nothing too complicated. This is how it looks for the TILTS at https://tiltwebapp.azurewebsites.net/AngTilt/tilt/public

Now , if I am going to a TILT Url , I can see the TILTs in the browser: https://tiltwebapp.azurewebsites.net/AngTilt/tilt/public/ignatandrei

For creating new TILTS , I can use the web interface https://tiltwebapp.azurewebsites.net/AngTilt/tilt/my

I enter a user name and a pasword and I can start adding the TILTS.

Tools Used

VSCode

Angular

TILT–CodeCoverage–part 14

The code coverage should be simple – just run tests and that’s all, right ?

For a reason, the coverlet console , dotnet-coverage ,dotnet test do not work – means that code coverage generated was 0% ( I have verified with dotnet-reportgenerator-globaltool )

The only that worked was altCover and this is the code into the yml:

dotnet test --no-build src/backend/Net6/NetTilt/NetTilt.sln  /p:AltCover=true /p:AltCoverAssemblyExcludeFilter="Humanizer|Moq|NUnit3|System|DB2GUI|AltCover|NetTilt.Tests" 

It was a good exercise. And now I have this: codecov

And for some tests written already, the code coverage is 46 %. A good one, I think …

Tools used

https://codecov.io

Moq

NUnit3

AltCover

Visual Studio

Andrei Ignat weekly software news(mostly .NET)

* indicates required

Please select all the ways you would like to hear from me:

You can unsubscribe at any time by clicking the link in the footer of our emails. For information about our privacy practices, please visit our website.

We use Mailchimp as our marketing platform. By clicking below to subscribe, you acknowledge that your information will be transferred to Mailchimp for processing. Learn more about Mailchimp's privacy practices here.