cgeier 187 Junior Poster

I've updated the code. See the notes inside the files (inside FtpDownload.zip) for more details.

Resources:

using ftp to download a file

FtpWebRequest Download File

Downloading Files Using FTPWebRequest

FtpWebRequest Class

System.Net.FtpWebRequest class behaves differently in .Net Framework 4 vs .Net Framework 3.5

Files attached below (in .zip file):

cgeier 187 Junior Poster

The following should work:

    Private _filenamePattern As String = ".*(?<filename>\d{4}-\d{2}-\d{2}-\d{4}.txt.tgz).*"

    Private _ftpRequest As FtpWebRequest = Nothing

    Private _downloadDirectory As String = String.Empty
    Private _ftpUrl As String = String.Empty
    Private _password As String = "user@name.com"
    Private _username As String = "anonymous"

        'Enum
    Private Enum FtpMethod
        ListFiles = 0
        Download = 1
    End Enum

        Private Function getNewestFilename(ByVal directoryData As String) As String

        Dim output As String = String.Empty
        Dim lastFilename As String = String.Empty
        Dim newestFilename As String = String.Empty

        'create new instance of RegEx
        Dim myRegex As New Regex(_filenamePattern)

        'create new instance of Match
        Dim myMatch As Match = myRegex.Match(directoryData)

        'keep looking for matches until no more are found
        While myMatch.Success

            'get groups
            Dim myGroups As GroupCollection = myMatch.Groups

            'For Each groupName As String In myRegex.GetGroupNames
            'output += String.Format("Group: '{0}' Value: {1}", groupName, myGroups(groupName).Value)
            'output += System.Environment.NewLine
            'Next

            'Console.WriteLine(output)

            lastFilename = myGroups("filename").Value

            If Not String.IsNullOrEmpty(newestFilename) Then
                If lastFilename > newestFilename Then
                    newestFilename = lastFilename
                End If
            Else
                newestFilename = myGroups("filename").Value
            End If

            'Console.WriteLine("lastFilename: " + lastFilename + " newestFilename: " + newestFilename)


            'get next match
            myMatch = myMatch.NextMatch()
        End While

        If String.IsNullOrEmpty(newestFilename) Then
            newestFilename = "No matches found for specified pattern."
        End If

        Return newestFilename
    End Function

        Private Function CreateFtpWebRequest(ByVal ftpUrl As String, ByVal username As String, ByVal password As String, ByVal ftpMethod As FtpMethod, ByVal keepAlive As Boolean) As Stream

        'defined as Private
        '_ftpRequest = DirectCast(WebRequest.Create(New Uri(ftpUrl)), FtpWebRequest)
        _ftpRequest = WebRequest.Create(New Uri(ftpUrl))

        'either download the file or
        'list the files in the directory
        If ftpMethod = 0 Then …
cgeier 187 Junior Poster

I don't understand why you would have to "modify the regex everytime". From the data you provided, the last filename is the newest filename. So you just have to get the last filename. If the filenames could be listed in a different order then what you need to do is search through the list of files and determine which one is the newest.

The following code will find the newest filename given the filename format that you have provided:

    Public Function extractData(ByVal myData As String) As String

        Dim output As String = String.Empty
        Dim lastFilename As String = String.Empty
        Dim newestFilename As String = String.Empty

        'Dim pattern As String = "[-rwx]{10}\s+\d\s+\d\s+\d\s+\d+\s+(?<monthName>[A-Z][a-z]+)\s+(?<monthNumber>\d+)\s+(?<timeOfDay>\d{2}:\d{2})\s+(?<filenameDateYear>\d{4})-(?<filenameDateMonth>\d{2})-(?<filenameDateDay>\d{2})-(?<filenameTimePart>\d{4}).txt.tgz.*"
        'Dim pattern As String = "[-rwx]{10}\s+\d\s+\d\s+\d\s+\d+\s+(?<monthName>[A-Z][a-z]+)\s+(?<monthNumber>\d+)\s+(?<timeOfDay>\d{2}:\d{2})\s+(?<filename>\d{4}-\d{2}-\d{2}-\d{4}.txt.tgz).*"
        'Dim pattern As String = ".*(?<monthName>[A-Z][a-z]+)\s+(?<monthNumber>\d+)\s+(?<timeOfDay>\d{2}:\d{2})\s+(?<filename>\d{4}-\d{2}-\d{2}-\d{4}.txt.tgz).*"

        Dim pattern As String = ".*(?<filename>\d{4}-\d{2}-\d{2}-\d{4}.txt.tgz).*"

        'create new instance of RegEx
        Dim myRegex As New Regex(pattern)

        'create new instance of Match
        Dim myMatch As Match = myRegex.Match(myData)

        'keep looking for matches until no more are found
        While myMatch.Success

            'get groups
            Dim myGroups As GroupCollection = myMatch.Groups

            'For Each groupName As String In myRegex.GetGroupNames
            'output += String.Format("Group: '{0}' Value: {1}", groupName, myGroups(groupName).Value)
            'output += System.Environment.NewLine
            'Next

            'Console.WriteLine(output)

            lastFilename = myGroups("filename").Value

            If Not String.IsNullOrEmpty(newestFilename) Then
                If lastFilename > newestFilename Then
                    newestFilename = lastFilename
                End If
            Else
                newestFilename = myGroups("filename").Value
            End If

            'Console.WriteLine("lastFilename: " + lastFilename + " newestFilename: " + newestFilename)


            'get next match
            myMatch = myMatch.NextMatch()
        End While

        Return newestFilename
    End Function

Usage:

Dim lastFilename as String = extractData(myData)

Example usage:

cgeier 187 Junior Poster

Try one of the following:

Version 1:

Dim pattern As String = "[-rwx]{10}\s+\d\s+\d\s+\d\s+\d+\s+(?<monthName>[A-Z][a-z]+)\s+(?<monthNumber>\d+)\s+(?<timeOfDay>\d{2}:\d{2})\s+(?<filename>\d{4}-\d{2}-\d{2}-\d{4}.txt.tgz).*"

Version 2:

Dim pattern As String = "[-rwx]{10}\s+\d\s+\d\s+\d\s+\d+\s+(?<monthName>[A-Z][a-z]+)\s+(?<monthNumber>\d+)\s+(?<timeOfDay>\d{2}:\d{2})\s+(?<filenameDatePart>\d{4}-\d{2}-\d{2})-(?<filenameTimePart>\d{4}).txt.tgz.*"

Version 3:

Dim pattern As String = "[-rwx]{10}\s+\d\s+\d\s+\d\s+\d+\s+(?<monthName>[A-Z][a-z]+)\s+(?<monthNumber>\d+)\s+(?<timeOfDay>\d{2}:\d{2})\s+(?<filenameDateYear>\d{4})-(?<filenameDateMonth>\d{2})-(?<filenameDateDay>\d{2})-(?<filenameTimePart>\d{4}).txt.tgz.*"

Group names are "monthName", "monthNumber", "timeOfDay", etc...:

Console.WriteLine("monthName: '" + myMatch.Groups("monthName").Value + "'")

or

For Each g As Group In myGroups
    Console.WriteLine(g.Value)
Next
cgeier 187 Junior Poster

Please post the value of "result" after line #15 is executed.

cgeier 187 Junior Poster

Please show your table relationships.

cgeier 187 Junior Poster

There is some code in this post that uses regex. It demonstrates usage of regex in VB .NET.

cgeier 187 Junior Poster

The code above is not for Exchange.

These may be of use:

Programmatically Accessing Outlook Contacts Via Exchange Web Services

How do I access my Outlook contacts from my web application?

I don't have access to an Exchange server to test the code.

cgeier 187 Junior Poster

You will also need to change the protection level of "FirstName", "LastName", and "EmailAddress" (in person).

Otherwise the following line will throw a compiler error:

mailing.Bcc.Add(person.EmailAddress);

Accessibility Levels (C# Reference)

Members of: class

Default member accessibility: private

cgeier 187 Junior Poster

Personalize the message. In emailText replace the word "user" with each person's first name. Use String.Replace

cgeier 187 Junior Poster
cgeier 187 Junior Poster

Try surrounding string values with single quotes. Or better yet, use parameters. Search for parameterized queries.

cgeier 187 Junior Poster

The following was tested on Outlook 2010:

If you've already added the .pst files you want, do the following:

Version 1 (.pst manually added):

Private Sub getOutlookEmailInfo()
    Dim output As String = String.Empty
    Dim olApp As Outlook.Application = Nothing
    Dim olNameSpace As Outlook.NameSpace = Nothing

    'create new instance of Outlook.Application
    olApp = New Outlook.Application()

    'set olNameSpace to MAPI namespace
    olNameSpace = olApp.GetNamespace("MAPI")

    ' TODO: Replace the "YourValidProfile" 
    ' and "myPassword" with Missing.Value 
    ' if you want to log on with the default profile.
    ' olNameSpace.Logon("YourValidProfile", "myPassword", True, True)
    ' olNameSpace.Logon()


    'loop through stores
    For Each oStore As Outlook.Store In olNameSpace.Stores

        'root folder for store
        Dim rootFolder As Outlook.MAPIFolder = oStore.GetRootFolder()

        'folders for store
        Dim subFolders As Outlook.Folders = rootFolder.Folders

        'loop through all folders
        For Each oFolder As Outlook.Folder In subFolders

            'get folder items
            Dim oItems As Outlook.Items = oFolder.Items

            'search through each email
            For Each email As Object In oItems

                'make sure item is a mail item,
                'not a meeting request
                If email.MessageClass = "IPM.Note" Then
                    If TypeOf email Is Microsoft.Office.Interop.Outlook.MailItem Then
                        output += "oStore: " + oStore.DisplayName + " oFolder: " + oFolder.Name + " " + "subject: " & email.Subject & System.Environment.NewLine
                    End If
                End If
            Next
        Next
    Next

    'olNameSpace.Logoff()

    olNameSpace = Nothing
    olApp = Nothing

    MessageBox.Show(output)

End Sub

Version 1 Usage:

getOutlookEmailInfo()

If you want to programmatically add the .pst files.

Version 2 (.pst filename specified, display name not specified, .pst added programmatically):

Private Sub getOutlookEmailInfo(ByVal pstList As List(Of String))
    Dim output …
cgeier 187 Junior Poster

Add reference to "Microsoft Outlook xx.x Object Library" (where xx.x = 14.0, 12.0, etc):
* Click "Project"
* Select "Add Reference"
* Click "COM"
* Select "Microsoft Outlook 14.0 Object Library"

Add Imports statement:

  • Imports Outlook = Microsoft.Office.Interop.Outlook;

getContacts:

Private Sub getContacts()

    'create new instance of Outlook.Application
    Dim outlookApp As Outlook.Application = New Outlook.Application()

    'create new instance of Outlook.MAPIFolder
    Dim outlookMapiFolder As Outlook.MAPIFolder = Nothing

    'create new instance of Outlook.Items
    Dim outlookItems As Outlook.Items = Nothing

    'set outlookMapiFolder to Contacts folder
    outlookMapiFolder = outlookApp.GetNamespace("MAPI").GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts)

    'get items from contacts
    outlookItems = outlookMapiFolder.Items


    For i As Integer = 0 To outlookItems.Count - 1

        Dim contact As Outlook.ContactItem = outlookItems(i + 1)


        Dim entryId As String = contact.EntryID
        Dim fullName As String = contact.FullName
        Dim companyName As String = contact.CompanyName
        Dim email1Address As String = contact.Email1Address
        Dim email1AddressType As String = contact.Email1AddressType
        Dim businessTelephoneNumber As String = contact.BusinessTelephoneNumber
        Dim homeTelephoneNumber As String = contact.HomeTelephoneNumber
        Dim mobileTelephoneNumber As String = contact.MobileTelephoneNumber

        'add any additional entries that you want to retrieve



        'add entryId and fullName to dataGridView1
        'where DataGridView1 is a DataGridView with
        'columns "entryId" and "fullName"
        DataGridView1.Rows.Add(entryId, fullName)

    Next
End Sub

Resources:
Adapted from: Get Outlook Contacts in to C# form based Application

Outlook Object Model Overview

cgeier 187 Junior Poster

Wmi is for computers running Windows. You need to provide more info about your devices and environment.

cgeier 187 Junior Poster

The above assumes that your program is running on each client pc.

cgeier 187 Junior Poster

Use wmi to get the relevant info (mac address, ip address, etc) and send that info wherever you want to send it.

cgeier 187 Junior Poster

I don't understand what you are looking for. What do you mean by "but also the pst(s) that is loaded in the outlook"? Maybe you can post a screen shot and then a description based on the screenshot. Also are you trying to do this for all users (on a computer) or only the currently logged in user?

cgeier 187 Junior Poster

Please post some code and some more information. Are you adding the data using datagridview? Or on another form?

cgeier 187 Junior Poster

You might have better luck in the "Visual Basic 4/5/6" forum. You may want to include the version of Excel that you are using. Some sample data is also beneficial.

Visual Basic for Applications

"Visual Basic for Applications (VBA) is an implementation of Microsoft's event-driven programming language Visual Basic 6..."

"...Compatibility ends with Visual Basic version 6; VBA is incompatible with Visual Basic .NET (VB.NET)..."

cgeier 187 Junior Poster

VBA is not VB .NET.

Visual Basic for Applications

cgeier 187 Junior Poster

movementClass.cs:

Add the following "using" statements:

using System.Drawing; and
using System.Windows.Forms;

public static class movementClass 
{
    public static void moveLeft(PictureBox moveBox)
    {
        Point p = moveBox.Location;
        p.X -= 20;
        moveBox.Location = p;
    }

    public static void moveDown(PictureBox moveBox)
    {
        Point p = moveBox.Location;
        p.Y += 20;
        moveBox.Location = p;
    }
}

Then in Form1.cs:

private void downBut_Click(object sender, EventArgs e)
{
    movementClass.moveDown(moveBox);
}

private void leftBut_Click(object sender, EventArgs e)
{
    movementClass.moveLeft(moveBox);
}
cgeier 187 Junior Poster

Try the following:

Boot into Safe Mode, then

  • Click "Start"
  • Select "Control Panel"
  • For View by, select "Small Icons" (or Large Icons)
  • Click "System"
  • Click "Advanced System Settings"
  • Do you want to allow the following program to make changes...? Click, "Yes"
  • Click "Advanced" tab
  • Under "Startup and Recovery", click "Settings"
  • Under "System failure", uncheck "Automatically restart"
  • Click "OK"
  • Click "OK"
  • Reboot computer.

If it successfully boots, you may see an error message which should help you identify what is causing the error.

cgeier 187 Junior Poster

It's in "javax.swing.JList".

See the documentation for more info:
JList

cgeier 187 Junior Poster
cgeier 187 Junior Poster

I think that you may need to use Command Line Processor Plus (CLPP) from IBM Data Server Driver Package.

To download and install:
IBM Support Fix Central

Method 1:

  • Click "Select product" tab
  • For "Product Group", select "Information Management"
  • For "Select from Information Management", select "IBM Data Server Client Packages"
  • For "Installed Version", select "10.5.*"
  • For "Platform", select "Windows"
  • Click "Continue"
  • Click "Continue" (Browse for fixes radio button should be checked by default)

Method 2:

  • Click "Find product" tab
  • For "Product selector", ente "Information Management"
  • For "Product selector " enter "IBM Data Server Client Packages"
  • For "Installed Version", select "10.5.*"
  • For "Platform", select "Windows"
  • Click "Continue"
  • Click "Continue" (Browse for fixes radio button should be checked by default)

Download and install "IBM Data Server Driver Package":

For 32-bit:
Download and install "IBM Data Server Driver Package (Windows/x86-32 32 bit) V10.5 Fix Pack 3

For 64-bit:
Download and install "IBM Data Server Driver Package (Windows/x86-64 64 bit) V10.5 Fix Pack 3

After installation, DB2 Command Line Processor Plus can be found in:

(for Win 7):

  • Start
  • All Programs
  • IBM DB2 DB2COPY1 (or IBM DB2...))
  • DB2 Command Line Processor Plus

or

  • Start
  • All Programs
  • Accessories
  • Command Prompt
  • Type: clpplus

Note: clpplus runs "C:\Program Files\IBM\SQLLIB\BIN\clpplus.bat" (for 32-bit)

Then:

SQL> connect user1/'YourPassword'@127.0.0.1:50000/sample

where
user1 = you user name
YourPassword = your password
127.0.0.1 = your IP address
50000 = port number
sample = database name

cgeier 187 Junior Poster

That syntax is for DB2 Command Line Processor Plus. You are trying to use it in DB Command Line Processor. They are two different tools.

When using DB2 Command Line Processor Plus you will see: SQL>

When using DB2 Command Line Processor you will see: db2=>

cgeier 187 Junior Poster

After installation, DB2 Command Line Processor Plus can be found in:

(for Win 7):
* Start
* All Programs
* IBM DB2...
* DB2 Command Line Processor Plus

cgeier 187 Junior Poster

Use command line processor (CLP) from IBM Data Server Runtime Client or Command line process plus (CLPP) from IBM Data Server Driver Package

See also:

IBM Knowledge Center

  • Click "Database fundamentals"
  • Click "Installing"
  • Click "Installing IBM Data Server drivers and clients"

Additional info:

  • Click "Developing code for accessing and managing data"
  • Click "Database applications"
    See desired links (ADO.NET, OLE DB, etc...)

To connect in DB2 Command Line Processor Plus:

SQL> connect user1/'YourPassword'@127.0.0.1:50000/sample

where:
user1 = you user name
YourPassword = your password
127.0.0.1 = your IP address
50000 = port number
sample = database name

cgeier 187 Junior Poster

Here are multiple ways of retrieving data from DB2. They were tested using the express version of DB2.

See previous post on installing appropriate packages and adding reference to "IBM.Data.DB2" and imports statement: Imports IBM.Data.DB2

In the following examples, I will use the following:

  • Schema name: HR
  • Database name: Sample
  • IP Address: 127.0.0.1
  • Port: 50000

Version 1 & version 2 are preferred methods.

Version 1: (using DB2Connection and DB2DataAdapter)

  • Add Imports IBM.Data.DB2

    Private Sub readDataFromDB2NETv1()
        Dim connectStr As String
        Dim sqlText As String
        Dim conn As New DB2Connection
    
        'without TrustedContext
        connectStr = "Database=Sample;Server=127.0.0.1:50000;Uid=db2admin;Pwd=nopass;"
        'connectStr = "Database=Sample;Server=127.0.0.1:50000;UserID=db2admin;Password=nopass;"
    
        'if TrustedContext has been set up
        'connectStr = "Database=Sample;Server=127.0.0.1:50000;UserID=db2admin;Password=nopass;TrustedContextSystemUserID=masteruser;TrustedContextSystemPassword=masterpassword"
    
    
        Try
    
            conn = New DB2Connection(connectStr)
            conn.Open()
    
            sqlText = "Select * from HR.Employee"
    
            Dim da As New DB2DataAdapter(sqlText, conn)
    
            Dim rowsRetrieved As Integer
            Dim output As String = String.Empty
    
            Dim dt As DataTable = New DataTable()
    
            'fill DataTable
            rowsRetrieved = da.Fill(dt)
    
            'close connection
            conn.Close()
    
            For Each row As DataRow In dt.Rows
                Dim col0 As String = row(0).ToString()
                Dim col1 As String = row(1).ToString()
                Dim col2 As String = row(2).ToString()
    
                output += col0 & " " & col1 & " " & col2
                output += System.Environment.NewLine
            Next
    
            MessageBox.Show(output)
    
        Catch ex As DB2Exception
            MessageBox.Show(ex.Message)
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub
    

Version 2 (using DB2Connection and DB2DataReader):

  • Add Imports IBM.Data.DB2

    Private Sub readDataFromDB2NETv2()
        Dim connectStr As String
        Dim sqlText As String
        Dim conn As New DB2Connection
    
        'without TrustedContext
        'connectStr = "Database=Sample;Server=127.0.0.1:50000;Uid=db2admin;Pwd=nopass;"
        connectStr = "Database=Sample;Server=127.0.0.1:50000;UserID=db2admin;Password=nopass;"
    
        'if TrustedContext has been set up
        'connectStr …
cgeier 187 Junior Poster

Go to IBM Fix Central website:
Fix Central

Click "Find Product" tab
In "Product Selector", enter IBM Data Server Client Packages
For "Installed Version", select 10.5.*
For "Platform", select Windows
Click Continue
Select Browse for fixes radio button
Click Continue

Download and install fix pack that says "IBM Database Add-Ins for Visual Studio"

May also need to download/install "IBM Data Server Driver Package (Windows/x86-32 32bit) V10.5 Fix Pack 3" for 32-bit OS. Or "IBM Data Server Driver Package (Windows/x86-64 64bit) V10.5 Fix Pack 3"

Add Reference:

  • Click "Project" (in menu)
  • Select "Add Reference"
  • Select "Add Reference"
  • Select ".NET"
  • Select "IBM.Data.DB2"
  • Click "OK"

Add Imports IBM.Data.DB2

Try the following:

        Dim connectStr As String
        Dim sqlText As String
        Dim conn As New DB2Connection

        connectStr = "Database=Sample;Server=127.0.0.1:50000;Uid=db2admin;Pwd=yourpass;"


        conn = New DB2Connection(connectStr)
        conn.Open()


        sqlText = "Select * from SchemaName.Employee"

        Dim cmd As New DB2Command(sqlText, conn)

Where "127.0.0.1" is your IP address, and "50000" is your port number, and "SchemaName" is your desired schema name (ex: user1)

cgeier 187 Junior Poster

The following seems to work to view e-mail subjects (from Inbox):

Add Reference to Microsoft Outlook xx.x Object Library (where xx.x is a number: 12.0, 14.0, etc)

  • Click "Project" (in menu)
  • Select "Add Reference"
  • Click "COM"
  • Select "Microsoft Outlook 14.0 Object Library"

Add Imports Outlook = Microsoft.Office.Interop.Outlook

    Private Sub getOutlookEmailInfo()

        Dim outlookapp As Outlook.Application = New Outlook.Application()
        Dim olNameSpace As Outlook.NameSpace = outlookapp.GetNamespace("MAPI")

        ' TODO: Replace the "YourValidProfile" and "myPassword" with 
        'Missing.Value if you want to log on with the default profile.
        'olNameSpace.Logon("YourValidProfile", "myPassword", True, True)
        'olNameSpace.Logon()

        Dim oInbox As Outlook.MAPIFolder = olNameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox)
        Dim oItems As Outlook.Items = oInbox.Items

        Dim output As String = String.Empty
        For Each email As Outlook.MailItem In oItems
            output += "subject: " & email.Subject & System.Environment.NewLine
        Next

        MessageBox.Show(output)

    End Sub

Resources:
Reading e-mail without Outlook app open

Looping over Outlook mail items in "Sent Items" folder

How to use the Microsoft Outlook Object Library to create an Outlook contact in Visual Basic .NET

How to automate Outlook by using Visual Basic

cgeier 187 Junior Poster

Installing IBM Data Server drivers and clients

The following is for C#, but can be easily translated to VB .NET:

Connection to DB2 from .NET

cgeier 187 Junior Poster

Use a "Sub".

Functions and subroutines

"...Subroutines are useful because they eliminate redundancy..."

cgeier 187 Junior Poster

The poster stated she is using DB2, not SQL Server.

SqlConnection Class
Represents an open connection to a SQL Server database

Use ODBC or OleDB.

Connection Strings

cgeier 187 Junior Poster

Did you try the following?

  • Click "Project" (in menu bar)
  • Select "Add Reference"
  • Click ".NET" tab
  • Select "Microsoft.Office.Interop.Outlook" (version 14.0.0.0)
  • Click "OK"
cgeier 187 Junior Poster

I think that you don't understand the difference between sub, function, module, and class.

Here's a basic description:

A "Function" is basically a "Sub" that returns a value.

Functions and Subs (as well as other things) are contained within Classes and/or Modules.

cgeier 187 Junior Poster

Have you checked the value of "intDays" after you call "getDaysOut(intDays)"?

You have the following:
Private Sub getDaysOut(intDays As Integer)

it should be:
Private Sub getDaysOut(ByRef intDays As Integer)

If you don't include "ByRef", the default is to pass the parameter "ByVal".

An alternative is:

    Private Function getDaysOut() As Integer
        Dim intDays As Integer = 0

        Console.Write("How many days did the customer have the DVD? ")

        If Int32.TryParse(Console.ReadLine(), intDays) Then
            getDaysOut = intDays
        Else
            getDaysOut = 0
        End If

    End Function

Usage:

Dim intDays As Integer = 0
intDays = getDaysOut()

        ...

Resource:
How to: Force an Argument to Be Passed by Value (Visual Basic)

...When you pass a variable by reference, you must use the ByRef keyword to specify this mechanism.

The default in Visual Basic is to pass arguments by value...

cgeier 187 Junior Poster

If you right-click the file and "Send To" => "Compressed (Zipped) Folder", you can attach it.

cgeier 187 Junior Poster

See above where it says: usage of the attached file.

cgeier 187 Junior Poster
cgeier 187 Junior Poster

Your connection string is incorrect.

Should be:
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Video Rental System\DvDSystem1.accdb"

Also add the following:

Catch ex As OleDB.OleDbException

Access Connection String

cgeier 187 Junior Poster

Is your Win 8.1 32-bit or 64-bit? What version of Outlook (year and 32-bit or 64-bit)?

Developing Outlook 2010 Solutions for 32-Bit and 64-Bit Systems

cgeier 187 Junior Poster

Here's "doTasks" that is in the attached file above:

    Public Sub doTasks(ByVal username As String, _
                        ByVal ToolStripStatusLabel1 As ToolStripStatusLabel, _
                        ByVal StatusStrip1 As StatusStrip, _
                        ByVal MenuStrip1 As MenuStrip, _
                        ByVal databaseProduct As String)

        Dim errMessage As String = String.Empty
        Dim permissionsDt As DataTable = Nothing

        'set private variable values
        'used by other methods
        _ToolStripStatusLabel1 = ToolStripStatusLabel1
        _StatusStrip1 = StatusStrip1

        Try

            If databaseProduct = "SQLExpress" Then
                'get user permissions from db
                permissionsDt = getPermissionsSQLExpress(username)
            ElseIf databaseProduct = "mySQL" Then
                'get user permissions from db
                permissionsDt = getPermissionsMySQL(username)
            Else
                errMessage = "Error: (doTasks): " & " Database product not supported. "
                errMessage += "Must be 'SQLExpress' or 'mySQL'."
                MessageBox.Show(errMessage)
                ToolStripStatusLabel1.Text = errMessage
                _StatusStrip1.Refresh()
            End If


            If permissionsDt IsNot Nothing Then
                setPermissions(permissionsDt, MenuStrip1)
            End If

        Catch ex As Exception
            errMessage = "Error: (doTasks): " & ex.Message
            MessageBox.Show(errMessage)
            ToolStripStatusLabel1.Text = errMessage
            _StatusStrip1.Refresh()
        End Try
    End Sub
cgeier 187 Junior Poster

The following will show how to hide/show a menu based on user rights/permissions using a database that uses the structure in my post(s) above. There are most likely other ways of doing this, but the way I decided to do it was by making use of recursion. I use Dictionary and List in the process.

Ensure that you have SQLExpress or mySQL installed.

In this example, I use a database named "UserApp". So, create a new database named "UserApp". And create the file structure as previously described. Do not enter the sample data yet as I have made some slight modifications that will eliminate the need for some of the data. I require that only the youngest ToolStripMenuItem be entered in the database. It will be assumed that a user will also need access to all of the menus ancestors (parents).

Create a form named "Form1.vb" and add the following to it:

  • Add a ComboBox named "ComboBox1" to the form.
  • Add a Button named "Button1" to the form.
  • Add a StatusStrip named "StatusStrip1" to the form. Then add a StatusLabel named ToolStripStatusLabel1" to "StatusStrip1".
  • Add a MenuStrip named "MenuStrip1" to the form. Then create the following structure in MenuStrip1:

File menu:

  • File => Backup
  • File => Exit

Tools menu:

  • Tools => Accounting
  • Tools => Employee => EmployeeSubMenu1
  • Tools => Employee => EmployeeSubMenu2
  • Tools => Order Entry
  • Tools => Refresh

Create a module named "AppPermissionsModule.vb".

For SQLExpress, add the following Imports statement: Imports System.Data.SqlClient

For mySQL, ensure …

cgeier 187 Junior Poster

My previous post was incorrect. Don't add Namespace My to "resultex". Change line #23 in "MyApplication" to:

Me.MainForm = My.Forms.resultex

The format is: Me.MainForm = My.Forms.<your form name to start>

cgeier 187 Junior Poster

I would say because class "resultex" is missing Namespace My which happens to be referenced in line #23 in "MyApplication" (Me.MainForm = My.Forms.MainForm). See line #11 & #27 in "MyApplication" for the placement (the position it should be in within "resultex").

cgeier 187 Junior Poster

You may consider storing the MenuStrip (ToolStripMenuItem) variable names in the database.

ex:

  • FileToolStripMenuItem
  • BackupToolStripMenuItem
  • ExitToolStripMenuItem
  • ToolsToolStripMenuItem
  • AccountingToolStripMenuItem
  • EmployeeToolStripMenuItem

The database structure will stay the same. The sample data in two of the tables will change as follows:

AppPermission:
b075cfdfecee5186895c9eb94dad07e6

AppGroupPermission:

f19d4eb425ff047e3501a85993319c8e

cgeier 187 Junior Poster

To get a list of menus that exist in the MenuStrip (ex: MenuStrip1):

I use a class called "MenuInfo" to store the data.

MenuInfo.vb

Public Class MenuInfo
    Public Property name As String
    Public Property depth As Integer
    Public Property parent As String

    'constructor
    Public Sub New()
    End Sub

    'constructor
    Public Sub New(ByVal name As String, ByVal depth As Integer, ByVal parent As String)
        Me.name = name
        Me.depth = depth
        Me.parent = parent
    End Sub
End Class

The following recursive method will get all of the sub-menus (DropDownItems). The initial call to "getToolStripChildMenuNames" is in "getToolStripMenuNames".

getToolStripChildMenuNames:

    Private Sub getToolStripChildMenuNames(ByVal myToolStripMenuItem As ToolStripMenuItem, ByRef menuList As List(Of MenuInfo), ByRef depth As Integer)

        'increment depth
        depth += 1

        For Each child As ToolStripMenuItem In myToolStripMenuItem.DropDownItems

            'add menu name to list
            menuList.Add(New MenuInfo(child.Name, depth, myToolStripMenuItem.Name))

            'recursivesly call function to get all children
            getToolStripChildMenuNames(child, menuList, depth)
        Next

        'decrement depth
        depth -= 1

    End Sub

The following method will get the menu names on the MenuStrip and call "getToolStripChildMenuNames" to get the sub-menus:

getToolStripMenuNames:

    Private Sub getToolStripMenuNames(ByVal myMenuStrip As MenuStrip)

        Dim output As String = String.Empty

        'hold menu info
        Dim menuList As New List(Of MenuInfo)

        'keeps track of depth
        Dim depth As Integer = 0

        'get top level menus - File, Tools, etc...
        For Each item As ToolStripMenuItem In myMenuStrip.Items

            'add menu to list
            menuList.Add(New MenuInfo(item.Name, depth, ""))

            'get all child menu items - DropDownMenus
            getToolStripChildMenuNames(item, menuList, depth)
        Next

        output = "List of Menus:" + System.Environment.NewLine + System.Environment.NewLine …
cgeier 187 Junior Poster

The code above in AppPermissionTbl is how to do it for SQL Server and SQL Server Express.