Generating Easy and Secure Passwords in PowerShell

Hi Everyone,

So the other day, I found a much easier way to generate secure passwords in PowerShell. Before this, we had to have a list of all the available characters and put them into a CharArray, or ping an internet service like dinopass.com.

Not anymore!

From now on, whenever I need to generate a password in PowerShell, I will be using the

GeneratePassword()

Function from the [System.Web.Security.Membership] namespace. What this allows you to do, is generate a string of a specified length, with a specified amount of alphanumerical characters.

So if I wanted a password that was 10 characters long and had 5 alphanumerical characters, I would use:

[System.Web.Security.Membership]::GeneratePassword(10,5)

I usually just wrap that in a function because I’ve found you need to add the ‘System.Web’ assembly and it’s cleaner to add it in the function rather than the entire script. This is my new function:

function New-RandomPassword(){
    Add-Type -AssemblyName 'System.Web'
    return [System.Web.Security.Membership]::GeneratePassword(10,5)
}

Hope you learnt something from this 🙂

Using RxDart and Flutter to Create A Timer

Final product

Hi Everyone! Very long time without any content 😢 This year, as you can probably imagine, was very hectic. Something had to give, and unfortunately, it was this creative outlet that lost out. Let’s jump straight into something completely different!

I’ve been learning Flutter and mobile development, which has been very exciting! Today, I wanted to share with you a little example of a timer app built using Flutter with RxDart as a state management solution. Basically, that means not using the standard setState command in the Stateful Widget.

To kick things off, you’ll want to add the latest version of RxDart into your pubspec.yaml file. At the time of writing, this looks like the following:

rxdart: ^0.24.1

In the main.dart file, it can be kept pretty much as a blank slate. Only making sure to replace the home of the Scaffold with a new view. I like to create a separate folder for my ‘ui’ and my ‘state’.

We’ll kick off first by looking at the timer_state.dart that will be using RxDart. We need to create a new class, which I will call ‘TimerState’. In this new class, we need to create the following variables:

  • Private Stopwatch
  • BehaviorSubject of type String to track the timer display
  • BehaviorSubject of type bool to track whether the timer is running or not
  • A string for the initial display value set to ’00:00′
  • A bool for the initial running state of the timer, set to false

For the class builder, we need to build the two BehaviorSubjects. We’ll do that by creating the following class constructor:

TimerState({this.initialDisplay, this.initialIsRunning}) {
    _subjectDisplay = BehaviorSubject<String>.seeded(this.initialDisplay);
    _subjectIsRunning = BehaviorSubject<bool>.seeded(this.initialIsRunning);
}

Next, we need to create the two Streams that we can watch for changes to the timer display and whether the timer is running or not. We’ll use these in the UI:

Stream<String> get timerObservable => _subjectDisplay.stream;

Stream<bool> get isRunningObservable => _subjectIsRunning.stream;

To finish off the TimerState class, we need to build quite a few functions to help use the timer/stopwatch. Here’s a list below:

  1. Public function for starting the timer
  2. Private function for running the timer every second
  3. Private function for keep the timer running
  4. Private function for formatting the elapsed time to a minutes/seconds format
  5. Public function for pausing the timer
  6. Public function for resetting the timer
  7. Public function for resuming the timer
  8. Public dispose function to remove the BehaviorSubjects to avoid memory leaks

For simplisity sakes, here is the full class below:

import 'dart:async';
import 'package:rxdart/rxdart.dart';

///The class for the timer
class TimerState {
  ///The Stopwatch object for running the timer
  final Stopwatch _sWatch = Stopwatch();

  ///Creating a BehaviorSubject of type String for the Stopwatch display
  BehaviorSubject<String> _subjectDisplay;

  ///Creating a BehaviorSubject of type bool for the IsRunning variable
  BehaviorSubject<bool> _subjectIsRunning;

  ///The initial String value for the Stopwatch display
  String initialDisplay = '00:00';

  ///The initial bool value for the IsRunning variable
  bool initialIsRunning = false;

  ///The class builder
  ///Takes in the local initialDisplay and initialIsRunning to seed the
  ///subject behaviours
  TimerState({this.initialDisplay, this.initialIsRunning}) {
    _subjectDisplay = BehaviorSubject<String>.seeded(this.initialDisplay);
    _subjectIsRunning = BehaviorSubject<bool>.seeded(this.initialIsRunning);
  }

  ///A Stream for the Stopwatch String value
  Stream<String> get timerObservable => _subjectDisplay.stream;

  ///A Stream for the IsRunning bool value
  Stream<bool> get isRunningObservable => _subjectIsRunning.stream;

  ///Start the timer
  ///
  ///If the timer already has a value, it continues where it left off. Otherwise,
  ///it starts counting from 00:00
  void startTimer() {
    _subjectIsRunning.value = true;
    _sWatch.start();
    _startTimer();
  }

  ///Runs the Stopwatch every second
  void _startTimer() {
    Timer(Duration(seconds: 1), _keepRunning);
  }

  ///Keeps the Stopwatch running and updates the Stopwatch display BehaviourSubject
  void _keepRunning() {
    //Stop the timer from overflowing, max value should be 99:99
    if (_sWatch.elapsed.inMinutes >= 100) {
      pauseTimer();
      return;
    }
    if (_sWatch.isRunning) {
      _startTimer();
    }
    _subjectDisplay.sink.add(_formatStopWatch(_sWatch));
  }

  ///Formats the StopWatch elapsed time into the 00:00 format
  String _formatStopWatch(Stopwatch _swatch) {
    final String _inMinutes =
        (_swatch.elapsed.inMinutes % 60).toString().padLeft(2, '0');
    final String _inSeconds =
        (_swatch.elapsed.inSeconds % 60).toString().padLeft(2, '0');

    return "$_inMinutes:$_inSeconds";
  }

  ///Pause the timer and stop on the current display from being changed
  void pauseTimer() {
    _subjectIsRunning.value = false;
    _sWatch.stop();
  }

  ///Reset the timer display and the Stopwatch object
  void resetTimer() {
    _subjectIsRunning.value = false;
    _subjectDisplay.sink.add('00:00');
    _sWatch.reset();
    _sWatch.stop();
  }

  ///Resumed the timer and continue updating the Stopwach display
  void resumeTimer() {
    _subjectIsRunning.value = true;
    _sWatch.start();
    _startTimer();
  }

  ///Dispose of the BehaviorSubjects
  void dispose() {
    _subjectDisplay.close();
    _subjectIsRunning.close();
  }
}

This class and the app in general could be a lot simpler, but I chose to keep the pause, resume and reset options. Only the best content here 😂

Finally, lets move onto the actual UI 🥳

So, we will need a StatefulWidget as we will be creating an instance of the TimerState class which will need disposing. All the items in my view that needed to change, such as the buttons and the display, were built using the StreamBuilder widget. This is an awesome little widget that listens to a Stream and then changes the output based on a builder function. Here is a example:

StreamBuilder(
    stream: _timerState.timerObservable,
    builder: (context, snapshot){
        if(snapshot.hasData){
            return Text(snapshot.data)
        }else{
            return Text('No data')
        }
    }
)

Flutter widget trees can get quite confusing to look at, so imma just dump it here for you to look at 🤦‍♂️

import 'package:flutter/material.dart';
import 'package:rxdart_timer/blocs/timer_state.dart';

class TimerView extends StatefulWidget {
  @override
  _TimerViewState createState() => _TimerViewState();
}

class _TimerViewState extends State<TimerView> {
  //Create a new instance of the timer for the stateful widget
  TimerState _timerState = TimerState();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          ///Stream builder to watch the timer observable stream from the BLOC
          StreamBuilder(
            stream: _timerState.timerObservable,
            builder: (context, snapshot) {
              ///Checking if the Stream has data
              ///
              ///For some reason, the seeded option isn't working in the BLOC
              if (snapshot.hasData) {
                return Text(snapshot.data);
              } else {
                return Text('00:00');
              }
            },
          ),
          const SizedBox(
            height: 40,
          ),

          ///The start button built using a StreamBuilder
          ///
          ///Checked if the timer is running and sets a seperate bool. The button then
          ///checks this bool and either allows the startTimer function to be ran or
          ///simple disabled the button
          StreamBuilder(
            stream: _timerState.isRunningObservable,
            builder: (context, snapshot) {
              bool _running = snapshot.hasData ? snapshot.data : false;
              return FlatButton(
                color: Colors.green,
                onPressed: _running ? null : _timerState.startTimer,
                child: Text('Start'),
              );
            },
          ),

          ///A row for containing the StreamBuilder for the Pause button and a
          ///regular Reset button
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              ///Using a StreamBuilder to build the Pause button
              ///
              ///I build another bool, similar to the strart button, to check whether the
              ///button should be enabled.
              StreamBuilder(
                stream: _timerState.isRunningObservable,
                builder: (context, snapshot) {
                  bool _running = snapshot.hasData ? snapshot.data : false;
                  return Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      FlatButton(
                        color: Colors.red[600],
                        onPressed: _running ? _timerState.pauseTimer : null,
                        child: Text('Pause'),
                      ),
                    ],
                  );
                },
              ),

              ///Seperating the Pause and Stop button by 30 pixels
              const SizedBox(
                width: 30,
              ),

              ///Reset button, always enabled
              FlatButton(
                color: Colors.yellow[700],
                onPressed: _timerState.resetTimer,
                child: Text('Reset'),
              ),
            ],
          )
        ],
      ),
    );
  }

  ///Disposes of the _timerState
  @override
  void dispose() {
    _timerState.dispose();
    super.dispose();
  }
}

There we go, I hope you can see all of the code goes together. Basically, adding on top of Darts built in Streams to make them easier to manage and subscribe to 🙂

On top of all the code in the post, here is a link to my GitHub repo with all the code. You might notice a few differences as well.

Comment if you have any issues 💕