Tuesday, November 6, 2018

Google Authenticator siteweb visual studio


Google 2FA with authenticator

Package
https://www.nuget.org/packages/GoogleAuthenticator/

Nuget console in visual studio:
Install-Package GoogleAuthenticator -Version 1.2.1

Source of Google.Authenticator.dll:
https://github.com/brandonpotter/GoogleAuthenticator

------------------ code visual studio.net c#----------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Security.Cryptography;
using System.Text;
using System.Web.Profile;
using System.Web.Security;
using Google.Authenticator;

public partial class _Default : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ////////////////////////////////////////////////
        // if user do not have a code, we generate one
        ////////////////////////////////////////////////
     


        ////////////////////////////////////////
        // get qrcode
        ////////////////////////////////////////
        TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();

        //the width and height of the Qr Code in pixels
        var setupInfo = tfa.GenerateSetupCode("Name of the app", "More info ABout the App", "SuperSecretKeyGoesHere22", 300, 300);

        // assigning the Qr code information + URL to string
        string qrCodeImageUrl = setupInfo.QrCodeSetupImageUrl;
        // show the Manual Entry Key for the users that don't have app or phone
        string manualEntrySetupCode = setupInfo.ManualEntryKey;

        // showing the qr code on the page "linking the string to image element"
        Image1.ImageUrl = qrCodeImageUrl;

        // showing the manual Entry setup code for the users
        Label1.Text = manualEntrySetupCode;
    }

    protected void Button1_Click(object sender, EventArgs e)
    {

        // login
        string login01 = txtlogin01.Text.Trim();
        string password01 = txtpassword01.Text.Trim();
        string passcode01 = txtpasscode01.Text.Trim();

        // check sql if the user have a passcodekey01



        ////////////////////////////////////////
        // validate google code
        ////////////////////////////////////////
     
        TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();
        bool isCorrectPIN = tfa.ValidateTwoFactorPIN("SuperSecretKeyGoesHere22", passcode01);
        if (isCorrectPIN == true)
        {
            Label2.Text = "i am cool";
        }
        else
        {
            Label2.Text = "i am Fool";
        }

    }

    protected void TextBox1_TextChanged(object sender, EventArgs e)
    {

    }
}

Friday, October 26, 2018

Object Programming Level 1

Object Programming Level 1

I never saw the use of object programming until we could make an object with a sql query.
Of course it is because i never had a program that needed it.

Doing a class with a get and set (wich is simply a variable with extra code) is superfluous, because you can do that with a variable in procedural mode. Without having to include your sub class in your main class and typing 10 lines of extra code just to have an object as a variable.

Most poeple create objects instead of variables and think it's cool. But what about the extra time you charge your client just so your variable are now objects, but the need for it was not there?

Programmer analyst must be analyse first. Do you need an object for a simple variable never used again? That do not need parent property? That does not have childrens?

So a procedural code with a variable is: (csharp)

--- code start csharp visual studio console app -------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace application_obejct_test
{
    class Program
    {
        static void Main(string[] args)
        {
            string variable01 = "hello";
            Console.WriteLine(variable01);

            variable01 = "not hello";
            Console.WriteLine(variable01);

            Thread.Sleep(3000);
        }
    }
}

--- end code ---

Now let's the same with an object

--- code start csharp visual studio console app -------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace application_obejct_test
{
    class Program
    {
       

        static void Main(string[] args)
        {
            string01 variable01 = new string01();
            variable01.text01 = "hello";
            Console.WriteLine(variable01.text01);

            variable01.text01 = "not hello";
            Console.WriteLine(variable01.text01);

            Thread.Sleep(3000);
        }
    }

    public class string01
    {
        // here i will not give the same name to the field and the property with a case difference (uppercase the first letter)
        // it's just a pain to always use the SHIFT key to type uppercases letters

        private string text02; // field, just a variable used to get and set value
        public string text01   // property, the thingy after the . in the name of your new object
        {
            get
            {
                return text02;
            }
            set
            {
                text02 = value; // value is an object property, it's always there
            }
        }
    }
}
------- code end --------

Now, as you can see, for a simple string, making an object to manage it, is really of no use
Poeple doing that with a string, have too much time to loose

BUT, object can be much more
You can validate the length before setting the value of the string object

That changes things, because your object now free you of validating every input from your client
But it would still cut the value without warning...
To add a warning you have to manage error that can happen in your object

--- code start csharp visual studio console app -------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace application_obejct_test
{
    class Program
    {
       

        static void Main(string[] args)
        {
            string01 variable01 = new string01();
            variable01.text01 = "hello";
            Console.WriteLine(variable01.text01);

            variable01.text01 = "not hello";
            if (variable01.errorcode01 == 99)
            {
                Console.WriteLine("ERROR " + variable01.errorcode01);
                Console.WriteLine("ERROR " + variable01.errormessage01);
                Console.WriteLine(variable01.text01);
            }
            else
            {
                Console.WriteLine(variable01.text01);
            }

            Thread.Sleep(3000);
        }
    }

    public class string01
    {
        // here i will not give the same name to the field and the property with a case difference (uppercase the first letter)
        // it's just a pain to always use the SHIFT key to type uppercases letters

        private int err01;
        private string err02;

        private string text02; // field, just a variable used to get and set value
        public string text01   // property, the thingy after the . in the name of your new object
        {
            get
            {
                return text02;
            }
            set
            {
                // validate the value before assigning it to the object
                int maxvalue01 = 7;
                if (value.Length > maxvalue01)
                {
                    text02 = value.Substring(0, maxvalue01);
                    err01 = 99;
                    err02 = "string was cut";
                }
                else
                {
                    text02 = value; // value is an object property, it's always there
                }
            }
        }

        public int errorcode01
        {
            get { return err01; }
        }

        public string errormessage01
        {
            get { return err02; }
        }

    }
}
--- code end ---

Until now, the difference is we can get and set the object variable WITH a validation on the set

We could do this with a struct passed to a function byref, but we would have to include the action to do on each variable in the struct.

So the difference with an object variable, is the actions are defined in it, and the validation too.

But can we access the object variables dynamically? (by name)
Yes we can:

--- code start ---
            // set with dynamic name
            typeof(string01).GetProperty("text01").SetValue(variable01, "hello");
            // get with dynamic name
            object value01 = typeof(string01).GetProperty("text01").GetValue(variable01);

            Console.WriteLine(value01);

--- code end ---

Of course, without hardcoding your object, you loose the warning the compiler will give you if you try to give a bad type of value to your object (string to an int etc.), but that is for amateur programmers. Real pro would trap that inside the object, and validate any get or set with an error returned by the object.

That's it for level 1 object programming.



Saturday, May 5, 2018

Eject usb drive but not all of them

Eject usb drive but not all of them

Using the windows 10 icon, "eject the media", is slow because windows start all my sleeping usb drives before i can click "eject safely"

I wanted to eject some drive without waiting for the windows to open
I did not want to eject my sleeping usb drives that i use for storage

So, I designed this little powershell script to do so

##### powershell script #####

### requirements
# because this script is not signed
# (this will allow unsigned local powershell scripts to run)
#   windows 7
#     Set-ExecutionPolicy RemoteSigned #################################
#   windows 10
#     Set-ExecutionPolicy -scope CurrentUser RemoteSigned ##############
#   run it in powershell ISE interface runned as admin


$donotejectserials = @(`
"FAFFFFF0FDF2F7F1BFC15635",`
"2GEWLRPL",`
"14510E6CDA88")

# get serial i do not want to eject - list all usb drives
#get-Disk | Where {($_.BusType -eq "USB")}

$allusbdisk = get-Disk | Where {($_.BusType -eq "USB")}

foreach ($usbdisk in $allusbdisk)
    {
    $founddonoteject = 0
    foreach ($donotejectserial in $donotejectserials)
        {
        if ($usbdisk.serialnumber -like "*$donotejectserial*")
            {
            $founddonoteject = 1
            }
        #write-host "Serials: " $usbdisk.serialnumber " ----- " $donotejectserial " ----- " $founddonoteject
        }
    if ($founddonoteject -eq 0)
        {
       
        $letter = ($usbdisk | Get-Partition ).DriveLetter
        write-host "Ejecting: " $letter " ----- " $usbdisk.friendlyname " ----- " $usbdisk.serialnumber
        (New-Object -comObject Shell.Application).NameSpace(17).ParseName("$($letter):").InvokeVerb('Eject')
        }
    else
        {
        #write-host "NOT Ejecting: " $usbdisk.friendlyname
        }
    }

Tuesday, April 24, 2018

powershell windows eventlog filter

Here is a little powershell line to filter events in powershell:

SYSTEM is the group the event is in
PROVIDERNAME is the category / type
MESSAGE is the content / description of the event
(change the keywords as needed)

# find reboots
Get-WinEvent -LogName System -MaxEvents 10000 | Where-Object {$_.providername -like "*kernel*" -and $_.Message -like "*démarré*"} | format-table Timecreated, Leveldisplayname, message -auto -wrap

# isolate a day to find the cause of the reboot
Get-WinEvent -LogName System -MaxEvents 10000 | Where-Object {$_.timecreated -le "2018-04-19" -and $_.timecreated -gt "2018-04-18 14:00:00"} | format-table Timecreated, Leveldisplayname, message -auto -wrap

remote version:
$machine01 = ""
$login01 = "compagny\user"
$password01 = "usuallydonotputpasswordofadmininascript"

$Credential= New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $login01,($password01 | ConvertTo-SecureString -AsPlainText -Force)

#Get-WinEvent -Credential $Credential -ComputerName $Machine01 -LogName System -MaxEvents 5000 | Where-Object {$_.providername -like "*kernel*" -and $_.Message -like "*démarré*"} | format-table Timecreated, Leveldisplayname, message -auto -wrap

# isolate a day
Get-WinEvent -LogName System -MaxEvents 1500 -Credential $Credential -ComputerName $Machine01 | `
Where-Object {$_.timecreated -le "2018-05-01" -and $_.timecreated -gt "2018-04-14 14:00:00" -and $_.message -like "*vid*"} | `
format-table Timecreated, Leveldisplayname, message -auto -wrap

Monday, April 9, 2018

Access extract all vba modules for versionning support

Hello,

I wanted to extract all VBA modules from Microsoft ACCESS to be able to use GIT for versionning my VBA code

Here is a VBA macro to extract all module in a subfolder called:
[current directory of access file]\VBAProjectFiles

In microsoft access4
ALT F11
new module
copy paste this code in the module
run it

every file will be overwritten each time, but eh, GIT will see what line were added and deleted in each module

Required:
Access to VBA models in options, confidentiality center


-------------------- VBA module99 ---------------------------------

Option Compare Database

'====================================================
' exportation des modules VBA pour push dans GIT
'====================================================
Public Sub exportVBAlinebyline()

    path00 = CurrentDb.Name
    pathend00 = InStrRev(path00, "\")
    path01 = Left(path00, Len(path00) - (Len(path00) - pathend00))
    filename00 = Right(path00, (Len(path00) - pathend00))
    filename01 = Replace(filename00, ".", "")
   
    ' The reference for the FileSystemObject Object is Windows Script Host Object Model
    ' but it not necessary to add the reference for this procedure.
   
    Dim objfso As Object
    Dim file01 As Object
    Dim strMod As String
    Dim mdl As Object
    Dim i As Integer
   
    Set objfso = CreateObject("Scripting.FileSystemObject")
   
    ' Set up the file.
    ' SpFolder is a small function, but it would be better to fill in a
    ' path name instead of SpFolder(Desktop), eg "c:\users\somename\desktop"
   
    path02 = path01 & "VBAProjectFiles"
    If objfso.FolderExists(path02) = False Then
        err01 = 0: err02 = "": On Error Resume Next
        objfso.createfolder path02
        err01 = Err.number: err02 = Err.Description: On Error GoTo 0
    Else
        '=== folder already exist
    End If
   
    If err01 = 0 Then
       
        '=== list of all modules
        Set file01 = objfso.CreateTextFile(path01 & "\" & filename01 & "_liste.txt")
       
       
        '=== For each component in the project ...
        For Each mdl In VBE.ActiveVBProject.VBComponents
            '=== list of all modules
            file01.writeline mdl.Name
           
            Set file02 = objfso.CreateTextFile(path02 & "\" & mdl.Name & ".txt")
            '=== using the count of lines ...
            i = VBE.ActiveVBProject.VBComponents(mdl.Name).CodeModule.CountOfLines
            '=== put the code in a string ...
            If i > 0 Then
               strMod = VBE.ActiveVBProject.VBComponents(mdl.Name).CodeModule.Lines(1, i)
            End If
            '=== and then write it to a file, first marking the start with
            '=== some equal signs and the component name.
            file02.writeline strMod
            file02.Close
        Next
       
        '=== Close eveything
        file01.Close
        Set objfso = Nothing
       
    Else
        MsgBox ("ERROR cannot create folder: " & vbCrLf & path02)
    End If
   
End Sub

Wednesday, March 14, 2018

Windows 10 STARTMENU TILE cleanup français

Enfin!

Un vrai nettoyage du startmenu windows 10 français

Powershell script (cleanupstartmenuwin10.ps1)


List all action possibles for an app:
$items01 = (New-Object -Com Shell.Application).NameSpace('shell:::{4234d49b-0245-4df3-b780-3893943456e1}').Items()
foreach($item01 in $items01)
{
    if ($item01.name -eq "excel")
    {
        write-host $item01.name
        $verbs01 = $item01.verbs()
        foreach($verb01 in $verbs01)
        {
            write-host $verb01.Name
        }
           
    }
}




############### Functions

function Pin-App
{ param(
 [string]$appname,
 [switch]$unpin
 )
 try{
     if ($unpin.IsPresent)
        {
        $action01 = "Désépingler|Désépingler de la page d'accueil"
        #((New-Object -Com Shell.Application).NameSpace('shell:::{4234d49b-0245-4df3-b780-3893943456e1}').Items() | ?{$_.Name -eq $appname}).Verbs() | ?{$_.Name.replace('&','') -match 'From "Start" UnPin|Unpin from Start'} | %{$_.DoIt()}
        ((New-Object -Com Shell.Application).NameSpace('shell:::{4234d49b-0245-4df3-b780-3893943456e1}').Items() | ?{$_.Name -eq $appname}).Verbs() | ?{$_.Name.replace('&','') -match 'From "Start" ' + $action01} | %{$_.DoIt()}
        #$action01 = "Détacher|Détacher du menu démarrer"
        #((New-Object -Com Shell.Application).NameSpace('shell:::{4234d49b-0245-4df3-b780-3893943456e1}').Items() | ?{$_.Name -eq $appname}).Verbs() | ?{$_.Name.replace('&','') -match 'From "Start" ' + $action01} | %{$_.DoIt()}
        #((New-Object -Com Shell.Application).NameSpace('shell:::{4234d49b-0245-4df3-b780-3893943456e1}').Items() | ?{$_.Name -eq $appname}).Verbs()
       
        return "App '$appname' unpinned from Start"
        }
        else
        {
        $action02 = "Épingler|Épingler à l’écran de démarrage"
        #((New-Object -Com Shell.Application).NameSpace('shell:::{4234d49b-0245-4df3-b780-3893943456e1}').Items() | ?{$_.Name -eq $appname}).Verbs()
        ((New-Object -Com Shell.Application).NameSpace('shell:::{4234d49b-0245-4df3-b780-3893943456e1}').Items() | ?{$_.Name -eq $appname}).Verbs() | ?{$_.Name.replace('&','') -match 'To "Start" ' + $action02} | %{$_.DoIt()
        }
        return "App '$appname' pinned to Start"
        }
    }
    catch
    {
    }
 }

 ############### Unpin All Apps
# shortcuts
 Export-StartLayout –path C:\startscreenlayout.xml
 [xml]$layoutfile = Get-Content C:\startscreenlayout.xml

 foreach ( $item in $layoutfile.LayoutModificationTemplate.DefaultLayoutOverride.StartLayoutCollection.StartLayout.Group.DesktopApplicationTile.DesktopApplicationLinkPath)
 {
        $outputFile = Split-Path $item -leaf
        $name = $outputFile.split('.') | Select-Object -first 1
        Pin-App "$name" -unpin
        #$name
        #((New-Object -Com Shell.Application).NameSpace('shell:::{4234d49b-0245-4df3-b780-3893943456e1}').Items() | ?{$_.Name -eq $name}).Verbs()
 }
# apps
 foreach ( $item in $layoutfile.LayoutModificationTemplate.DefaultLayoutOverride.StartLayoutCollection.StartLayout.Group.Tile.AppUserModelID)
 {
        $outputFile = Split-Path $item -leaf
        $name = $outputFile | Select-Object -first 1
        #Pin-App "$name" -unpin
        $name
        $action01 = "Désépingler|Désépingler de la page d'accueil"
        #((New-Object -Com Shell.Application).NameSpace('shell:::{4234d49b-0245-4df3-b780-3893943456e1}').Items() | ?{$_.Path -eq $name}).Verbs() | ?{$_.Name.replace('&','') -match 'From "Start" ' + $action01}
       
       
        ((New-Object -Com Shell.Application).NameSpace('shell:::{4234d49b-0245-4df3-b780-3893943456e1}').Items() | ?{$_.Path -eq $name}).Verbs() | ?{$_.Name.replace('&','') -match 'From "Start" ' + $action01} | %{$_.DoIt()}
 }
# PUB
 foreach ( $item in $layoutfile.LayoutModificationTemplate.DefaultLayoutOverride.StartLayoutCollection.StartLayout.Group.SecondaryTile.AppUserModelID)
 {
        $outputFile = Split-Path $item -leaf
        $name = $outputFile | Select-Object -first 1
        #Pin-App "$name" -unpin
        $name
        $action01 = "Désépingler|Désépingler de la page d'accueil"
        #((New-Object -Com Shell.Application).NameSpace('shell:::{4234d49b-0245-4df3-b780-3893943456e1}').Items() | ?{$_.Path -eq $name}).Verbs()
       
        ((New-Object -Com Shell.Application).NameSpace('shell:::{4234d49b-0245-4df3-b780-3893943456e1}').Items() | ?{$_.Path -eq $name}).Verbs() | ?{$_.Name.replace('&','') -match 'From "Start" ' + $action01} | %{$_.DoIt()}
 }

 ############### PIN YOUR FAVORITE APPS
 Pin-App "Netflix" -pin
 #Pin-App "Photos" -pin
 #Pin-App "Calculatrice" -pin
 #Pin-App "Snipping Tool" -pin
 #Pin-App "Notepad" -pin
 Pin-App "Explorateur de fichiers" -pin
 #Pin-App "Word 2013" -pin
 #Pin-App "Excel 2013" -pin
 #Pin-App "Outlook 2013" -pin
 #Pin-App "Powerpoint 2013" -pin
 #Pin-App "Word 2016" -pin
 #Pin-App "Excel 2016" -pin
 #Pin-App "Outlook 2016" -pin
 #Pin-App "Powerpoint 2016" -pin


### remove menu item, app, lock future installation
write-host "=== will remove menu icon, delete app, prevent futur install"

$listonly01 = 0

[string[]]$items02="http://java.com/help"
$items02+="MicrosoftSolitaireCollection_8wekyb3d8bbwe"
$items02+="MSPaint_8wekyb3d8bbwe"
$items02+="Microsoft3DViewer_8wekyb3d8bbwe"
$items02+="XboxApp_8wekyb3d8bbwe"
$items02+="ZuneMusic_8wekyb3d8bbwe"
$items02+="ZuneVideo_8wekyb3d8bbwe"
$items02+="MicrosoftOfficeHub_8wekyb3d8bbwe"
$items02+="http://java.com/"
$items02+="asphalt*8*airborne"
$items02+="marchofempire"
$items02+="bubblewitch3saga"
$items02+="candycrushsodasaga"
$items02+="asphalt*8*airborne"
$items02+="minecraft"
$items02+="xbox"

$action01 = "*Détacher de l*écran d*accueil*"

foreach ($item02 in $items02)
    {
    if ($listonly01 -eq 1)
        {
        ((New-Object -Com Shell.Application).NameSpace('shell:::{4234d49b-0245-4df3-b780-3893943456e1}').Items() | select name, path | where-object {$_.path –like "*$item02*" -or $_.name –like "*$item02*"})
        }
        else
        {
        #write-host $action01 ":" $item02
# not working see up for the real one working     
#((New-Object -Com Shell.Application).NameSpace('shell:::{4234d49b-0245-4df3-b780-3893943456e1}').Items() | where-object {$_.path –like "*$item02*"}).Verbs() | ?{$_.Name.replace('&','') -like "$action01"} | %{$_.doit()}
     
        write-host "removing: " $item02
        (Get-AppxPackage -allusers | where-object {$_.name –like "*$item02*" -or $_.PackageFamilyName –like "*$item02*"}) | Remove-AppxPackage
     
        write-host "removing online install: " $item02
        Get-appxprovisionedpackage –online | where-object {$_.name –like "*$item02*" -or $_.PackageFamilyName –like "*$item02*"} | remove-appxprovisionedpackage –online
        }
    }