|
- <% Option Explicit %>
- <!--#include file="../../include_all.asp"-->
- <!--#include file="../../ViewModels/JurisdictionViewModels.asp"-->
- <%
- Class JurisdictionController
- Public Model
-
- Public Sub Index
-
- dim page_size : page_size = 10
- dim page_num : page_num = Choice(Len(Request.Querystring("page_num")) > 0, Request.Querystring("page_num"), 1)
- dim page_count, record_count
- set Model = new PagedIndex_ViewModel_Class
- Model.Title = "Jurisdiction"
- set Model.Jurisdiction = JurisdictionRepository.FindPaged(empty, "JCode", page_size, page_num, page_count, record_count)
- Model.CurrentPageNumber = page_num
- Model.PageSize = page_size
- Model.PageCount = page_count
- Model.RecordCount = record_count
- %> <!--#include file="../../Views/Jurisdiction/Index.asp"--> <%
-
- End Sub
- Public Sub Search
-
- dim searchValue:searchValue = Choice(Request.Form.Count = 0,Request.QueryString("q"),Request.Form("q"))
- dim page_size : page_size = 10
- dim page_num : page_num = Choice(Len(Request.Querystring("page_num")) > 0, Request.Querystring("page_num"), 1)
- dim page_count, record_count
- set Model = new PagedIndex_ViewModel_Class
- Model.Title = "Jurisdiction"
- set Model.Jurisdiction = JurisdictionRepository.SearchTablePaged(Array("JCode","%" & searchValue & "%","Name","%" & searchValue & "%","Mailing_Address","%" & searchValue & "%","CSZ","%" & searchValue & "%","IMB","%" & searchValue & "%","IMB_Digits","%" & searchValue & "%"),"JCode", page_size, page_num, page_count, record_count)
- Model.CurrentPageNumber = page_num
- Model.PageSize = page_size
- Model.PageCount = page_count
- Model.RecordCount = record_count
- %> <!--#include file="../../Views/Jurisdiction/Index.asp"--> <%
-
- End Sub
-
- Public Sub Edit
-
- dim id : id = Request.QueryString("Id")
- set Model = new Edit_ViewModel_Class
- set Model.Jurisdiction = JurisdictionRepository.FindByJCode(id)
- set Model.Contacts = ContactsRepository.Find(Array("JURISCODE = ?",id),empty)
- Model.Title = "Edit Jurisdiction"
- HTMLSecurity.SetAntiCSRFToken "JurisdictionEditForm"
- %> <!--#include file="../../Views/Jurisdiction/Edit.asp"--> <%
- Flash.Success = "Jurisdiction Updated."
- End Sub
-
- Public Sub EditPost
- MVC.RequirePost
- HTMLSecurity.OnInvalidAntiCsrfTokenRedirectToActionExt "JurisdictionEditForm", Request.Form("nonce"), "Edit", Array("Id", Request.Form("Id"))
- dim JCode : JCode = Request.Form("Id")
- dim model : set model = JurisdictionRepository.FindByJCode(JCode)
- set model = Automapper.AutoMap(Request.Form, model)
- 'model.Validate
- 'If model.Validator.HasErrors then
- FormCache.SerializeForm "EditJurisdiction", Request.Form
- ' Flash.Errors = model.Validator.Errors
- ' MVC.RedirectToActionExt "Edit", Array("Id",JCode)
- 'Else
- JurisdictionRepository.Update model
- FormCache.ClearForm "EditJurisdiction"
- Flash.Success = "Jurisdiction updated."
- MVC.RedirectToAction "Index"
- 'End If
- End Sub
-
- Public Sub Create
-
- dim form_params : set form_params = FormCache.DeserializeForm("NewJurisdiction")
- If Not form_params Is Nothing then
- set Model = Automapper.AutoMap(form_params, New Create_ViewModel_Class)
- Else
- set Model = new Create_ViewModel_Class
- End If
-
- HTMLSecurity.SetAntiCSRFToken "JurisdictionCreateForm"
-
- %> <!--#include file="../../Views/Jurisdiction/Create.asp"--> <%
- End Sub
-
- Public Sub CreatePost
-
- MVC.RequirePost
- HtmlSecurity.OnInvalidAntiCSRFTokenRedirectToAction "JurisdictionCreateForm", Request.Form("nonce"), "Create"
-
- dim new_Jurisdiction_model : set new_Jurisdiction_model = Automapper.AutoMap(Request.Form, new JurisdictionModel_Class)
-
- 'new_Jurisdiction_model.Validator.Validate
-
- 'If new_Jurisdiction_model.Validator.HasErrors then
- ' FormCache.SerializeForm "NewJurisdiction", Request.Form
- ' Flash.Errors = new_Jurisdiction_model.Validator.Errors
- ' MVC.RedirectToAction "Create"
- 'Else
- JurisdictionRepository.AddNew new_Jurisdiction_model
- ' FormCache.ClearForm "NewJurisdiction"
- Flash.Success = "Jurisdiction added."
- MVC.RedirectToAction "Index"
- 'End If
- End Sub
-
- Public Sub Delete
- dim id : id = Request.QueryString("Id")
- set Model = new Delete_ViewModel_Class
- set Model.Jurisdiction = JurisdictionRepository.FindByJCode(id)
- Model.Title = "Delete Jurisdiction"
-
- HTMLSecurity.SetAntiCSRFToken "JurisdictionDeleteForm"
-
- %> <!--#include file="../../Views/Jurisdiction/Delete.asp"--> <%
- End Sub
-
- Public Sub DeletePost
- MVC.RequirePost
- HtmlSecurity.OnInvalidAntiCSRFTokenRedirectToAction "JurisdictionDeleteForm", Request.Form("nonce"), "Create"
-
- dim id : id = Request.Form("Id")
- JurisdictionRepository.Delete id
-
- Flash.Success = "Jurisdiction deleted."
- MVC.RedirectToAction "Index"
- End Sub
-
- Public Sub Createkit
- dim id : id = Request.QueryString("Id")
- set Model = new Delete_ViewModel_Class
- set Model.Jurisdiction = JurisdictionRepository.FindByJCode(id)
- Model.Title = "Create Kit"
-
- HTMLSecurity.SetAntiCSRFToken "JurisdictionDeleteForm"
-
- %> <!--#include file="../../Views/Jurisdiction/createkit.asp"--> <%
-
- End sub
-
- Public Sub CreateKitPost
- MVC.RequirePost
- HtmlSecurity.OnInvalidAntiCSRFTokenRedirectToAction "CreateKitForm", Request.Form("nonce"), "Index"
- dim id : id = Request.QueryString("Id")
- set Model = new Delete_ViewModel_Class
- set Model.Jurisdiction = JurisdictionRepository.FindByJCode(id)
- Model.Title = "Create Kit"
-
- HTMLSecurity.SetAntiCSRFToken "JurisdictionDeleteForm"
-
- %> <!--#include file="../../Views/Jurisdiction/createkit.asp"--> <%
-
- End sub
-
- Public Sub Import
-
- dim page_size : page_size = 10
- dim page_num : page_num = Choice(Len(Request.Querystring("page_num")) > 0, Request.Querystring("page_num"), 1)
- dim page_count, record_count
- set Model = new PagedIndex_ViewModel_Class
- Model.Title = "Jurisdiction"
- set Model.Jurisdiction = JurisdictionRepository.FindPaged(empty, "JCode", page_size, page_num, page_count, record_count)
- Model.CurrentPageNumber = page_num
- Model.PageSize = page_size
- Model.PageCount = page_count
- 'Model.RecordCount = record_count
- HTMLSecurity.SetAntiCSRFToken "JurisdictionImportForm"
- %> <!--#include file="../../Views/Jurisdiction/import.asp"--> <%
-
- End Sub
-
- Public Sub ImportPost
- If UCase(Request.ServerVariables("REQUEST_METHOD") & "") <> "POST" Then
- Err.Raise 1, "JurisdictionController:ImportPost", "Action only responds to POST requests."
- End If
-
- Dim Upload : Set Upload = New FreeASPUpload
- Dim uploadPath, uploadedFile, fileName, fileExt, fileSize
- Dim maxFileSize, dotPos, nonce
- Dim savedFileName, savedLocalFileName, savedPath
- Dim workbookData, worksheetName, headerIndex, missingHeaders
- Dim importToken, totalRows, duplicateCount
-
- maxFileSize = 10485760 '10 MB in bytes
- uploadPath = Server.MapPath("/uploads")
-
- Upload.Upload
- nonce = Upload.Form("nonce")
-
- If Not HTMLSecurity.IsValidAntiCSRFToken("JurisdictionImportForm", nonce) Then
- HTMLSecurity.ClearAntiCSRFToken "JurisdictionImportForm"
- HTMLSecurity.SetAntiCSRFToken "JurisdictionImportForm"
- SendImportJsonError "Invalid form state. Please refresh and try again."
- Exit Sub
- End If
- HTMLSecurity.ClearAntiCSRFToken "JurisdictionImportForm"
- HTMLSecurity.SetAntiCSRFToken "JurisdictionImportForm"
-
- If Upload.FileExists("filename") = False Then
- SendImportJsonError "No file selected for upload."
- Exit Sub
- End If
-
- Set uploadedFile = Upload.UploadedFiles("filename")
- fileName = uploadedFile.FileName
- fileSize = uploadedFile.Length
-
- dotPos = InStrRev(fileName, ".")
- If dotPos > 0 Then
- fileExt = LCase(Mid(fileName, dotPos))
- Else
- fileExt = ""
- End If
-
- If fileExt <> ".xlsx" Then
- SendImportJsonError "Only .xlsx files are allowed."
- Exit Sub
- End If
-
- If fileSize > maxFileSize Then
- SendImportJsonError "File size exceeds 10 MB limit."
- Exit Sub
- End If
-
- EnsureFolderExists uploadPath
- Upload.SaveOne uploadPath, 0, savedFileName, savedLocalFileName
- savedPath = uploadPath & "\" & savedLocalFileName
-
- On Error Resume Next
- workbookData = ReadWorkbookData(savedPath, worksheetName)
- If Err.Number <> 0 Then
- Dim workbookErr : workbookErr = Err.Description
- Err.Clear
- On Error GoTo 0
- DeleteFileIfExists savedPath
- SendImportJsonError "Unable to read the XLSX workbook. Verify Microsoft ACE OLEDB is installed and the workbook is valid. " & workbookErr
- Exit Sub
- End If
- On Error GoTo 0
-
- If Not WorkbookHasHeaderRows(workbookData) Then
- DeleteFileIfExists savedPath
- SendImportJsonError "The uploaded workbook must contain an information row and a header row."
- Exit Sub
- End If
-
- Set headerIndex = BuildHeaderIndex(workbookData, 1)
- missingHeaders = MissingRequiredHeaders(headerIndex)
- If Len(missingHeaders) > 0 Then
- DeleteFileIfExists savedPath
- SendImportJsonError "Missing required header(s): " & missingHeaders
- Exit Sub
- End If
-
- totalRows = CountImportRows(workbookData)
- duplicateCount = CountDuplicateJCodes(workbookData, CLng(headerIndex.Item("JURISDICTION")))
- importToken = CreateImportToken()
-
- InitializeImportSession importToken, workbookData, worksheetName, fileName, savedPath, totalRows, duplicateCount, headerIndex
- SendImportJsonSuccess importToken, fileName, totalRows, duplicateCount
- End Sub
-
- Public Sub ImportProgress
- Dim importToken : importToken = Trim(Request.QueryString("token") & "")
- If Len(importToken) = 0 Then
- SendImportJsonError "Missing import token."
- Exit Sub
- End If
-
- If Not ImportExists(importToken) Then
- SendImportJsonError "The requested import session was not found. Please upload the workbook again."
- Exit Sub
- End If
-
- Dim phase : phase = GetImportValue(importToken, "Phase")
- If phase <> "complete" And phase <> "error" Then
- ProcessImportChunk importToken, 25
- End If
-
- SendImportProgressJson importToken
- End Sub
-
- Private Sub ProcessImportChunk(importToken, maxRowsPerRequest)
- Dim sessionKey : sessionKey = ImportSessionKey(importToken)
- Dim workbookData : workbookData = Session(sessionKey & "Data")
- Dim currentRow, lastRow, rowsProcessed
-
- If Not IsArray(workbookData) Then
- SetImportValue importToken, "Phase", "error"
- SetImportValue importToken, "StatusMessage", "Workbook data is no longer available in session."
- AppendImportError importToken, 0, "Workbook data is no longer available in session.", ""
- Exit Sub
- End If
-
- currentRow = CLng(GetImportValue(importToken, "CurrentRow"))
- lastRow = UBound(workbookData, 2)
- rowsProcessed = 0
-
- If currentRow < 2 Then currentRow = 2
- SetImportValue importToken, "Phase", "processing"
-
- Do While currentRow <= lastRow And rowsProcessed < maxRowsPerRequest
- ProcessImportRow importToken, workbookData, currentRow
- currentRow = currentRow + 1
- rowsProcessed = rowsProcessed + 1
- SetImportValue importToken, "CurrentRow", currentRow
- SetImportValue importToken, "ProcessedRows", CLng(GetImportValue(importToken, "ProcessedRows")) + 1
- Loop
-
- If currentRow > lastRow Then
- SetImportValue importToken, "Phase", "complete"
- SetImportValue importToken, "StatusMessage", "Import complete."
- Session.Contents.Remove sessionKey & "Data"
- DeleteFileIfExists GetImportValue(importToken, "FilePath")
- Session.Contents.Remove sessionKey & "FilePath"
- Else
- SetImportValue importToken, "StatusMessage", "Processed " & GetImportValue(importToken, "ProcessedRows") & " of " & GetImportValue(importToken, "TotalRows") & " row(s)."
- End If
- End Sub
-
- Private Sub ProcessImportRow(importToken, workbookData, rowIndex)
- Dim county, jurisdictionText, jCode, jurisdictionName, mailingAddress, cityTownship, zipPlusFour, mailerId
- Dim csz, imbDigits, imb, jurisdictionModel, recordSummary
-
- county = SafeWorkbookValue(workbookData(GetImportColumnIndex(importToken, "CountyIndex"), rowIndex))
- jurisdictionText = SafeWorkbookValue(workbookData(GetImportColumnIndex(importToken, "JurisdictionIndex"), rowIndex))
- mailingAddress = SafeWorkbookValue(workbookData(GetImportColumnIndex(importToken, "MailingAddressIndex"), rowIndex))
- cityTownship = SafeWorkbookValue(workbookData(GetImportColumnIndex(importToken, "CityTownshipIndex"), rowIndex))
- zipPlusFour = SafeWorkbookValue(workbookData(GetImportColumnIndex(importToken, "ZipPlusFourIndex"), rowIndex))
- mailerId = SafeWorkbookValue(workbookData(GetImportColumnIndex(importToken, "MailerIdIndex"), rowIndex))
- recordSummary = BuildImportRecordSummary(county, jurisdictionText, mailingAddress, cityTownship, zipPlusFour, mailerId)
-
- If Len(Trim(county & jurisdictionText & mailingAddress & cityTownship & zipPlusFour & mailerId)) = 0 Then
- IncrementImportCounter importToken, "InvalidCount"
- AppendImportError importToken, rowIndex + 1, "Row is empty.", recordSummary
- Exit Sub
- End If
-
- jCode = ExtractJurisdictionCode(jurisdictionText)
- If Len(jCode) = 0 Then
- IncrementImportCounter importToken, "InvalidCount"
- AppendImportError importToken, rowIndex + 1, "Jurisdiction field is missing a code in parentheses.", recordSummary
- Exit Sub
- End If
-
- jurisdictionName = NormalizeJurisdictionName(ExtractJurisdictionName(jurisdictionText))
- If Len(jurisdictionName) = 0 Then
- IncrementImportCounter importToken, "InvalidCount"
- AppendImportError importToken, rowIndex + 1, "Jurisdiction name could not be parsed.", recordSummary
- Exit Sub
- End If
-
- csz = BuildCSZ(cityTownship, zipPlusFour)
- imbDigits = BuildIMBDigits(mailerId, zipPlusFour)
- If Len(imbDigits) = 0 Then
- IncrementImportCounter importToken, "InvalidCount"
- AppendImportError importToken, rowIndex + 1, "Unable to build IMB digits from Mailer ID Option 1 and ZIP + 4.", recordSummary
- Exit Sub
- End If
-
- On Error Resume Next
- imb = GetIMBCodec.EncodeDigits(imbDigits)
- If Err.Number <> 0 Then
- Dim imbErr : imbErr = Err.Description
- Err.Clear
- On Error GoTo 0
- IncrementImportCounter importToken, "FailedCount"
- AppendImportError importToken, rowIndex + 1, "IMB generation failed for JCode " & jCode & ". " & imbErr, recordSummary
- Exit Sub
- End If
- On Error GoTo 0
-
- On Error Resume Next
- Set jurisdictionModel = JurisdictionRepository.FindByJCode(jCode)
- If Err.Number <> 0 Then
- Err.Clear
- On Error GoTo 0
- Set jurisdictionModel = New JurisdictionModel_Class
- jurisdictionModel.JCode = jCode
- jurisdictionModel.Name = jurisdictionName
- jurisdictionModel.Mailing_Address = mailingAddress
- jurisdictionModel.CSZ = csz
- jurisdictionModel.IMB_Digits = imbDigits
- jurisdictionModel.IMB = imb
-
- On Error Resume Next
- JurisdictionRepository.AddNewWithJCode jurisdictionModel
- If Err.Number <> 0 Then
- Dim insertErr : insertErr = Err.Description
- Err.Clear
- On Error GoTo 0
- IncrementImportCounter importToken, "FailedCount"
- AppendImportError importToken, rowIndex + 1, "Failed to insert new JCode " & jCode & ". " & insertErr, recordSummary
- Exit Sub
- End If
- On Error GoTo 0
-
- IncrementImportCounter importToken, "InsertedCount"
- Exit Sub
- End If
- On Error GoTo 0
-
- jurisdictionModel.Name = jurisdictionName
- jurisdictionModel.Mailing_Address = mailingAddress
- jurisdictionModel.CSZ = csz
- jurisdictionModel.IMB_Digits = imbDigits
- jurisdictionModel.IMB = imb
-
- On Error Resume Next
- JurisdictionRepository.Update jurisdictionModel
- If Err.Number <> 0 Then
- Dim updateErr : updateErr = Err.Description
- Err.Clear
- On Error GoTo 0
- IncrementImportCounter importToken, "FailedCount"
- AppendImportError importToken, rowIndex + 1, "Failed to update JCode " & jCode & ". " & updateErr, recordSummary
- Exit Sub
- End If
- On Error GoTo 0
-
- IncrementImportCounter importToken, "UpdatedCount"
- End Sub
-
- Private Function ReadWorkbookData(filePath, ByRef worksheetName)
- Dim conn, rs, connString, sql
-
- connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & filePath & ";Extended Properties=""Excel 12.0 Xml;HDR=NO;IMEX=1"";"
- Set conn = Server.CreateObject("ADODB.Connection")
- conn.Open connString
-
- worksheetName = FirstWorksheetName(conn)
- If Len(worksheetName) = 0 Then
- conn.Close
- Set conn = Nothing
- Err.Raise vbObjectError + 2010, "JurisdictionController", "No worksheet was found in the uploaded workbook."
- End If
-
- sql = "SELECT * FROM [" & worksheetName & "]"
- Set rs = Server.CreateObject("ADODB.Recordset")
- rs.Open sql, conn, 3, 1
-
- If rs.EOF And rs.BOF Then
- rs.Close
- conn.Close
- Set rs = Nothing
- Set conn = Nothing
- Err.Raise vbObjectError + 2011, "JurisdictionController", "The worksheet does not contain any rows."
- End If
-
- ReadWorkbookData = rs.GetRows()
-
- rs.Close
- conn.Close
- Set rs = Nothing
- Set conn = Nothing
- End Function
-
- Private Function FirstWorksheetName(conn)
- Dim schema, tableName
-
- Set schema = conn.OpenSchema(20)
- Do Until schema.EOF
- tableName = Trim(schema("TABLE_NAME") & "")
- If InStr(tableName, "$") > 0 And InStr(tableName, "_xlnm") = 0 Then
- FirstWorksheetName = tableName
- schema.Close
- Set schema = Nothing
- Exit Function
- End If
- schema.MoveNext
- Loop
-
- If Not schema Is Nothing Then
- schema.Close
- Set schema = Nothing
- End If
- FirstWorksheetName = ""
- End Function
-
- Private Function BuildHeaderIndex(workbookData, headerRowIndex)
- Dim headerMap, colIndex, headerName
-
- Set headerMap = Server.CreateObject("Scripting.Dictionary")
- For colIndex = 0 To UBound(workbookData, 1)
- headerName = UCase(Trim(SafeWorkbookValue(workbookData(colIndex, headerRowIndex))))
- If Len(headerName) > 0 Then
- If Not headerMap.Exists(headerName) Then
- headerMap.Add headerName, colIndex
- End If
- End If
- Next
-
- Set BuildHeaderIndex = headerMap
- End Function
-
- Private Function WorkbookHasHeaderRows(workbookData)
- On Error Resume Next
- WorkbookHasHeaderRows = (IsArray(workbookData) And UBound(workbookData, 2) >= 1)
- If Err.Number <> 0 Then
- Err.Clear
- WorkbookHasHeaderRows = False
- End If
- On Error GoTo 0
- End Function
-
- Private Function MissingRequiredHeaders(headerIndex)
- Dim requiredHeaders, missingHeaders, i
-
- requiredHeaders = Array("County", "Jurisdiction", "Mailing Address", "City & Township", "ZIP + 4", "Mailer ID Option 1")
- missingHeaders = ""
-
- For i = 0 To UBound(requiredHeaders)
- If Not headerIndex.Exists(UCase(requiredHeaders(i))) Then
- If Len(missingHeaders) > 0 Then missingHeaders = missingHeaders & ", "
- missingHeaders = missingHeaders & requiredHeaders(i)
- End If
- Next
-
- MissingRequiredHeaders = missingHeaders
- End Function
-
- Private Function CountImportRows(workbookData)
- If Not WorkbookHasHeaderRows(workbookData) Then
- CountImportRows = 0
- ElseIf UBound(workbookData, 2) < 2 Then
- CountImportRows = 0
- Else
- CountImportRows = UBound(workbookData, 2) - 1
- End If
- End Function
-
- Private Function CountDuplicateJCodes(workbookData, jurisdictionColumnIndex)
- Dim seenCodes, rowIndex, jCode
-
- Set seenCodes = Server.CreateObject("Scripting.Dictionary")
- CountDuplicateJCodes = 0
-
- If Not WorkbookHasHeaderRows(workbookData) Then Exit Function
- If UBound(workbookData, 2) < 2 Then Exit Function
-
- For rowIndex = 2 To UBound(workbookData, 2)
- jCode = ExtractJurisdictionCode(SafeWorkbookValue(workbookData(jurisdictionColumnIndex, rowIndex)))
- If Len(jCode) > 0 Then
- If seenCodes.Exists(jCode) Then
- CountDuplicateJCodes = CountDuplicateJCodes + 1
- Else
- seenCodes.Add jCode, True
- End If
- End If
- Next
- End Function
-
- Private Sub InitializeImportSession(importToken, workbookData, worksheetName, fileName, filePath, totalRows, duplicateCount, headerIndex)
- Dim sessionKey : sessionKey = ImportSessionKey(importToken)
-
- Session(sessionKey & "Data") = workbookData
- Session(sessionKey & "WorksheetName") = worksheetName
- Session(sessionKey & "FileName") = fileName
- Session(sessionKey & "FilePath") = filePath
- Session(sessionKey & "CurrentRow") = 2
- Session(sessionKey & "ProcessedRows") = 0
- Session(sessionKey & "TotalRows") = totalRows
- Session(sessionKey & "UpdatedCount") = 0
- Session(sessionKey & "InsertedCount") = 0
- Session(sessionKey & "UnmatchedCount") = 0
- Session(sessionKey & "InvalidCount") = 0
- Session(sessionKey & "FailedCount") = 0
- Session(sessionKey & "DuplicateCount") = duplicateCount
- Session(sessionKey & "Phase") = "staged"
- Session(sessionKey & "StatusMessage") = "Workbook uploaded. Processing will begin shortly."
- Session(sessionKey & "Errors") = ""
- Session(sessionKey & "CountyIndex") = CLng(headerIndex.Item("COUNTY"))
- Session(sessionKey & "JurisdictionIndex") = CLng(headerIndex.Item("JURISDICTION"))
- Session(sessionKey & "MailingAddressIndex") = CLng(headerIndex.Item("MAILING ADDRESS"))
- Session(sessionKey & "CityTownshipIndex") = CLng(headerIndex.Item("CITY & TOWNSHIP"))
- Session(sessionKey & "ZipPlusFourIndex") = CLng(headerIndex.Item("ZIP + 4"))
- Session(sessionKey & "MailerIdIndex") = CLng(headerIndex.Item("MAILER ID OPTION 1"))
- End Sub
-
- Private Function CreateImportToken()
- Dim token : token = HTMLSecurity.Nonce()
- token = Replace(token, "{", "")
- token = Replace(token, "}", "")
- CreateImportToken = token
- End Function
-
- Private Function ImportSessionKey(importToken)
- ImportSessionKey = "JurisdictionImport." & importToken & "."
- End Function
-
- Private Function ImportExists(importToken)
- ImportExists = (Len(GetImportValue(importToken, "Phase")) > 0)
- End Function
-
- Private Function GetImportValue(importToken, name)
- GetImportValue = Session(ImportSessionKey(importToken) & name)
- End Function
-
- Private Sub SetImportValue(importToken, name, value)
- Session(ImportSessionKey(importToken) & name) = value
- End Sub
-
- Private Function GetImportColumnIndex(importToken, name)
- GetImportColumnIndex = CLng(GetImportValue(importToken, name))
- End Function
-
- Private Sub IncrementImportCounter(importToken, counterName)
- SetImportValue importToken, counterName, CLng(GetImportValue(importToken, counterName)) + 1
- End Sub
-
- Private Function ExtractJurisdictionCode(jurisdictionText)
- Dim openPos, closePos
-
- openPos = InStrRev(jurisdictionText, "(")
- closePos = InStrRev(jurisdictionText, ")")
-
- If openPos > 0 And closePos > openPos Then
- ExtractJurisdictionCode = Trim(Mid(jurisdictionText, openPos + 1, closePos - openPos - 1))
- Else
- ExtractJurisdictionCode = ""
- End If
- End Function
-
- Private Function ExtractJurisdictionName(jurisdictionText)
- Dim openPos
-
- openPos = InStrRev(jurisdictionText, "(")
- If openPos > 0 Then
- ExtractJurisdictionName = Trim(Left(jurisdictionText, openPos - 1))
- Else
- ExtractJurisdictionName = Trim(jurisdictionText)
- End If
- End Function
-
- Private Function NormalizeJurisdictionName(jurisdictionName)
- Dim normalizedName
-
- normalizedName = Trim(jurisdictionName)
- If Len(normalizedName) >= 5 Then
- If UCase(Right(normalizedName, 5)) = " CITY" Then
- normalizedName = "CITY OF " & Trim(Left(normalizedName, Len(normalizedName) - 5))
- End If
- End If
-
- NormalizeJurisdictionName = normalizedName
- End Function
-
- Private Function BuildCSZ(cityTownship, zipPlusFour)
- BuildCSZ = Trim(Trim(cityTownship) & " " & Trim(zipPlusFour))
- End Function
-
- Private Function BuildIMBDigits(mailerId, zipPlusFour)
- Dim cleanMailerId, cleanZip
-
- cleanMailerId = DigitsOnly(mailerId)
- cleanZip = DigitsOnly(zipPlusFour)
-
- If Len(cleanMailerId) = 0 Or Len(cleanZip) = 0 Then
- BuildIMBDigits = ""
- Else
- BuildIMBDigits = "00778" & cleanMailerId & "000000" & cleanZip
- End If
- End Function
-
- Private Function DigitsOnly(inputValue)
- Dim i, ch
-
- DigitsOnly = ""
- For i = 1 To Len(inputValue)
- ch = Mid(inputValue, i, 1)
- If ch >= "0" And ch <= "9" Then
- DigitsOnly = DigitsOnly & ch
- End If
- Next
- End Function
-
- Private Function SafeWorkbookValue(value)
- If IsNull(value) Or IsEmpty(value) Then
- SafeWorkbookValue = ""
- Else
- SafeWorkbookValue = Trim(CStr(value))
- End If
- End Function
-
- Private Function BuildImportRecordSummary(county, jurisdictionText, mailingAddress, cityTownship, zipPlusFour, mailerId)
- BuildImportRecordSummary = "County=" & DisplayImportField(county) & _
- "; Jurisdiction=" & DisplayImportField(jurisdictionText) & _
- "; Mailing Address=" & DisplayImportField(mailingAddress) & _
- "; City & Township=" & DisplayImportField(cityTownship) & _
- "; ZIP + 4=" & DisplayImportField(zipPlusFour) & _
- "; Mailer ID Option 1=" & DisplayImportField(mailerId)
- End Function
-
- Private Function DisplayImportField(value)
- If Len(Trim(value & "")) = 0 Then
- DisplayImportField = "<blank>"
- Else
- DisplayImportField = value & ""
- End If
- End Function
-
- Private Sub AppendImportError(importToken, rowNumber, errorMessage, recordSummary)
- Dim sessionKey, currentErrors, fullMessage
-
- sessionKey = ImportSessionKey(importToken)
- currentErrors = Session(sessionKey & "Errors") & ""
-
- If rowNumber > 0 Then
- fullMessage = "Row " & rowNumber & ": " & errorMessage
- Else
- fullMessage = errorMessage
- End If
-
- If Len(Trim(recordSummary & "")) > 0 Then
- fullMessage = fullMessage & " Record: " & recordSummary
- End If
-
- If Len(currentErrors) > 0 Then
- currentErrors = currentErrors & Chr(30)
- End If
- currentErrors = currentErrors & fullMessage
-
- Session(sessionKey & "Errors") = currentErrors
- End Sub
-
- Private Sub SendImportJsonSuccess(importToken, fileName, totalRows, duplicateCount)
- Response.ContentType = "application/json"
- Response.Write "{""ok"":true,""token"":""" & JsonEscape(importToken) & """,""fileName"":""" & JsonEscape(fileName) & """,""phase"":""staged"",""totalRows"":" & totalRows & ",""processedRows"":0,""updatedCount"":0,""insertedCount"":0,""invalidCount"":0,""failedCount"":0,""duplicateCount"":" & duplicateCount & ",""percentComplete"":0,""statusMessage"":""Workbook uploaded. Processing will begin shortly."",""nextNonce"":""" & JsonEscape(HTMLSecurity.GetAntiCSRFToken("JurisdictionImportForm")) & """,""errors"":[]}"
- Response.End
- End Sub
-
- Private Sub SendImportProgressJson(importToken)
- Dim phase, totalRows, processedRows, updatedCount, insertedCount, invalidCount, failedCount, duplicateCount
- Dim percentComplete, statusMessage, errorsJson
-
- phase = GetImportValue(importToken, "Phase")
- totalRows = CLng(GetImportValue(importToken, "TotalRows"))
- processedRows = CLng(GetImportValue(importToken, "ProcessedRows"))
- updatedCount = CLng(GetImportValue(importToken, "UpdatedCount"))
- insertedCount = CLng(GetImportValue(importToken, "InsertedCount"))
- invalidCount = CLng(GetImportValue(importToken, "InvalidCount"))
- failedCount = CLng(GetImportValue(importToken, "FailedCount"))
- duplicateCount = CLng(GetImportValue(importToken, "DuplicateCount"))
- statusMessage = GetImportValue(importToken, "StatusMessage") & ""
- errorsJson = JsonArrayFromDelimitedString(GetImportValue(importToken, "Errors") & "")
-
- If totalRows > 0 Then
- percentComplete = Int((processedRows / totalRows) * 100)
- Else
- percentComplete = 100
- End If
- If phase = "complete" Then percentComplete = 100
-
- Response.ContentType = "application/json"
- Response.Write "{""ok"":true,""token"":""" & JsonEscape(importToken) & """,""phase"":""" & JsonEscape(phase) & """,""totalRows"":" & totalRows & ",""processedRows"":" & processedRows & ",""updatedCount"":" & updatedCount & ",""insertedCount"":" & insertedCount & ",""invalidCount"":" & invalidCount & ",""failedCount"":" & failedCount & ",""duplicateCount"":" & duplicateCount & ",""percentComplete"":" & percentComplete & ",""statusMessage"":""" & JsonEscape(statusMessage) & """,""errors"":" & errorsJson & "}"
- Response.End
- End Sub
-
- Private Sub SendImportJsonError(errorMessage)
- Response.ContentType = "application/json"
- Response.Status = "400 Bad Request"
- Response.Write "{""ok"":false,""message"":""" & JsonEscape(errorMessage) & """,""nextNonce"":""" & JsonEscape(HTMLSecurity.GetAntiCSRFToken("JurisdictionImportForm")) & """}"
- Response.End
- End Sub
-
- Private Function JsonArrayFromDelimitedString(delimitedValue)
- Dim items, i, result
-
- If Len(delimitedValue) = 0 Then
- JsonArrayFromDelimitedString = "[]"
- Exit Function
- End If
-
- items = Split(delimitedValue, Chr(30))
- result = "["
- For i = 0 To UBound(items)
- If i > 0 Then result = result & ","
- result = result & """" & JsonEscape(items(i)) & """"
- Next
- result = result & "]"
-
- JsonArrayFromDelimitedString = result
- End Function
-
- Private Function JsonEscape(value)
- value = Replace(value & "", "\", "\\")
- value = Replace(value, """", "\""")
- value = Replace(value, vbCrLf, "\n")
- value = Replace(value, vbCr, "\n")
- value = Replace(value, vbLf, "\n")
- JsonEscape = value
- End Function
-
- Private Sub EnsureFolderExists(folderPath)
- Dim fso : Set fso = Server.CreateObject("Scripting.FileSystemObject")
- If Not fso.FolderExists(folderPath) Then
- fso.CreateFolder folderPath
- End If
- Set fso = Nothing
- End Sub
-
- Private Sub DeleteFileIfExists(filePath)
- Dim fso
- If Len(Trim(filePath & "")) = 0 Then Exit Sub
-
- Set fso = Server.CreateObject("Scripting.FileSystemObject")
- If fso.FileExists(filePath) Then
- On Error Resume Next
- fso.DeleteFile filePath, True
- On Error GoTo 0
- End If
- Set fso = Nothing
- End Sub
- End Class
- MVC.Dispatch
- %>
|