30 December 2022

MS Access - Specify Max Length for TextBox or ComboBox on a Form

You should limit both events:
  • KeyPress() for user typing
  • Change() for copy/paste
Public Sub LimitKeyPress(ByRef pControl As Control, pMaxLen As Long, ByRef KeyAscii As Integer)

    On Error GoTo GesErr

'   -------------------------------------------------------------------------
'   -- GESTIONE MAX LENGTH IN UNA TEXTBOX/COMBO UNBOUND 1/2: KeyPress
'   -------------------------------------------------------------------------
'   Via:          http://allenbrowne.com/ser-34.html
'
'   Utilizzo:     Nella KeyPress():
'                   Private Sub Testo0_KeyPress(KeyAscii As Integer)
'                       LimitKeyPress Me.ActiveControl, cMaxLen, KeyAscii
'                   End Sub
'
'   NB:           Ricordarsi di lanciare anche la LimitChange()
'   -------------------------------------------------------------------------
    
    With pControl
        If Len(pControl.Text) - .SelLength >= pMaxLen Then
            If KeyAscii <> vbKeyBack Then
                KeyAscii = 0
            End If
        End If
    End With
    
    Exit Sub
    
GesErr:
    SysGesErr , StringFormat("LimitKeyPress({0}, {1}, {2})", pControl.name, pMaxLen, KeyAscii)
    
End Sub

Public Sub LimitChange(ByRef pControl As Control, pMaxLen As Long)

    On Error GoTo GesErr

'   -------------------------------------------------------------------------
'   -- GESTIONE MAX LENGTH IN UNA TEXTBOX/COMBO UNBOUND 2/2: Copy/Paste
'   -------------------------------------------------------------------------
'   Via:          http://allenbrowne.com/ser-34.html
'
'   Utilizzo:     Nella Change():
'                   Private Sub Testo0_Change()
'                       LimitChange Me.ActiveControl, cMaxLen
'                   End Sub
'
'   NB:           Ricordarsi di lanciare anche la LimitKeyPress()
'   -------------------------------------------------------------------------

    With pControl
        If Len(.Text) > pMaxLen Then
            .Text = Left(.Text, pMaxLen)
            .SelStart = pMaxLen
        End If
    End With
    
    Exit Sub

GesErr:
    SysGesErr , StringFormat("LimitChange({0}, {1})", pControl.name, pMaxLen)
    
End Sub


Using in the Form:
Private Sub Testo0_KeyPress(KeyAscii As Integer)
    LimitKeyPress Me.ActiveControl, cMaxLen, KeyAscii
End Sub

Private Sub Testo0_Change()
    LimitChange Me.ActiveControl, cMaxLen
End Sub
Via: http://allenbrowne.com/ser-34.html

11 November 2022

MS Access VBA Bug - Numlock key keeps turning off with SendKeys

The SendKeys() function that is built-in VBA has really a side effect that causes NumLock to be deactivated.
But you can use a workaround and call another implementation of the same function that is a part of WScript component (a part of Windows operating system).

If you create a new Sub with the same name, it shadows the "system" SendKeys:
Public Sub SendKeys(pString, Optional pWait As Boolean = True)
   
    '-- There is a well known bug in all versions of Access involving SendKeys switching off the Numlock key.
    Dim WshShell

    Set WshShell = CreateObject("WScript.Shell")
    WshShell.SendKeys pString, pWait
    Set WshShell = Nothing

End Sub
https://stackoverflow.com/questions/25977933/sendkeys-is-messing-with-my-numlock-key-via-vba-code-in-access-form

21 October 2022

SQL Server: how to disable a Linked Server

DECLARE @Linked_Server_Name sysname = 'SRVZUC02\SQLEXPRESS'

-- check the existent linked servers
SELECT s.is_data_access_enabled, *
FROM SYS.SERVERS s
WHERE s.NAME = @Linked_Server_Name


-- Disable data access
EXEC sp_serveroption 
      @server   = @Linked_Server_Name
	, @optname  = 'data access'
	, @optvalue = 'FALSE'


-- check the existent linked servers
SELECT s.is_data_access_enabled, *
FROM SYS.SERVERS s
WHERE NAME = @Linked_Server_Name

Found here.

About procedure [sp_serveroption] on SQL Docs.

HOWTO configure Windows Firewall for SQL Server

New-NetFirewallRule -DisplayName "SQLServer default instance" -Direction Inbound -LocalPort 1433 -Protocol TCP -Action Allow

New-NetFirewallRule -DisplayName "SQLServer Browser service" -Direction Inbound -LocalPort 1434 -Protocol UDP -Action Allow

NOTE: Remeber to activate the SQLServer Browser service.

03 October 2022

Adobe Acrobat: Copiare i form fields da un PDF ad un altro

Non bisogna copiare i campi ma, partendo al vecchio file, sostituire le pagine "sotto" ai campi modulo:
Are you familiar with using Replace Pages as a tool for keeping your form designs, while replacing the page backgrounds? It sounds exactly what would save you a lot of time.
Found here.

28 September 2022

SQL: How to determine free space and file size for SQL Server databases

DECLARE @FileSize AS TABLE (
	dbName NVARCHAR(128)
	, FileName NVARCHAR(128)
	, type_desc NVARCHAR(128)
	, CurrentSizeMB DECIMAL(10, 2)
	, FreeSpaceMB DECIMAL(10, 2)
	);

INSERT INTO @FileSize (
	dbName
	, FileName
	, type_desc
	, CurrentSizeMB
	, FreeSpaceMB
	)
EXEC sp_msforeachdb 
	'use [?]; 
 SELECT DB_NAME() AS DbName, 
        name AS FileName, 
        type_desc,
        size/128.0                                                           AS CurrentSizeMB,  
        size/128.0 - CAST(FILEPROPERTY(name, ''SpaceUsed'') AS INT)/128.0    AS FreeSpaceMB
FROM sys.database_files
WHERE type IN (0,1);'
	;

SELECT dbName
	, FileName
	, type_desc
	, FORMAT(X.CurrentSizeMB, 'N0') AS CurrentSizeMB
	, FORMAT(X.FreeSpaceMB, 'N0') AS FreeSpaceMB
FROM @FileSize X
WHERE dbName NOT IN ('distribution', 'master', 'model', 'msdb')
	AND FreeSpaceMB > 1000
ORDER BY FreeSpaceMB DESC
Found here.

24 June 2022

Enable / Disable SMB1 on Windows 10 with Powershell

Powershell Method

Here are the steps to detect, disable and enable SMBv1 client and server by using PowerShell commands.

NOTE: The computer will restart after you run the PowerShell commands to disable or enable SMBv1.
# DETECT
Get-WindowsOptionalFeature -Online -FeatureName SMB1Protocol


# DISABLE
Disable-WindowsOptionalFeature -Online -FeatureName SMB1Protocol


# ENABLE
Enable-WindowsOptionalFeature -Online -FeatureName SMB1Protocol
Found here.

07 June 2022

SQL Server Database Growth and Autogrowth Settings

Identifying Databases that are using the Default Auto-growth Settings:
-- Drop temporary table if it exists
IF OBJECT_ID('tempdb..#info') IS NOT NULL
       DROP TABLE #info;
 
-- Create table to house database file information
CREATE TABLE #info (
     databasename VARCHAR(128)
     ,name VARCHAR(128)
    ,fileid INT
    ,filename VARCHAR(1000)
    ,filegroup VARCHAR(128)
    ,size VARCHAR(25)
    ,maxsize VARCHAR(25)
    ,growth VARCHAR(25)
    ,usage VARCHAR(25));
    
-- Get database file information for each database   
SET NOCOUNT ON; 
INSERT INTO #info
EXEC sp_MSforeachdb 'use ? 
select ''?'',name,  fileid, filename,
filegroup = filegroup_name(groupid),
''size'' = convert(nvarchar(15), convert (bigint, size) * 8) + N'' KB'',
''maxsize'' = (case maxsize when -1 then N''Unlimited''
else
convert(nvarchar(15), convert (bigint, maxsize) * 8) + N'' KB'' end),
''growth'' = (case status & 0x100000 when 0x100000 then
convert(nvarchar(15), growth) + N''%''
else
convert(nvarchar(15), convert (bigint, growth) * 8) + N'' KB'' end),
''usage'' = (case status & 0x40 when 0x40 then ''log only'' else ''data only'' end)
from sysfiles
';
 
-- Identify database files that use default auto-grow properties
SELECT databasename AS [Database Name]
      ,name AS [Logical Name]
      ,filename AS [Physical File Name]
      ,growth AS [Auto-grow Setting] FROM #info 
WHERE (usage = 'data only' AND growth = '1024 KB') 
   OR (usage = 'log only' AND growth = '10%')
ORDER BY databasename
 
-- get rid of temp table 
DROP TABLE #info;
Identifying How Often an Auto-growth Event has Occurred:
DECLARE @filename NVARCHAR(1000);
DECLARE @bc INT;
DECLARE @ec INT;
DECLARE @bfn VARCHAR(1000);
DECLARE @efn VARCHAR(10);
 
-- Get the name of the current default trace
SELECT @filename = CAST(value AS NVARCHAR(1000))
FROM ::fn_trace_getinfo(DEFAULT)
WHERE traceid = 1 AND property = 2;
 
-- rip apart file name into pieces
SET @filename = REVERSE(@filename);
SET @bc = CHARINDEX('.',@filename);
SET @ec = CHARINDEX('_',@filename)+1;
SET @efn = REVERSE(SUBSTRING(@filename,1,@bc));
SET @bfn = REVERSE(SUBSTRING(@filename,@ec,LEN(@filename)));
 
-- set filename without rollover number
SET @filename = @bfn + @efn
 
-- process all trace files
SELECT 
  ftg.StartTime
,te.name AS EventName
,DB_NAME(ftg.databaseid) AS DatabaseName  
,ftg.Filename
,(ftg.IntegerData*8)/1024.0 AS GrowthMB 
,(ftg.duration/1000)AS DurMS
FROM ::fn_trace_gettable(@filename, DEFAULT) AS ftg 
INNER JOIN sys.trace_events AS te ON ftg.EventClass = te.trace_event_id  
WHERE (ftg.EventClass = 92  -- Date File Auto-grow
    OR ftg.EventClass = 93) -- Log File Auto-grow
ORDER BY ftg.StartTime
Via: https://www.red-gate.com/simple-talk/databases/sql-server/database-administration-sql-server/sql-server-database-growth-and-autogrowth-settings/