Category Archives: free Access Add-in

How to Use Microsoft Access to Create Logins in a SQL Azure Database

In this article we will demonstrate how you can use a Pass-through query in Access with VBA code to create SQL Azure Logins. Microsoft Access can then use the Login and Password to gain access to SQL Azure Tables, Views, and Stored Procedures. We will create a Login using SQL in Access similar to the following Transact-SQL (T-SQL):

CREATE LOGIN MyLoginName WITH password = ‘zX/w3-q7jU’

Thankfully, a user would never have to memorize that password! Because this Login and password would only be used by my Access application the user never sees it and does not even know it exists.

There are several steps involved in creating a Login and Password for SQL Azure. And although most T-SQL that is used in SQL Azure is exactly the same as that used with SQL Server there are some critical differences which we will address in the following steps.

 

1) Create a Strong Password that Meets the Requirements of the Password Policy.

It is very important to use Strong Passwords because the extra security is needed since we cannot use Windows Authentication with SQL Azure. Passwords must be at least 8 characters long and contain at least one number or special character such as -/~^&.

 

2) Use Characters That Do Not Conflict With ODBC Connection Strings.

To avoid errors we should not use these ODBC connection string characters []{}(),;?*!@ in our Login Name and Password.

 

3) Build a Transact-SQL Statement Which Will Create the Login.

We will use the T-SQL CREATE LOGIN statement in a Pass-through query to create the Login. Since Pass-through queries “pass” the SQL unaltered to SQL Azure most of the time the SQL is just like what we would in SQL Server Management Studio (SSMS) and as seen here:

CREATE LOGIN MyLoginName WITH password = ‘zX/w3-q7jU’

Another requirement of the CREATE LOGIN statement is that it must be the only statement in a SQL batch. So we are only going to create one Login at a time.

 

4) Ensure the Login and Password Are Created In the master Database.

This is required because “USE master” does not work in SQL Azure as it does with SQL Server because the USE statement is not supported in SQL Azure. But with Access we can create the Login in the master database by specifying the master database in our Connection String: “DATABASE=master;”. We use a Function like the one below to get the Connection String with an obfuscated name to keep it more secure.

Public Function obfuscatedFunctionName() As String
    obfuscatedFunctionName = "ODBC;" _
	    & "DRIVER={SQL Server Native Client 10.0};" _
	    & "SERVER=tcp:MyServerName.database.windows.net,1433;" _
	    & "UID=MyUserName@MyServerName;" _
	    & "PWD=MyPassword;" _
	    & "DATABASE=master;" _
	    & "Encrypt=Yes"
End Function

See my article Building Safer SQL Azure Cloud Applications with Microsoft Access for more information about securing your Access application.

 

5) Create a Function to Execute the SQL and Create the Login.

Place the ExecuteMasterDBSQL Function below in a Standard Module. This Function executes our CREATE LOGIN statement. It can be used any time you want to execute a T-SQL statement in the SQL Azure master database that does not return records. The Function returns True if the SQL was executed successfully or False if the SQL fails to be executed.

'This procedure executes Action Query SQL in the SQL Azure master database.	
'Example usage: Call ExecuteMasterDBSQL(strSQL) or If ExecuteMasterDBSQL(strSQL) = False Then
'
Function ExecuteMasterDBSQL(strSQL As String) As Boolean
On Error GoTo ErrHandle

    Dim db As DAO.Database
    Dim qdf As DAO.QueryDef

    ExecuteMasterDBSQL = False 'Default Value

    Set db = CurrentDb

    'Create a temporary unnamed Pass-through QueryDef. This is a
    'practice recommended in the Microsoft Developer Reference.
    'The order of each line of code must not be changed or the code will fail.
    Set qdf = db.CreateQueryDef("")
    'Use a function to get the SQL Azure Connection string to the master database
    qdf.Connect = obfuscatedFunctionName
    'Set the QueryDef's SQL as the strSQL passed in to the procedure
    qdf.SQL = strSQL
    'ReturnsRecords must be set to False if the SQL does not return records
    qdf.ReturnsRecords = False
    'Execute the Pass-through query
    qdf.Execute dbFailOnError

    'If no errors were raised the query was successfully executed
    ExecuteMasterDBSQL = True

ExitHere:
    'Cleanup for security and to release memory
    On Error Resume Next
    Set qdf = Nothing
    Set db = Nothing
    Exit Function

ErrHandle:
    MsgBox "Error " & Err.Number & vbCrLf & Err.Description _
    & vbCrLf & "In procedure ExecuteMasterDBSQL"
    Resume ExitHere

End Function

 

6) Use a Form to Enter the Login Name and Password

We can make it easy for users to create a Login by using a form. To do this we need to add two text boxes and a command button to the form. Both text boxes need to be unbound. Name the text box for the Login Name txtLoginName. Name the text box for the Password txtPassword. Name the command button cmdCreateLogin. The form should look something like this, but without the extra touches for appearance sake.

Create Logins Form

Add the code below to the command button’s Click event. After the code verifies that a Login Name and Password has been entered, it calls the ExecuteMasterDBSQL Function to create the Login in our SQL Azure master database.

Private Sub cmdCreateLogin_Click()

    'Prepare a Variable to hold the SQL statement
    Dim strSQL As String

    'Build the SQL statement
    strSQL = "CREATE LOGIN " & Me.txtLoginName & " WITH password = '" & Me.txtPassword & "'"

    'Verify both a Login Name and a Password has been entered.
    If Len(Me.txtLoginName & vbNullString) = 0 Then
        'A Login Name has not been entered.
        MsgBox "Please enter a value in the Login Name text box.", vbCritical
    Else
        'We have a Login Name, verify a Password has been entered.
        If Len(Me.txtPassword & vbNullString) = 0 Then
        	'A Password has not been entered.
        	MsgBox "Please enter a value in the Password text box.", vbCritical
        Else
        	'We have a Login Name and a Password.
        	'Create the Login by calling the ExecuteMasterDBSQL Function.
	        If ExecuteMasterDBSQL(strSQL) = False Then
	    	    MsgBox "The Login failed to be created.", vbCritical
	        Else
	    	    MsgBox "The Login was successfully created.", vbInformation
	        End If
        End If
    End If
End Sub

The code in the Form checks the return value of the ExecuteMasterDBSQL Function and informs us whether or not the Login was successfully created. Once we have created a Login we can create a Database User for the Login and grant the User access to the data in the SQL Azure Database. Creating a Database User for the Login appears to be a good subject for another article.

Get the free Demonstration Application that shows how effectively Microsoft Access can use SQL Azure as a back end.

More Free Downloads:
Us or UK/AU Pop-up Calendar
Report Date Dialog Form in US or UK/AU Version.
Free Church Management Software with Contributions management.
Code Samples

Get the Access and Outlook Appointment Manager to manage all of your Outlook Calendar Appointments and Access dated information.

Happy computing,
Patrick (Pat) Wood
Gaining Access
http://gainingaccess.net

Download the Free Updated Code Tracker 1.0 Add-in for Access

The free Code Tracker™ Beta Add-in for Microsoft Access® has been upgraded to Version 1.0 and can be used in Access 2002, 2003, and 2007. It is a free download.

The Code Tracker™ 1.0 Add-in records the use of every procedure in your database. You can see how and when your code is being used. We have added a number of Reports and a Report Form that allows you to filter and sort your code use data in a multitude of different ways. Plus the Code Use Data form allows you to view and filter your data in over 17 different ways. You can spot and eliminate procedures and modules that never get used, and you can see which procedures are used most often. You can see the flow of code use for your databases by sorting all used procedures by date and time. The Code Tracker reveals how your code is really working and you will undoubtably be surprised how often some procedures are used.

This free Add-in is not a demo. It is a mda file so you can see all of the code and how it works. Because the data is saved in tables on your database, you can create your own Reports and Forms to view the data according to your needs.


Instructions are included in the zip file. Unzip the downloaded file to the location of your choice and read the text files for help getting started.


Image of Code Tracker Menu


The new Code Tracker Report Manager allows you to filter Reports by dates, Procedures, and Modules.

Image of Code Tracker Report Manager


You can sort code use by procedure, by module, by date and time, by number of uses and more. You can also see a list of every Procedure and Module that is not being used so you can trim unused procedures and Modules from your database. You can drill down to individual modules or procedures.


Image of Code Use Data Form


You can download the free Code Tracker™ 1.0 on our Free Downloads Page.

Other free downloads include our new Microsoft Access and SQL Azure and demonstration application which uses Microsoft Access and SQL Azure to leverage the power of cloud computing.

More Free Downloads:
Us or UK/AU Pop-up Calendar
Report Date Dialog Form in US or UK/AU Version.
Free Church Management Software with Contributions management.
Code Samples


Get the Access and Outlook Appointment Manager to manage all of your Outlook Calendar Appointments and Access dated information.


Happy computing,

Patrick (Pat) Wood
Gaining Access

Instantly Name Microsoft Access Form Controls

Even though Access is the best rapid development tool for databases I have ever used, some things can be drudgery. Take form controls for example. Access names the controls on a form the same as the control source. This makes it easy to have errors. You may try to use the name of the control but Access reads it as the name of the field. To avoid errors like this we have to go through the controls on a form and rename them one at a time. This can really slow down development and it gets to be drudgery after a few forms. So to save myself some time I wrote the following procedure which renames the most used controls on a form in a flash.

The code works by looping through the various controls on a form and adding an appropriate prefix to the existing name. You can run the procedure from the Immediate window using the following code:

Call NameFormControls("frmMyFormName")


Below is the procedure that does all the work. All you need to do is add it to a Standard Module and call it using the name of your form.

Public Sub NameFormControls(strFormName As String)
 
    Dim frm As Form
    Dim ctl As Control
    Dim strCtlName As String
    Dim ctlLabel As Label

    ' Open the Form in Design View and make it invisible
    DoCmd.OpenForm strFormName, acDesign, , , , acHidden

    ' Instatiate the form
    Set frm = Forms(strFormName)

    ' Loop through all the controls on the Form
    For Each ctl In frm.Controls
        ' Name specific controls according to their type
        ' making sure the control has not already been named
        Select Case ctl.ControlType
            Case acTextBox
                If Left(ctl.Name, 3) <> "txt" Then
                    ctl.Name = "txt" & ctl.Name
                End If
            Case acComboBox
                If Left(ctl.Name, 3) <> "cbo" Then
                    ctl.Name = "cbo" & ctl.Name
                End If
            Case acListBox
                If Left(ctl.Name, 3) <> "lst" Then
                    ctl.Name = "lst" & ctl.Name
                End If
            Case acCheckBox
                If Left(ctl.Name, 3) <> "chk" Then
                    ctl.Name = "chk" & ctl.Name
                End If
            Case acLabel
                Set ctlLabel = ctl
                If Left(ctl.Name, 3) <> "lbl" Then
                    ctl.Name = "lbl" & ctlLabel.Caption
                End If
        End Select
    Next ctl
 
    ' Close and save the Form
    DoCmd.Close acForm, strFormName, acSaveYes
 
    ' Release Memory
    Set ctlLabel = Nothing
    Set ctl = Nothing
    Set frm = Nothing 

End Sub


This code even names the labels! You may want to change the caption or format a label in some situations and this makes it much easier to manage.


I hope this code can help you make your Access development work a little easier and faster.

Other free downloads include our new Microsoft Access and SQL Azure and demonstration application which uses Microsoft Access and SQL Azure to leverage the power of cloud computing.

More Free Downloads:
Us or UK/AU Pop-up Calendar
Report Date Dialog Form in US or UK/AU Version.
Free Church Management Software with Contributions management.
Code Samples


Get the Access and Outlook Appointment Manager to manage all of your Outlook Calendar Appointments and Access dated information.


Happy computing,

Patrick (Pat) Wood
Gaining Access

Document Access Code Use with the Free Code Tracker Beta Add-in

On June 1, Liz Ravenwood asked the MS_Access_Professionals group on Yahoo, “Is there a way that I can determine if chunks of my vba code is never being used?”

As I thought about this I thought that there should be a way to do this without spending a small fortune on expensive software. I recalled some code I had dabbled with some time ago. Now that dabbling was about to pay off. It gave me a start on how I could develop an Application that would do exactly what Liz wanted. This eventually became the free Code Tracker™ Beta Add-in for Microsoft Office Access® versions 2002-2003.


With the Code Tracker™ Beta Add-in you can you can record the use of every procedure and see how and when your code is being used in over 17 different ways. You can spot and eliminate procedures and modules that never get used, and you can see which procedures are used most often. You can see the flow of code use for your databases by sorting all used procedures by date and time.


This free Add-in is not a demo. It is a mda file so you can see all of the code and how it works.

Image of Code Tracker Menu


Instructions are included in the zip file. Unzip the downloaded file to the location of your choice and read the text files for help getting started. You can download the free Code Tracker™ Beta Add-in at my Gaining Access website.

The Code Tracker™ Beta for Microsoft Office Access®

The Code Tracker requires one line of code to be added to each procedure to record that procedure’s use. The Code Tracker makes adding this code very easy. You only have to click a button and the Code Tracker inserts the required line of tracking code into every procedure in a database. You can also click another button and remove every line of the code that was inserted into the procedures. A log file records the code and line number of every deletion to a text log file so you do not have to worry about loosing your code. You also have the choice of writing the line of code to place it into the procedures of your choice. The MZ-Tools Add-in can enable you to use a shortcut key to add the code to your procedures.

The Code Use Data form can sort the information in 17 different ways to help you understand how your code is being used.

Image of Code Use Data Form


You can sort code use by procedure, by module, by date and time, by number of uses and more. You can also see a list of every Procedure and Module that is not being used so you can trim unused procedures and Modules from your database. You can drill down to individual modules or procedures.

See How Your Code is Actually Being Used Instead of Just Seeing a Static Code Diagram

The Code Tracker™ Beta shows you the flow of your code as it uses and reuses procedures in your database. Be prepared for some surprising revelations as you learn precisely what your code is doing. You will learn that some procedures are used far more often than you would think and other procedures are not used at all. Knowing how your code is being used can help you do far more that just trim the unused modules and procedures from your database. It can help you make your database leaner and run faster.

How the Code Tracker™ Beta Can Help You Increase the Performance of Your Application

Whenever you run a procedure or set or retrieve the value of a variable in a module, Access does not load just that procedure or variable, it loads the entire module into memory. The modules that are loaded into memory are not removed from memory until the database is closed. This can place an unnecessary burden upon the performance of your application.

You can improve the performance of your application by placing your most often used procedures together in modules with other often used procedures. This will increase performance because the other often used procedures will already be loaded into memory, ready to be used. You can also place your seldom used procedures in small modules so that when they are loaded into memory your database does not take an unnecessary performance hit by loading a large module of procedures it may not use.

How Code Tracker™ Beta Works

How does the Code Tracker™ Beta work? While it is actually fairly easy to write code by hand to record the use of a single procedure, it is quite difficult to write code to insert it into all of the procedures. To manually insert code into a procedure you only need to add one line of code like this:

Call RecordCodeUse("YourProcedureName", "YourModuleName", Now())


This code passes the name of the Procedure, the name of the Module, and the date and time the procedure was used to the RecordCodeUse sub, which is in a standard module. The RecordCodeUse sub appends the information into the table USystblCodeUse using the code below.

Sub RecordCodeUse(strProcName As String, strMdlName As String, dteWhenUsed As Date)

    Dim strSQL As String

    strSQL = "INSERT INTO USystblCodeUse " _
                 & "(ProcName, ModuleName, WhenUsed) " _
                 & "Values (""" & strProcName & """, " _
                 & """" & strMdlName & """, " _
                 & "#" & dteWhenUsed & "#);"

    CurrentDb.Execute strSQL, dbFailOnError

End Sub


That is all there is to it. This code is lean and it runs fast. By using CurrentDb.Execute and dbFailOnError the code rolls back the updates if an error occurs making sure we do not have any records with only part of the data. We are using a hidden table, USystblCodeUse, because you may not want other users to see it and tamper with it.


That was the easy part. The hard part was making it possible to click a button and insert that line of code into every procedure in the database. The code has to be put into each procedure without causing errors in the procedure. We wanted to insert the code immediately after the start of the procedure since that is the safest place. That is not as easy as it may appear at first. Consider the following code.

Public Function SendEmail(strTo As String, _
                     strSubject As String, _
                     strMessageBody As String, _
                     Optional strAttachmentPaths As String, _
                     Optional strCC As String, _   
                     Optional strBCC As String)
                     As Boolean


We want to place our line of code in the procedure immediately after the first line if we can. But if we did that as you can see in this case it would ruin the procedure.


Public Function SendEmail(strTo As String, _
Call RecordCodeUse("SendEmail", "modEmail", Now())
                     strSubject As String, _
                     strMessageBody As String, _
                     Optional strAttachmentPaths As String, _
                     Optional strCC As String, _
                     Optional strBCC As String) As Boolean


Now that is some ugly code! So we have written our code and tested it to avoid this as well as other problems such as inserting the code within a Select Case construct. And since this is a free Beta version we are releasing, we ask that you please report any problems to us at contact@gainingaccess.net. We would also like for you to send us your feature requests.


You can find and download the free Code Tracker™ Beta on our Free Downloads Page.


I hope the Code Tracker™ Beta can help you make your Access Applications better.

Other free downloads include our new Microsoft Access and SQL Azure and demonstration application which uses Microsoft Access and SQL Azure to leverage the power of cloud computing.

More Free Downloads:
Us or UK/AU Pop-up Calendar
Report Date Dialog Form in US or UK/AU Version.
Free Church Management Software with Contributions management.
Code Samples


Get the Access and Outlook Appointment Manager to manage all of your Outlook Calendar Appointments and Access dated information.


Happy computing,

Patrick (Pat) Wood
Gaining Access

Follow

Get every new post delivered to your Inbox.