Executing code in intervals with…

Executing code in intervals with JS: setTimeout() and setInterval()

There are two ways you can execute the code in intervals with JS, but which one to use?

rtIXD7RoYl

OD9HaMdfuk

How do recursive setTimeout() and setInterval() differ?

The difference between the two versions of the above code is a subtle one.

  • Recursive setTimeout() guarantees the same delay between the executions. (For example, 100ms in the above case.) The code will run, then wait 100 milliseconds before it runs again—so the interval will be the same, regardless of how long the code takes to run.
  • The example using setInterval() does things somewhat differently. The interval you chose includes the time taken to execute the code you want to run in. Let’s say that the code takes 40 milliseconds to run — the interval then ends up being only 60 milliseconds.
  • When using setTimeout() recursively, each iteration can calculate a different delay before running the next iteration. In other words, the value of the second parameter can specify a different time in milliseconds to wait before running the code again.
    When your code has the potential to take longer to run than the time interval you’ve assigned, it’s better to use recursive setTimeout() — this will keep the time interval constant between executions regardless of how long the code takes to execute, and you won’t get errors.

Resource: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Timeouts_and_intervals

#javascript #setinterval #settimeout

Linode Object Storage with .NET and C#

Linode Object Storage is now available on Frankfurt data centre [1]. It is much more affordable and easier to manage unstructured data such as content assets (images, files etc..), sophisticated and data-intensive storage challenges around artificial intelligence and machine learning.

Since it is S3-compatible object storage, we can use AWS SDK for .NET for any operations needed.

1. Create a Project

dotnet new console 

2. Add Amazon SDK

dotnet add package AWSSDK.S3 

3. Example: List the buckets

class Program
    {
        static void Main(string[] args)
        {
            string accessKey = "**";
            string secretKey = "**";

            var config = new AmazonS3Config
            {
                RegionEndpoint = RegionEndpoint.EUCentral1, // Our bucket is on eu data center
                ServiceURL = "https://eu-central-1.linodeobjects.com" 
            };
            var amazonS3Client = new AmazonS3Client(accessKey, secretKey, config);
            ListMehmetBuckets(amazonS3Client).Wait();

        }

        static async Task ListMehmetBuckets(AmazonS3Client amazonS3Client)
        {
           var listBucketResponse = await amazonS3Client.ListBucketsAsync();
            foreach (var bucket in listBucketResponse.Buckets)
            {
                Console.Out.WriteLine("bucket '" + bucket.BucketName + "' created at " + bucket.CreationDate);
            }
            if (listBucketResponse.Buckets.Count > 0)
            {
                var bucketName = listBucketResponse.Buckets[1].BucketName;
                var listObjectsResponse = await amazonS3Client.ListObjectsAsync(bucketName);
                foreach (var obj in listObjectsResponse.S3Objects)
                {
                    Console.Out.WriteLine("key = '" + obj.Key + "' | size = " + obj.Size + " | tags = '" + obj.ETag + "' | modified = " + obj.LastModified);
                }
            }

        }
    }

You need to enable Object Storage in your Linode account before all. Check Linode docs for the details.
That’s all.

[1] Linode Storage Solutions
#linode #objectstorage #amazon-s3 #amazon-sdk-net

ASP.NET Core 3 Service…

ASP.NET Core 3 Service Registration – AddControllers() AddControllersWithViews() AddRazorPages()

With v3 and higher, there are several ways to register MVC. This way the application can only use what it requires, not the whole framework. This would result with a smaller size and being not sure, better performance.

AddControllers()

If you are developing an API, go with this. This is only for API-related features, Views or pages are not supported.

AddControllersWithViews();

This adds API + Views but not Pages. If you “dotnet new mvc”, it uses this code.

AddRazorPages()

This adds support for Razor Pages and minimal controller support. If you “dotnet new web”, it uses this code.

These can be combined as well. The following is equivalent to calling AddMvc in ASP.NET Core 2.2:

  
services.AddControllersWithViews();
services.AddRazorPages();

Resources:

https://docs.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-3.1&tabs=visual-studio-code#mvc-service-registration

https://www.strathweb.com/2020/02/asp-net-core-mvc-3-x-addmvc-addmvccore-addcontrollers-and-other-bootstrapping-approaches/

#aspnetcore #dotnet #net-core

Deserialize json array with System.Text.Json

Json Data

[
  {
    "FirstName": "Brick",
    "LastName": "Heck"
  },
  {
    "FirstName": "Sue Sue",
    "LastName": "Heck"
  }
]

And the class and method for deserialization

     public class Dto {
	public string FirstName { get;	set;}
	public string LastName {	get;	set;}
}
// Deserializer method
public static IList < Dto > DeserializeSystemNotificationEmail(string json) {
	var options = new JsonSerializerOptions {
		AllowTrailingCommas = true,
		PropertyNameCaseInsensitive = true
	};

	return JsonSerializer.Deserialize <IList<Dto>> (json, options);
}

A post about the performance of system.text.json

#json #System.Text.Json #net-core #dotnet

Talks & Videos

Nowadays, it seems that going to a tech conf is the only way to prove that you are a developer (?)
You can learn something from anything anyway, here are some videos I watched recently.

Angular

Introduction to Angular 8 – Alain Chautard
Handling Angular Forms Without Losing Your Sanity – Jennifer Wadella
These ARE the Angular Tips You’re Looking For | John Papa
Angular For Enterprise | Stephen Fluin
“N Things You Didn’t Know About the Router” | Deborah Kurata
The magic of template reference variables – Alain Chautard
How to Dynamically Insert & Remove Form Controls in Angular

JS

dotJS 2018 – John Papa – Choosing Your JavaScript Framework
Ready for Readable Code? – John Papa
The Future of Machine Learning & Javascript | Asim Hussain

Others

Keynote NDC Sydney 2016: If I knew then what I know now – Scott Hanselman

#angular #videos #talks

BrowserSync, Gulp and TypeScript

I was creating a simple web app with VueJS (without cli, no single file component) and I thought it would be good to have a local server which watches changes, auto-transpiles TypeScript and later maybe builds(minify, terser, copy files etc.) for the production. By using BrowserSync & Gulp, a typescript project can be easily watched, and the browser can be auto-reloaded in case of any changes. Let’s assume we have .ts files and index.html in “src” folder. The following gulpfile compiles the TS files into “dist” folder, watches for the changes and reloads the browser in case of changes. It still requires the build function for the production but it would be similar to development function, maybe terser plugin can be added.

const { series, watch, src, dest } = require('gulp');
var ts = require('gulp-typescript');
var sourcemaps = require('gulp-sourcemaps');
var tsProject = ts.createProject('tsconfig.json');
var server = require('browser-sync').create();

const paths = {
    scripts: {
        ts: 'src/*.ts',
        dest: 'dist/js/'
    }
};

function reload(done) {
    server.reload();
    done();
}

function serve(done) {
    server.init({
        server: {
            baseDir: './dist'
        }
    });
    done();
}


let development = function() {
    src('./index.html').pipe(dest('./dist/'));
    src('./css/**/*').pipe(dest('./dist/css'));
    src('./src/*.json').pipe(dest('./dist'));
    src('./assets/**/*').pipe(dest('./dist/assets/'));
    return tsProject.src()
        .pipe(sourcemaps.init())
        .pipe(tsProject())
        .pipe(sourcemaps.write())
        .pipe(dest('./dist/js/'));
};

const mywatcher = () => {
    console.log(paths.scripts.ts)
    const watcher = watch(paths.scripts.ts, series(development, reload))
    watcher.on('change', (path) => {
        console.log(`File ${path} was changed.`);
    });
};
const dev = series(development, serve, mywatcher );
exports.default = dev;

Another simple example. It uses terser and browsersync, dist folder is alway ready to deploy. It is for single js file but can be modified:

const { series, watch, src, dest } = require('gulp');
const terser = require('gulp-terser');
var server = require('browser-sync').create();

function copyAssets() {
    return src('src/assets/*')
        .pipe(dest('dist/assets'));
}

function copy() {
    return src('./src/app.js')
        .pipe(terser({
            mangle: { toplevel: true },
            compress: true
        }))
        .pipe(src('src/index.html'))
        .pipe(src('src/style.css'))
        .pipe(src('_redirects'))
        .pipe(dest('dist/'));
}

function reload(done) {
    server.reload();
    done();
}

function serve(done) {
    server.init({
        server: {
            baseDir: './dist'
        }
    });
    done();
}


const watcher = () => {
    const watcher = watch('src', series(copyAssets, copy, reload))
    watcher.on('change', (path) => {
        console.log(`File ${path} was changed.`);
    });
};
exports.default = series(copyAssets, copy, serve, watcher);

There is a gulp plugin for the same purpose: https://www.npmjs.com/package/gulp-webserver

Use browsersync to start a server from a folder and watch all the files for changes:

 browser-sync start --server './' --files './'

Links:
1. https://www.browsersync.io/docs/gulp
2. https://gulpjs.com/docs/en/api/watch
3. https://css-tricks.com/gulp-for-beginners/
#typescript #gulp #vuejs #javascript

Angular – Scroll to a…

Angular – Scroll to a div in child component

Child Component

<div  #scrollToPoint>
div to scroll
 </div>

Return scroll point to parent

 @ViewChild('scrollToPoint', { static: false }) scrollToPoint: ElementRef;
  constructor() { }
  ngOnInit() {
  }
  getScrollPoint() {
    return this.scrollToPoint;
  }

Parent Component

  @ViewChild(ChildComponent, { static: false }) childComponent: ChildComponent;
 scroll() {
    this.ChildComponent.getScrollPoint().nativeElement.scrollIntoView();
  }

This would work fine. If you have another button in a child and want to listen to that to scroll, you can add an event emitter:

Parent HTML

<app-child-hero (startHereClick)="scroll()"></app-child-hero> >

Child HTML

<button type="button" class="btn btn-danger" (click)="startHere()">Start Here</button>

Child Class

 @Output() startHereClick: EventEmitter<boolean> = new EventEmitter();
 startHere() {
    this.startHereClick.emit(true);
  }

#angular

#scrolltopoint