Wednesday, October 26, 2016

C# Error Logger

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ErrorLogger
{
    // ===========================================================
    public class AppLog
    {
        private string _OutputFolder;
        private string _fileName;
        //
        public AppLog(string OutputFolder,string prefix="OUTPUT")
        {
            string fileName;
            fileName = prefix + "_" + this.getUserName() + "_" + this.getJulianDate() + "_" + this.getTimeStamp() + "_" + this.getRandomNumber() + ".txt";
            _fileName=Path.Combine(OutputFolder,fileName);
            //
            _OutputFolder = OutputFolder;
        }


      /// <summary>
      /// will log error info: DateStamp,UserName and error message
      /// </summary>
      /// <param name="dateStamp"></param>
      /// <param name="UserName"></param>
      /// <param name="ErrorMsg"></param>
      /// <returns></returns>
      ///
        // ===============================================
        public string getUserName()
        {
            return Environment.UserName;
        }
        // ================================================
        public string getJulianDate()
        {
            string value;
            value = DateTime.Now.ToString("yyyyMMdd");
            return value;
        }
        // ===============================================
        public string getTimeStamp()
        {
            string rvalue;
            rvalue=DateTime.Now.ToString("HHmmss");
            return rvalue;
        }
        // ===============================================
        public string getRandomNumber()
        {
            int seed = (int)DateTime.Now.Ticks;
            Random rndNumber = new Random(seed);
            int value = rndNumber.Next(0,10000);
            string rvalue = String.Format(value.ToString(),"{0:00000}");
            return rvalue;
        }
        // ========================================================
        public bool LogEvent(DateTime dateStamp, string UserName, string ErrorMsg)
        {
            bool returnValue;
            try
            {
                string output = UserName + "," + dateStamp.ToString() + "," + ErrorMsg;
                using (StreamWriter sw = new StreamWriter(new FileStream(path: _fileName, mode: FileMode.Append, access: FileAccess.Write)))
                {
                    sw.WriteLine(output);
                }
                returnValue = true;
            }
            catch (Exception )
            {
                returnValue = false;
            }
            return returnValue;
        }
        /// <summary>
        /// wjd 4-26-2016 added overload method to capture non-fatal errors will reading the file via OpenXML
        /// </summary>
        /// <param name="dateStamp"></param>
        /// <param name="UserName"></param>
        /// <param name="ErrorMsg"></param>
        /// <param name="ValidationErrors"></param>
        /// <returns></returns>
        ///
        // ============================================================================================
        public bool LogEvent(DateTime dateStamp, string UserName, IEnumerable<string> ValidationErrors)
        {
            bool returnValue;
            try
            {
                string output = UserName + "," + dateStamp.ToString();
                using (StreamWriter sw = new StreamWriter(new FileStream(path: _fileName, mode: FileMode.Append, access: FileAccess.Write)))
                {
                    sw.WriteLine(output);
                    foreach (string validationError in ValidationErrors)
                    {
                        sw.WriteLine( validationError);
                    }
                }
                returnValue = true;
            }
            catch (Exception ex)
            {
                returnValue = false;
            }
            return returnValue;
        }
    }
}

Thursday, October 20, 2016

Common WinAPI functionality

(1) Declare WinAPI
(2) Write public functions


Option Compare Database
Option Explicit





Private Declare Function ShellExecute Lib "shell32.dll" Alias _
   "ShellExecuteA" (ByVal hwnd As Long, ByVal lpOperation _
   As String, ByVal lpFile As String, ByVal lpParameters _
   As String, ByVal lpDirectory As String, ByVal nShowCmd _
   As Long) As Long
'************** Code Start **************
'This code was originally written by Terry Kreft.
'It is not to be altered or distributed,
'except as part of an application.
'You are free to use it in any application,
'provided the copyright notice is left unchanged.
'
'Code courtesy of
'Terry Kreft

Private Type BROWSEINFO
  hOwner As Long
  pidlRoot As Long
  pszDisplayName As String
  lpszTitle As String
  ulFlags As Long
  lpfn As Long
  lParam As Long
  iImage As Long
End Type

Private Declare Function SHGetPathFromIDList Lib "shell32.dll" Alias _
            "SHGetPathFromIDListA" (ByVal pidl As Long, _
            ByVal pszPath As String) As Long
           
Private Declare Function SHBrowseForFolder Lib "shell32.dll" Alias _
            "SHBrowseForFolderA" (lpBrowseInfo As BROWSEINFO) _
            As Long


Private Const BIF_RETURNONLYFSDIRS = &H1

Public Declare Function GetTickCount Lib "kernel32" () As Long

Private Declare Function GetUserName Lib "advapi32.dll" Alias _
"GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long

Private Declare Function GetComputerName _
Lib "kernel32" Alias "GetComputerNameA" _
(ByVal lpBuffer As String, nSize As Long) As Long

Private Declare Function GetOpenFileName Lib "comdlg32.dll" Alias _
"GetOpenFileNameA" (pOpenfilename As OPENFILENAME) As Long

Private Type OPENFILENAME
    lStructSize As Long
    hwndOwner As Long
    hInstance As Long
    lpstrFilter As String
    lpstrCustomFilter As String
    nMaxCustFilter As Long
    nFilterIndex As Long
    lpstrFile As String
    nMaxFile As Long
    lpstrFileTitle As String
    nMaxFileTitle As Long
    lpstrInitialDir As String
    lpstrTitle As String
    Flags As Long
    nFileOffset As Integer
    nFileExtension As Integer
    lpstrDefExt As String
    lCustData As Long
    lpfnHook As Long
    lpTemplateName As String
End Type


Private Declare Function GetSaveFileNameA Lib "comdlg32.dll" (pOpenfilename As OPENFILENAME) As Long
Private Declare Function GetActiveWindow Lib "user32" () As Long

Public Function SaveAsCommonDialog(iOfficeVersion As OfficeProduct, _
    strForm As Form, _
    Optional sTitle = "Save File", _
    Optional sDefaultDir As String, _
    Optional filename As String = "") As String
   
Const clBufferLen As Long = 255
Dim OFName As OPENFILENAME, sBuffer As String * clBufferLen
Dim sFilter As String
On Error GoTo ExitFunction

OFName.lStructSize = Len(OFName)
OFName.hwndOwner = strForm.hwnd ' GetActiveWindow  'or Me.hwnd in VB
'OFName.hInstance = 0                'or App.hInstance in VB

'If Len(sFilter) Then
'    OFName.lpstrFilter = sFilter
'Else
'    OFName.lpstrFilter = "Text Files (*.txt)" & Chr$(0) & "*.txt" & Chr$(0) & "All Files (*.*)" & Chr$(0) & "*.*" & Chr$(0)
'End If
   
Select Case iOfficeVersion
    Case OfficeProduct.Excel2007Only
     
        sFilter = "Excel 2007 Workbooks (*.xlsx)" & Chr(0) & "*.xlsx" & Chr(0) & _
            "Excel 2003 Workbooks (*.xls)" & Chr(0) & "*.xls" & Chr(0)
       
    Case OfficeProduct.Access2007Only
        sFilter = "Access Databases 2007(*.acdb*)" & Chr(0) & "*.acdb" & Chr(0) & _
            "Access Databases 2003 (*.MDB)" & Chr(0) & "*.MDB & Chr(0)"
   
    Case Else
        sFilter = "All Files (*.*)" & Chr(0) & "*.*"
End Select
   
   
OFName.lpstrFilter = sFilter
OFName.nFilterIndex = 1
   
' set file to initialDir and Filename (Note - need to retain length of sBuffer)
If filename <> "" Then
    Dim initialFilePath As String
    If Right(sDefaultDir, 1) = "\" Then
        initialFilePath = sDefaultDir & filename
    Else
        initialFilePath = sDefaultDir & "\" & filename
    End If
    sBuffer = initialFilePath & (Right(sBuffer, Len(sBuffer) - Len(initialFilePath)))
End If

OFName.lpstrFile = sBuffer
OFName.nMaxFile = clBufferLen       'Set max number of characters
OFName.lpstrFileTitle = sBuffer
OFName.nMaxFileTitle = clBufferLen  'Set max number of characters
   
'Set the initial directory
If Len(sDefaultDir) Then
    OFName.lpstrInitialDir = sDefaultDir
Else
    OFName.lpstrInitialDir = CurDir$
End If

OFName.lpstrTitle = sTitle
OFName.Flags = 0

'debug.Print "sBuffer: " & sBuffer

'Show dialog
If GetSaveFileNameA(OFName) Then
    SaveAsCommonDialog = Left$(OFName.lpstrFile, InStr(1, OFName.lpstrFile, Chr(0)) - 1)
Else
    SaveAsCommonDialog = ""
End If
ExitFunction:
    On Error GoTo 0
End Function


Function getWindowsUserId() As String
' Returns the network login name.
Dim lngLen As Long, lngX As Long
Dim strUserName As String
strUserName = String$(254, 0)
lngLen = 255
lngX = GetUserName(strUserName, lngLen)
If lngX <> 0 Then
    getWindowsUserId = Left$(strUserName, lngLen - 1)
Else
    getWindowsUserId = "Unknown"
End If

End Function


Public Function GetWorkstationId() As String
' Retrieve the name of the computer.
Const acbcMaxComputerName = 15
Dim strBuffer As String
Dim lngLen As Long
strBuffer = Space(acbcMaxComputerName + 1)
lngLen = Len(strBuffer)
If CBool(GetComputerName(strBuffer, lngLen)) Then
    GetWorkstationId = Left$(strBuffer, lngLen)
Else
    GetWorkstationId = ""
End If
End Function


Public Function BrowseFolder(szDialogTitle As String) As String
  Dim X As Long, bi As BROWSEINFO, dwIList As Long
  Dim szPath As String, wPos As Integer
 
    With bi
        .hOwner = hWndAccessApp
        .lpszTitle = szDialogTitle
        .ulFlags = BIF_RETURNONLYFSDIRS
    End With
   
    dwIList = SHBrowseForFolder(bi)
    szPath = Space$(512)
    X = SHGetPathFromIDList(ByVal dwIList, ByVal szPath)
   
    If X Then
        wPos = InStr(szPath, Chr(0))
        BrowseFolder = Left$(szPath, wPos - 1)
    Else
        BrowseFolder = vbNullString
    End If
End Function


Function APIGetOpenFileNameCD(iOfficeVersion As OfficeProduct, _
    strForm As Form, Optional _
    InitialFileName As String) As String
Dim OpenFile As OPENFILENAME
Dim lReturn As Long
Dim sFilter As String
   
   
OpenFile.lStructSize = Len(OpenFile)
OpenFile.hwndOwner = strForm.hwnd
   
Select Case iOfficeVersion
    Case OfficeProduct.Excel2007Only
     
        sFilter = "Excel 2007 Workbooks (*.xlsx)" & Chr(0) & "*.xlsx" & Chr(0) & _
            "Excel 2003 Workbooks (*.xls)" & Chr(0) & "*.xls" & Chr(0)
       
    Case OfficeProduct.Access2007Only
        sFilter = "Access Databases 2007(*.acdb*)" & Chr(0) & "*.acdb" & Chr(0) & _
            "Access Databases 2003 (*.MDB)" & Chr(0) & "*.MDB & Chr(0)"
   
    Case Else
        sFilter = "All Files (*.*)" & Chr(0) & "*.*"
End Select
    'sFilter = "All Files (*.*)" & Chr(0) & "*.*" & Chr(0) & _
      "JPEG Files (*.JPG)" & Chr(0) & "*.JPG" & Chr(0)
OpenFile.lpstrFilter = sFilter
OpenFile.nFilterIndex = 1
OpenFile.lpstrFile = String(257, 0)
OpenFile.nMaxFile = Len(OpenFile.lpstrFile) - 1
OpenFile.lpstrFileTitle = OpenFile.lpstrFile
OpenFile.nMaxFileTitle = OpenFile.nMaxFile
If Len(InitialFileName) > 0 Then
    OpenFile.lpstrInitialDir = InitialFileName
Else
    OpenFile.lpstrInitialDir = "C:\"
End If
   

OpenFile.lpstrTitle = "Select a file name"
OpenFile.Flags = 0
lReturn = GetOpenFileName(OpenFile)
If lReturn = 0 Then
    'MsgBox "A file was not selected!", vbInformation, _
      "Select a file using the Common Dialog DLL"
    Exit Function
Else
    APIGetOpenFileNameCD = Trim(Left(OpenFile.lpstrFile, InStr(1, OpenFile.lpstrFile, vbNullChar) - 1))
End If
End Function


Public Function OpenPDFFile(ByVal strFileName) As Boolean
Dim lngErr As Long
'Dim objShell As Object

'objShell.ShellExecute
Const SW_SHOWNORMAL = 1
lngErr = ShellExecute(0, "OPEN", strFileName, vbNullString, vbNullString, SW_SHOWNORMAL)

OpenPDFFile = lngErr > 32
End Function

Wednesday, October 12, 2016

Form Picker (Access VBA)









Option Compare Database

Private m_bOk As Boolean
Private m_frmParent As Form
Private Sub cmdCancel_Click()
DoCmd.Close acForm, Me.Name
End Sub


Private Sub cmdOk_Click()
Dim strSourceControlName As String
Dim strDestinationControlName As String
Dim lngFindPos As Long

'lngFindPos = InStr(1, Nz(Me.OpenArgs), "-")
'If lngFindPos Then
'    strSourceControlName = Mid(Me.OpenArgs, 1, lngFindPos - 1)
'    strDestinationControlName = Mid(Me.OpenArgs, lngFindPos + 1)
'Else
'    strDestinationControlName = Nz(Me.OpenArgs)
'End If

strSourceControlName = Nz(Me.OpenArgs)
m_bOk = True
'Unload Me

'With Forms(m_frmParent.Name).Controls(strSourceControlName)
 '   .RowSource = vbNullString
 '   .RowSource = Me.TargetList()
'End With
Call setLVRowSourceProperty(Forms(m_frmParent.Name).Controls(strSourceControlName), _
    Me.TargetList())
DoCmd.Close acForm, Me.Name
End Sub

Private Sub cmdToDestination_Click()

If Not (Me.lbSource.ListIndex = -1) Then
    'Me.lbSource.AddItem strNewEntry, Me.lbSource.ListIndex + 1
    Me.lbDestination.AddItem lbSource.Value
    Me.lbSource.RemoveItem Me.lbSource.ListIndex
End If
End Sub

Private Sub cmdToSource_Click()
If Not (Me.lbDestination.ListIndex = -1) Then
    'Me.lbSource.AddItem strNewEntry, Me.lbSource.ListIndex + 1
    Me.lbSource.AddItem lbDestination.Value
    Me.lbDestination.RemoveItem Me.lbDestination.ListIndex
End If
End Sub

Public Property Let TargetList(ByVal strValue As String)
If Len(strValue) Then
    Me.lbDestination.RowSource = strValue
End If
End Property

Public Property Get TargetList() As String
    TargetList = Me.lbDestination.RowSource
End Property

Public Property Get bOK() As Boolean
bOK = m_bOk
End Property

Private Sub Command8_Click()
Dim i As Integer
With Me.lbSource
    .RowSourceType = "Value List"
    .RowSource = vbNullString
    .ColumnCount = 1
    .BoundColumn = 1
   ' .AddItem "Yankees;East;AL"
   ' .AddItem "Boston RedSox;East;AL"
   ' .AddItem "Floriday Marlins;East;AL"
    '.AddItem "Seattle Mariners;West;AL"
   ' .AddItem "NY Mets;East;NL"
    For i = 1 To 12
        .AddItem MonthName(i)
    Next
End With
End Sub

Private Sub Form_Load()
Const ssource As String = "Form_Load"
On Error GoTo ErrorHandler
DoCmd.Hourglass True
Dim strSQL As String, strTable As String
Dim rs As ADODB.Recordset
Dim objConn As ADODB.Connection
Dim i As Integer
Dim varItem As Variant
Dim strCriteria, aCriteria() As String
Dim strValue As String

Dim strControlName As String
Dim strSourceControlName As String
Dim strDestinationControlName As String
Dim lngFindPos As Long
Dim lbSource As Control 'ListBox

Set m_frmParent = Screen.ActiveForm
'lngFindPos = InStr(1, Nz(Me.OpenArgs), "-")
'If lngFindPos Then
'    strSourceControlName = Mid(Me.OpenArgs, 1, lngFindPos - 1)
'    strDestinationControlName = Mid(Me.OpenArgs, lngFindPos + 1)
'Else
'    strDestinationControlName = Nz(Me.OpenArgs)
'End If

strSourceControlName = Nz(Me.OpenArgs)
With Me
    .lbDestination.RowSourceType = "Value List"
    .lbDestination.ColumnCount = 1
    .lbSource.RowSourceType = "Value List"
    .lbSource.ColumnCount = 1
   
    'build lb's
    'Call Command8_Click
    'do not include user's selections
    '.lbDestination.RowSource = Forms(m_frmParent.Name).Controls(strSourceControlName).RowSource
    .lbDestination.RowSource = getLVRowSourceProperty(Forms(m_frmParent.Name).Controls(strSourceControlName))
End With

Set lbSource = Forms(m_frmParent.Name).Controls(strSourceControlName)
With Me.lbSource
   
    .RowSource = ""
    .RowSourceType = "Value List"
    .ColumnHeads = False
    .ColumnCount = 1
    .ColumnWidths = "2 in"
  
   
    'For Each varItem In lb.ItemsSelected
    '    strValue = strValue & lb.Column(1, varItem) & ","
    'Next
   
    '11/29 took out
    'strValue = lbSource.RowSource
    strValue = Me.lbDestination.RowSource
   
    aCriteria() = Split(strValue, ";")
    For i = LBound(aCriteria) To UBound(aCriteria)
        strCriteria = strCriteria & " " & " Note LIKE " & "'%" & aCriteria(i) & "%' OR"
    Next
    'avoid duplicating user's selections
    If Len(strCriteria) Then
        'remove trailing OR
        strCriteria = Left(strCriteria, Len(strCriteria) - 3)
        strSQL = "SELECT Note FROM tblLanguage WHERE " & _
        " NOT (" & strCriteria & " )" & _
        " ORDER BY Note "
    Else
        strSQL = "SELECT Note" & _
            " FROM tblLanguage " & _
            " ORDER BY Note"
    End If
   
    'Debug.Print strSQL
   
    Set rs = New ADODB.Recordset
    With rs
        .LockType = adLockOptimistic
        .CursorType = adOpenDynamic
    End With
   
    Set objConn = New ADODB.Connection
    Set objConn = CurrentProject.Connection
   
    rs.Open strSQL, objConn, Options:=adCmdText
    If Not (rs.EOF() And rs.BOF) Then
        strSQL = ""
        Do While Not rs.EOF
            For i = 0 To rs.Fields.Count - 1
                strSQL = strSQL & Nz(rs.Fields(i)) & ";"
            Next
            strSQL = Mid(strSQL, 1, Len(strSQL) - 1)
            .AddItem strSQL
            strSQL = ""
            rs.MoveNext
        Loop
    End If
  
End With

ExitProc:
    On Error Resume Next
    Set objConn = Nothing
    Set rs = Nothing
    DoCmd.Hourglass False
    Exit Sub

ErrorHandler:
   
    If bCentralErrorHandler("frmPicker", ssource) Then
        Stop
        Resume
    Else
        Resume ExitProc
    End If

End Sub

Private Sub Form_Open(Cancel As Integer)
If IsNull(Me.OpenArgs) Then
    Cancel = True
    Exit Sub
End If

End Sub

Private Sub lbDestination_DblClick(Cancel As Integer)
Call cmdToSource_Click
End Sub


Private Sub lbSource_DblClick(Cancel As Integer)
Call cmdToDestination_Click
End Sub


Bulk Send Wizard (Access VBA)


























Option Compare Database
Option Explicit
Private Const msMODULE As String = "BulkSendWizard"
#Const DEBUG_MODE = 1
#Const PROD_MODE = 0
#Const APP_MODE = DEBUG_MODE
Dim CurrentStatus As Integer

Public Enum WizardScreen
    PickaFolder = 0
    PickAFileName
    PickEmailTo
    PickWhethereToZip
End Enum
Private m_bOk As Boolean

Public Property Get bOK() As Boolean
bOK = m_bOk
End Property

Private Sub cmdBrowse_Click()
Const ssource As String = "cmdNext_Click"
Dim strOutputFolder As String
On Error GoTo ErrorHandler

'strOutputFolder = BrowseFolder("Output folder for client statements")
strOutputFolder = getFolderDestination(Nz(Me.txtOutputFolder))
If Len(strOutputFolder) Then
    Me.txtOutputFolder.Value = strOutputFolder
    Call VerifyDupeFileNames
End If
ExitProc:
   On Error Resume Next
   Exit Sub
   
ErrorHandler:
    If bCentralErrorHandler(msMODULE, ssource, , bEntryPoint:=True) Then
        Stop
        Resume
    Else
        Resume ExitProc
    End If
End Sub

Private Sub cmdNext_Click()
Const ssource As String = "cmdNext_Click"
On Error GoTo ErrorHandler

Dim CTab As Integer
   
    If ValidateData(CurrentStatus) = 1 Then
    'advance for next tab and setup up stuff
        CurrentStatus = CurrentStatus + 1
        ValidateButton (CurrentStatus)
            CTab = Me.tabWizard.Value + 1
            If CTab = Me.tabWizard.Pages.Count Then
                Else
           
                Me.tabWizard.Pages(CTab).SetFocus
            End If
    Else
        MsgBox ("Please complete the information"), vbInformation, "Incomplete information"
    End If

ExitProc:
   On Error Resume Next
   Exit Sub
   
ErrorHandler:
    If bCentralErrorHandler(msMODULE, ssource, , bEntryPoint:=True) Then
        Stop
        Resume
    Else
        Resume ExitProc
    End If
End Sub

Private Sub cmdPrevious_Click()
Const ssource As String = "cmdClientAdd_Click"
On Error GoTo ErrorHandler
Dim CTab As Integer

CurrentStatus = CurrentStatus - 1
ValidateButton (CurrentStatus)
CTab = Me.tabWizard.Value - 1
If CTab < 0 Then
Else
    Me.tabWizard.Pages(CTab).SetFocus
End If

ExitProc:
   On Error Resume Next
   Exit Sub
   
ErrorHandler:
    If bCentralErrorHandler(msMODULE, ssource, , bEntryPoint:=True) Then
        Stop
        Resume
    Else
        Resume ExitProc
    End If
End Sub


Private Sub cmdCancel_Click()
On Error Resume Next
'DoCmd.Close
Me.Visible = False
End Sub



Private Sub Form_Open(Cancel As Integer)
Dim COB_Date As Date
Dim intRegion As Integer
Dim strSQL As String

On Error Resume Next
Me.chkZipFile.Value = False
Me.chkZipFile.Enabled = False
Me.txtOutputFolder = getAppPath() & "\output"
CurrentStatus = 0
ValidateButton (CurrentStatus)

COB_Date = CDate(Forms!SentDailyWork!tvCOBDates.SelectedItem.Text)
Me.lblErrorCount.Caption = vbNullString
intRegion = getClientLocationId()
'Call loadEmailInfo(Me.lvEmailInfo, COB_Date, intRegion)
strSQL = "SELECT Client.ClientID, Client.ClientName, Client.Email as [To:], " & _
    "DailyWork.COB_Date, Client.ClientLocationID " & _
    "FROM Client INNER JOIN DailyWork ON Client.ClientID = DailyWork.ClientID " & _
    " WHERE DailyWork.COB_Date =#" & COB_Date & "#" & _
    " AND DailyWork.DailyWorkStatusID=2 " & _
    " And Client.ClientLocationID= " & intRegion & _
    " ORDER BY Client.ClientName "
With Me.lbEmailInfo
    .RowSource = strSQL
    .Requery
End With

Call loadListView(COB_Date)
End Sub

Private Sub ValidateButton(StatusId As Integer)
Const ssource As String = "cmdClientAdd_Click"
On Error GoTo ErrorHandler
   
    Select Case StatusId
       
        Case WizardScreen.PickaFolder
            CmdNext.SetFocus
            CmdPrevious.Visible = False
   
        Case WizardScreen.PickAFileName, WizardScreen.PickEmailTo
       
            CmdPrevious.Visible = True
            CmdNext.Caption = "Next>"
       
        Case WizardScreen.PickEmailTo
            CmdNext.Caption = "&Finish"
       
        Case WizardScreen.PickWhethereToZip
            CmdNext.Caption = "&Finish"
           
        Case 4
       
            'MsgBox "will finish now"
            m_bOk = True
            'DoCmd.Close acForm, Me.Name
            Me.Visible = False
            Exit Sub
           
    End Select
   

ExitProc:
   On Error Resume Next
   Exit Sub
   
ErrorHandler:
    If bCentralErrorHandler(msMODULE, ssource, , bEntryPoint:=True) Then
        Stop
        Resume
    Else
        Resume ExitProc
    End If
End Sub

Private Function ValidateData(StatusId As Integer) As Integer
Const ssource As String = "ValidateData"
On Error GoTo ErrorHandler

    Select Case StatusId
            Case 0  ' get Name ans Address
                'If IsNull(CustomerName) Or CustomerName = "" Then
                '    ValidateData = 0
                'ElseIf IsNull(CustomerAddress) Or CustomerAddress = "" Then
                '    ValidateData = 0
                'Else
                ValidateData = 1
                'End If

            Case 1
                'If IsNull(Country) Or Country = "" Then
                '    ValidateData = 0
                'ElseIf IsNull(PostalCode) Or PostalCode = "" Then
                '    ValidateData = 0
               ' Else
                ValidateData = 1
               ' End If

            Case 2
                'If IsNull(Phone) Or Phone = "" Then
                '    ValidateData = 0
               ' ElseIf IsNull(Fax) Or Fax = "" Then
               '     ValidateData = 0
               ' Else
                ValidateData = 1
               ' End If
   
   
            Case WizardScreen.PickWhethereToZip
                'will do the finally validation
               
                If IsNull(Me.txtOutputFolder) Or Len(Me.txtOutputFolder) = 0 Then
                   
                    MsgBox "Need a output folder location", vbInformation, "Validate Controls"
                    ValidateData = 0
                ElseIf Len(Me.lblErrorCount.Caption) > 0 Then
                    Call MsgBox(Me.lblErrorCount.Caption & "." & vbNewLine & _
                    "Please rename those files", vbCritical, "Validate Controls")
                    ValidateData = 0
                   
                Else
                    ValidateData = 1
                End If
              

            Case Else
                ValidateData = 1
   
    End Select
   

ExitProc:
    On Error Resume Next
    Exit Function

ErrorHandler:
   
    If bCentralErrorHandler(msMODULE, ssource) Then
        Stop
        Resume
    Else
        Resume ExitProc
    End If
   
End Function

Function loadListView(COB_Date As Date) As Boolean
Const ssource As String = "loadSecurityUserQueue"
Dim strSQL As String
Dim objLVSentDailyWork As Object, LV As Object
Dim objli As ListItem, objLINew As ListItem
Dim i As Integer
Dim strFileName As String, strFullPathName As String
Dim strOutputPath As String

On Error GoTo ErrorHandler
Set objLVSentDailyWork = Forms!SentDailyWork!lvHistory
Set LV = Me.lvFileName
strOutputPath = AddBS(Me.txtOutputFolder.Value)

With LV

    'clear out old data
    .ListItems.Clear
    .ColumnHeaders.Clear

    'define headers
    .ColumnHeaders.Add , , "Client ID", 0
    .ColumnHeaders.Add , , "COB_Date", 1100, lvwColumnRight
    .ColumnHeaders.Add , , "Client Name", 0
    .ColumnHeaders.Add , , "File Name", 4320, lvwColumnLeft
    .ColumnHeaders.Add , , "Dupe", 720, lvwColumnCenter

  
    For Each objli In objLVSentDailyWork.ListItems
           Set objLINew = LV.ListItems.Add(, , Nz(objli.Text))
           With objLINew
                .SubItems(1) = Format(COB_Date, MASK_DATE)
                .SubItems(2) = objli.SubItems(4)
                strFileName = Format(COB_Date, "yyyymmdd") & _
                Space(1) & objli.SubItems(4) & " Statement" & ".pdf"
                .SubItems(3) = strFileName
                '.SubItems(4) = ""
            End With
           
     Next
     Call VerifyDupeFileNames
End With
   
loadListView = True
ExitProc:
    On Error Resume Next
    Set objli = Nothing
   
    Exit Function

ErrorHandler:
   
    If bCentralErrorHandler(msMODULE, ssource) Then
        Stop
        Resume
    Else
        Resume ExitProc
    End If
   
End Function

Function VerifyDupeFileNames() As Boolean
Const ssource As String = "VerifyDupeFileNames"
Dim strSQL As String
Dim LV As Object
Dim objli As ListItem
Dim i As Integer
Dim strFileName As String, strFullPathName As String
Dim strOutputPath As String
Dim objfsh As Scripting.FileSystemObject

On Error GoTo ErrorHandler

Set LV = Me.lvFileName
strOutputPath = AddBS(Me.txtOutputFolder.Value)
Set objfsh = CreateObject("Scripting.FileSystemObject")
For Each objli In LV.ListItems
   
    With objli
         strFileName = .SubItems(3)
          strFullPathName = strOutputPath & strFileName
         
         .SubItems(4) = Format$(objfsh.FileExists(strFullPathName), "Yes/No")
    End With
Next
    
Call CalcErrors
VerifyDupeFileNames = True
ExitProc:
    On Error Resume Next
    Set objli = Nothing
    Set LV = Nothing
   
   
    Exit Function

ErrorHandler:
   
    If bCentralErrorHandler(msMODULE, ssource) Then
        Stop
        Resume
    Else
        Resume ExitProc
    End If
   
End Function

Function CalcErrors() As Boolean
Const ssource As String = "CalcErrors"
Dim strSQL As String
Dim LV As Object
Dim objli As ListItem
Dim i As Integer
Dim iErrorCount As Integer

On Error GoTo ErrorHandler

Set LV = Me.lvFileName

For Each objli In LV.ListItems
    With objli
        If Mid$(.SubItems(4), 1, 1) = "Y" Then
            iErrorCount = iErrorCount + 1
        End If
    End With
Next
    
If iErrorCount Then
    Me.lblErrorCount.Caption = Format(iErrorCount, "#,##0") & " file conflict error(s)"
Else
    Me.lblErrorCount.Caption = vbNullString
End If

CalcErrors = True
ExitProc:
    On Error Resume Next
    Set objli = Nothing
    Set LV = Nothing
    Exit Function

ErrorHandler:
   
    If bCentralErrorHandler(msMODULE, ssource) Then
        Stop
        Resume
    Else
        Resume ExitProc
    End If
   
End Function
   
Function loadEmailInfo(ByRef LV As CustomControl, _
    ByVal asofDate As Date, _
    ByVal Region As Integer) As Boolean
   
Const ssource As String = "loadEmailInfo"
On Error GoTo ErrorHandler
Dim strSQL As String
Dim rs As ADODB.Recordset
Dim objConn As ADODB.Connection
Dim objli As ListItem
Dim i As Integer

Dim objCatalog As ADOX.Catalog
Dim objCmd As ADODB.Command
Dim strQueryName As String

   
strQueryName = "qryClientgetEmailInfo"

Set objCatalog = New ADOX.Catalog
Set objCatalog.ActiveConnection = CurrentProject.Connection

Set objCmd = New ADODB.Command
Set objCmd = objCatalog.Procedures(strQueryName).Command
objCmd.Parameters(0).Value = asofDate
objCmd.Parameters(1).Value = Region

    LV.ListItems.Clear
    Set rs = objCmd.Execute
   
    LV.ColumnHeaders.Clear
    LV.ColumnHeaders.Add , , "ID", 0
    LV.ColumnHeaders.Add , , "Client Name", 2880, lvwColumnLeft
    LV.ColumnHeaders.Add , , "To:", 2880
   
    If Not (rs.EOF() And rs.BOF) Then
        Do While Not rs.EOF
           Set objli = LV.ListItems.Add(, , Nz(rs.Fields("ClientID").Value))
           With objli
                .SubItems(1) = Nz(rs.Fields("ClientName").Value)
                .SubItems(2) = Nz(rs.Fields("Email").Value)
            End With
            rs.MoveNext
        Loop
        loadEmailInfo = (LV.ListItems.Count > 0)
    End If
   
ExitProc:
    On Error Resume Next
    Set rs = Nothing
    Set objConn = Nothing
    Exit Function

ErrorHandler:
   
    If bCentralErrorHandler(msMODULE, ssource) Then
        Stop
        Resume
    Else
        Resume ExitProc
    End If

End Function

Save As File Dialog in Access VBA

 Private Sub cmdBrowse_Click()
Const ssource As String = "cmdNext_Click"
Dim strOutputFolder As String
On Error GoTo ErrorHandler

'strOutputFolder = BrowseFolder("Output folder for client statements")
strOutputFolder = getFolderDestination(Nz(Me.txtOutputFolder))
If Len(strOutputFolder) Then
    Me.txtOutputFolder.Value = strOutputFolder
  
End If
ExitProc:
   On Error Resume Next
   Exit Sub
  
ErrorHandler:
    If bCentralErrorHandler(msMODULE, ssource, , bEntryPoint:=True) Then
        Stop
        Resume
    Else
        Resume ExitProc
    End If
End Sub

Function getFolderDestination(Optional strInitialFileName As String) As String

Const ssource As String = "getSaveAs2"
Dim fDialog As Office.FileDialog
On Error GoTo ErrorHandler
' Requires reference to Microsoft Office 11.0 Object Library.

' Set up the File Dialog.
'Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
Set fDialog = Application.FileDialog(msoFileDialogFolderPicker)

With fDialog
   
    If Len(strInitialFileName) Then
        .InitialFileName = strInitialFileName
    End If
    ' Set the title of the dialog box.
    '.Title = "Please select one or more files"

   
      ' Show the dialog box. If the .Show method returns True, the
      ' user picked at least one file. If the .Show method returns
      ' False, the user clicked Cancel.
    If .Show Then
        getFolderDestination = .SelectedItems(1)
    End If
End With


ExitProc:
    On Error Resume Next
    Set fDialog = Nothing
    Exit Function

ErrorHandler:
   
    If bCentralErrorHandler(msMODULE, "getSaveAs2") Then
        Stop
        Resume
    Else
        Resume ExitProc
    End If


End Function

Function getFileOpen2(iOfficeVersion As OfficeProduct, _
    Optional bAllowMultiSelect As Boolean = False, _
    Optional strInitialFileName As String, _
    Optional ByVal strTitle As String) As String
Const ssource As String = "getFileOpen2"
Dim fDialog As Office.FileDialog
On Error GoTo ErrorHandler
' Requires reference to Microsoft Office 11.0 Object Library.

' Set up the File Dialog.
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
'Set fDialog = Application.FileDialog(msoFileDialogSaveAs)

With fDialog
    .AllowMultiSelect = bAllowMultiSelect
         
    'If Len(strInitialFileName) Then
     '   .InitialFileName = strInitialFileName
    'End If
    ' Set the title of the dialog box.
    If Len(strTitle) > 0 Then
        .Title = strTitle
    Else
        .Title = "Please select one or more files"
    End If
   
    ' Clear out the current filters, and add our own.
    .Filters.Clear
    Select Case iOfficeVersion
        Case OfficeProduct.Excel2007Only
            .Filters.Add "Excel 2007 Workbooks", "*.XLSX"
            .Filters.Add "All Files", "*.*"

        Case OfficeProduct.Access2007Only
            .Filters.Add "Access Databases", "*.MDB"
            .Filters.Add "Access Projects", "*.ADP"
            .Filters.Add "All Files", "*.*"
           
        Case OfficeProduct.XML
           ' .Filters.Add "All Files", "*.*"
            .Filters.Add "XML Files", "*.XML"
           
       
        Case Else
            .Filters.Add "All Files", "*.*"
    End Select
   
      ' Show the dialog box. If the .Show method returns True, the
      ' user picked at least one file. If the .Show method returns
      ' False, the user clicked Cancel.
    If .Show Then
        getFileOpen2 = .SelectedItems(1)
    End If
End With


ExitProc:
    On Error Resume Next
    Set fDialog = Nothing
    Exit Function

ErrorHandler:
   
    If bCentralErrorHandler(msMODULE, "getSaveAs2") Then
        Stop
        Resume
    Else
        Resume ExitProc
    End If


End Function


Saturday, October 8, 2016

How to correctly release object variables in ADO

Connection object

Cnxn.Open sConnString     '"Provider=OraOLEDB.Oracle;Data Source=(DESCRIPTION=(CID=JCGPRD01)(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=JCG04AW.vsp.sas.com)(PORT=6660)))(CONNECT_DATA=(SID=JCGPRD01)(SERVER=DEDICATED)));User Id=jcg0vbapp;Password=oyv3re8d4;"
          '
100       If Cnxn.State <> adStateOpen Then

110          sMsg = "**** ERROR Could Not Open Connection to File! ****" & vbCrLf & vbCrLf & _
                       "in Module 'modUtils' - Function 'Fetch_TD_Data'" & vbCrLf & "Line # " & 90 & vbCrLf & _
                       vbCrLf & " SQL: '" & strSQL & "'"
120          vLogMsg = sMsg
130          MsgLog

140          GoTo Fetch_TD_Data_Exit
150       End If


 Recordset object
Set rs = New ADODB.Recordset
190       strSQL = cnstLOCK_ROWS & strSQL
200       rs.Open strSQL, Cnxn  ', adOpenStatic, adLockReadOnly, adCmdText 'adLockOptimistic  'adLockReadOnly
          '
210       If rs.State <> adStateOpen Then

220          sMsg = "**** ERROR Could Not Open/Find File! ****" & vbCrLf & vbCrLf & _
                       "in Module 'modUtils' - Function 'Fetch_TD_Data'" & vbCrLf & "Line # " & 190 & vbCrLf & _
                       vbCrLf & " SQL: '" & strSQL & "'"
230          vLogMsg = sMsg
240          MsgLog

250          GoTo Fetch_TD_Data_Exit
260       End If



Determine if a recordset contains data


If Not rs.EOF And Not rs.BOF Then    'Check for End or Beginning of File
'310           Debug.Print rs!locationid    'Print the contents of the field...
'           End If
'280       If rs.RecordCount > 0 Then
360          vtemp = rs.GetRows()
370          If IsArray(vtemp) Then
380             Fetch_TD_Data = TransposeArray(vtemp)    'vtemp '
390          End If
400       Else
410          sMsg = "**** ERROR NO DATA FOUND ****" & vbCrLf & vbCrLf & _
                       "in Module 'modUtils' - Function 'Fetch_TD_Data'" & vbCrLf & "Line # " & 140 & vbCrLf & _
                       vbCrLf & " SQL: '" & strSQL & "'"
420          vLogMsg = sMsg
430          MsgLog
440       End If 



Cleanup recordset object variable

 ' clean up
450       If Not rs Is Nothing Then
460          If rs.State = adStateOpen Then rs.Close
470       End If
480       Set rs = Nothing



Cleanup connection object variable

 490       If Not Cnxn Is Nothing Then
500           If Cnxn.State = adStateOpen Then Cnxn.Close
510       End If
520       Set Cnxn = Nothing