Jump to content
Sign in to follow this  
storme

_SetBaseLocations - standardise your scripts

Recommended Posts

storme

If you start writing programs that have to live in the windows environment you need to know where to put your data/downloads/settings/etc. That is why I created this script. To give a standard for everything I could think of.

Features

- Only sets the global variables you have defined in calling script

- Standardises directories and registry locations

- Works with 32 and 64 bit systems

- Creates the directory locations (Optional)

;Locations for this program
Global $sRegBaseUser ; Base for user registry items
Global $sRegBaseMachine ; Base for computer registry items
Global $sStartMenuDir ; Start Menu location for this user
Global $sStartMenuCommonDir ; Start Menu location for ALLUSER
Global $sAppDataCommonDir ; Common Appdata Folder
Global $sAppData ; User Appdata Folder
Global $sCommonFilesDir ; Common Files folder
Global $sProgamFilesDir ; This scripts Program Folder
Global $sTempDir ; this scripts temp directory
Global $sINIFileUser ; INI File for this user (for this script)
Global $sINIFileSystem ; INI File for this system (for this script)

_SetBaseLocations("MyApp", "Storm-e")

ConsoleWrite("$sRegBaseUser =        " & $sRegBaseUser & @CR)
ConsoleWrite("$sRegBaseMachine =     " & $sRegBaseMachine & @CR)
ConsoleWrite("$sStartMenuCommonDir = " & $sStartMenuCommonDir & @CR)
ConsoleWrite("$sStartMenuDir =       " & $sStartMenuDir & @CR)
ConsoleWrite("$sAppDataCommonDir =   " & $sAppDataCommonDir & @CR)
ConsoleWrite("$sAppData =            " & $sAppData & @CR)
ConsoleWrite("$sCommonFilesDir =     " & $sCommonFilesDir & @CR)
ConsoleWrite("$sProgamFilesDir =     " & $sProgamFilesDir & @CR)
ConsoleWrite("$sTempDir =            " & $sTempDir & @CR)
ConsoleWrite("$sINIFileUser =        " & $sINIFileUser & @CR)
ConsoleWrite("$sINIFileSystem =      " & $sINIFileSystem & @CR)


; #FUNCTION# ====================================================================================================================
; Name...........: _SetBaseLocations
; Description ...: Sets pre-defined variables (see script for full list) to standard registry and folder loacations
; Syntax.........: _SetBaseLocations($sApplicaitonName[, $sCompanyUserName = ""] [, $bInitalise = False])
; Parameters ....: $sApplicaitonName - The name of your application
;                  $sCompanyUserName - your name or your companies name (NO CHECKING is done,  Call yourself microsoft and its your problem)
;                  $bInitalise - True = Create the directories for variables you've specified
; Return values .: Success - returns True
;                  Failure - at the moment it doesn't fail on anything
; Author ........: Storm-E aka John Morrison
; Modified.......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: Yes
; ===============================================================================================================================
Func _SetBaseLocations($sApplicaitonName, $sCompanyUserName = "", $bInitalise = False)

    #cs
        ; Variables that can be set by this function
        ; Copy the globals you need to your main script and call this function
        Global $sRegBaseUser ; Base for user registry items
        Global $sRegBaseMachine ; Base for computer registry items
        Global $sStartMenuDir ; Start Menu location for this user
        Global $sStartMenuCommonDir ; Start Menu location for ALLUSER
        Global $sAppDataCommonDir ; Common Appdata Folder
        Global $sAppData ; User Appdata Folder
        Global $sCommonFilesDir ; Common Files folder
        Global $sProgamFilesDir ; This scripts Program Folder
        Global $sTempDir ; this scripts temp directory
        Global $sINIFileUser ; INI File for this user (for this script)
        Global $sINIFileSystem ; INI File for this system (for this script)
    #ce

    Local $sArch = "64"
    If @OSArch = "X86" Then
        $sArch = ""
    EndIf

    If $sCompanyUserName <> "" Then
        ; Add backslash to end of company
        $sCompanyUserName = $sCompanyUserName & "\"
    EndIf

    ;Assign won't set variables unless they exist so set teh variables you want
    Assign("sRegBaseUser", "HKCU" & $sArch & "\Software\" & $sCompanyUserName & $sApplicaitonName, 4)
    Assign("sRegBaseMachine", "HKLM" & $sArch & "\Software\" & $sCompanyUserName & $sApplicaitonName, 4)
    Assign("sStartMenuCommonDir", @StartMenuCommonDir & "\" & $sCompanyUserName & $sApplicaitonName & "\", 4)
    Assign("sStartMenuDir", @StartMenuDir & "\" & $sCompanyUserName & $sApplicaitonName & "\", 4)
    Assign("sAppDataCommonDir", @AppDataCommonDir & "\" & $sCompanyUserName & $sApplicaitonName & "\", 4) ; Must be set for sINIFileSystem
    Assign("sAppData", @AppDataDir & "\" & $sCompanyUserName & $sApplicaitonName & "\", 4) ; Must be set for sINIFileUser
    Assign("sCommonFilesDir", @CommonFilesDir & "\" & $sCompanyUserName & $sApplicaitonName & "\", 4)
    Assign("sProgamFilesDir", @ProgramFilesDir & "\" & $sCompanyUserName & $sApplicaitonName & "\", 4)
    Assign("sTempDir", @TempDir & "\" & $sCompanyUserName & $sApplicaitonName & "\", 4)
    Assign("sINIFileUser", $sAppData & $sCompanyUserName & $sApplicaitonName & ".ini", 4)
    Assign("sINIFileSystem", $sAppDataCommonDir & $sCompanyUserName & $sApplicaitonName & ".ini", 4)

    If Not ($bInitalise) Then
        ;Initialise directories
        If IsDeclared($sStartMenuCommonDir) Then DirCreate($sStartMenuCommonDir)
        If IsDeclared($sStartMenuDir) Then DirCreate($sStartMenuDir)
        If IsDeclared($sAppDataCommonDir) Then DirCreate($sAppDataCommonDir)
        If IsDeclared($sAppData) Then DirCreate($sAppData)
        If IsDeclared($sCommonFilesDir) Then DirCreate($sCommonFilesDir)
        If IsDeclared($sProgamFilesDir) Then DirCreate($sProgamFilesDir)
        If IsDeclared($sTempDir) Then DirCreate($sTempDir)
    EndIf

EndFunc   ;==>_SetBaseLocations

The script is not really complete but I have a few questions that keep running around and you might be able to help me with an answer or 2. :graduated:

All of these variables are specific to the script it's run from (or whatever you set in $sApplicaitonName). Should I also have "Company" variables that specify the Company level for things like common INI/log/etc files?

If there is anything you think should be changed please let me know and I'll consider it. ;)

Hope this is of sum use and I'm always open to suggestions so fire away. :)

John Morrison

Edited by storme

Share this post


Link to post
Share on other sites
storme

Just thought of something I wanted to add but didn't know how.

When the ($sApplicaitonName, $sCompanyUserName) are specified I'd like to remove any special characters that can't be used in the registry or as folder names. Maybe remove spaces to and capitolise the first character of the next word.

EG

Fred's fishing and bait

would become

FredsFishingAndBait

Can any regex expert give me a wizbang line of magic to do that?

Thanks if you can! If not I'll resort to a for loop and character by character cleanup. :graduated:

Share this post


Link to post
Share on other sites
guinness

Just one question first why are you using Assign()? Surely $iVariable = "Data" is suffice?

Edited by guinness

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Share this post


Link to post
Share on other sites
Melba23

storme,

Can any regex expert give me a wizbang line of magic to do that?

Not an expert and not at all sure this is "wizbang", but it ought to do the trick: :graduated:

$sText = StringRegExpReplace($sText, "[^[:alnum:]]", "")

It removes everything except the alphanumeric characters.

M23


Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind._______Open Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Share this post


Link to post
Share on other sites
storme

Just one question first why are you using Assign()? Surely $iVariable = &quot;Data&quot; is suffice?

Because of the ,4 on the end. :graduated:

I want the user to be able to add only the varaibles they want.

I.E

The idea is instead of adding a block of code like this to your main script with a lot of unused varaibles.

Global $sRegBaseUser ; Base for user registry items
Global $sRegBaseMachine ; Base for computer registry items
Global $sStartMenuDir ; Start Menu location for this user
Global $sStartMenuCommonDir ; Start Menu location for ALLUSER
Global $sAppDataCommonDir ; Common Appdata Folder
Global $sAppData ; User Appdata Folder
Global $sCommonFilesDir ; Common Files folder
Global $sProgamFilesDir ; This scripts Program Folder
Global $sTempDir ; this scripts temp directory
Global $sINIFileUser ; INI File for this user (for this script)
Global $sINIFileSystem ; INI File for this system (for this script)

_SetBaseLocations("MyApp", "Storm-e")

they can simply add what they need

Global $sINIFileUser ; INI File for this user (for this script)

_SetBaseLocations("MyApp", "Storm-e")

This is for a program that only needs a user ini file.

It makes the main code cleaner and easier to understand.

I started by using globals in the UDF, which is a NO-NO. Then I moved them out to the main code as you see in my script. Then I caught on the idea of only declaring what was needed. I was going to use an IF with isdeclared like I have for the initialisation section but stumbled on the assign and the option 4. ;)

Hope that clears things up.

John Morrison

Share this post


Link to post
Share on other sites
storme

storme,

Not an expert and not at all sure this is &quot;wizbang&quot;, but it ought to do the trick: ;)

$sText = StringRegExpReplace($sText, &quot;[^[:alnum:]]&quot;, &quot;&quot;)

It removes everything except the alphanumeric characters.

M23

This will do most of the job. The other part is a wish and I'm not sure regex can do it.

I.E Capitalise the first letter after any space.

EG "my great script" -> "myGreatScript"

Thanks for the help I'll add that to the script. :graduated:

John Morrison

Share this post


Link to post
Share on other sites
storme

I've had second thoughts about removeing the spaces adn ALL non alpha/nuneric characters from the company and script fields. I will restrict what can be entered so much that legal entires will be eliminated. ;) Spaces are fine in both teh registry and folder names so I shouldn't remove them.

So anyone know what the restricted characters are for Registry folder.keys?

Are they the same as folder names IE \/:*?"<>|

If so I'll just remove those characters. :graduated:

Thanks!

Share this post


Link to post
Share on other sites
guinness

which is a NO-NO.

I've been taught that using Global variables can sometimes be smarter than using variables in Local scope, but now I'm going off-topic. Thanks for answering my question, I was just curious :graduated:

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Share this post


Link to post
Share on other sites
Melba23

storme,

I'm not sure regex can do it. I.E Capitalise the first letter after any space. EG "my great script" -> "myGreatScript"

But AutoIt can: :graduated:

#include <String.au3>

$sText = "my great script"

$sNewtext = StringRegExpReplace(_StringProper($sText), "[^[:alnum:]]", "")

MsgBox(0, "Result", $sNewtext)

M23


Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind._______Open Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Share this post


Link to post
Share on other sites
storme

I've been taught that using Global variables can sometimes be smarter than using variables in Local scope, but now I'm going off-topic. Thanks for answering my question, I was just curious :graduated:

I should have explained in more detail...

Creating Global variables in a func can cause confustion for anyone trying to read the script as the globals just "appear"

The "right" way is to declare your globals at the top of the script so it's clear which they are.

Any "local" varialbes in functions should be declaired local.

Anyway that is what I was taught. ;)

Thanks for asking

John Morrison

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×