directshow - How to detect webcam plug / unplug? - directshow

Is there a simple way with DirectShow to detect if the webcam is plugged in (USB), or if someone has unplugged it (and then poll or search for it)?
I have seen code for Microsoft Media Foundation, but it is complex and Media Foundation isn't installable on < Vista, afaik.
Thx, WW

i use a WMI event watcher looking for the PID in the property string (some cameras may fire the events twice depending on drivers). here is a VB.Net example:
Dim CamEventWatcher As ManagementEventWatcher
Public Delegate Sub SetMessageCallback(ByVal [_Msg] As Boolean)
Private Sub MessageCallback(ByVal _Msg As Boolean)
If (_Msg) Then
'cam connected
Else
'camera removed
End If
End Sub
Private Sub RemoveCameraUSBHandler()
Try
If Not CamEventWatcher Is Nothing Then
CamEventWatcher.Stop()
End If
Catch ex As Exception
End Try
End Sub
Private Sub AddCameraUSBHandler()
Dim q As WqlEventQuery
Dim scope As ManagementScope = New ManagementScope("root\CIMV2")
scope.Options.EnablePrivileges = True
Try
q = New WqlEventQuery()
q.EventClassName = "__InstanceOperationEvent"
q.WithinInterval = New TimeSpan(0, 0, 1)
q.Condition = "TargetInstance ISA 'Win32_USBControllerdevice'"
CamEventWatcher = New ManagementEventWatcher(scope, q)
AddHandler CamEventWatcher.EventArrived, AddressOf CamUSBEvent
CamEventWatcher.Start()
Catch ex As Exception
End Try
End Sub
Private iCreatedFired As Integer = 0
Private iRemovedFired As Integer = 0
Public Sub CamUSBEvent(ByVal sender As System.Object, ByVal e As EventArrivedEventArgs)
If e.NewEvent.ClassPath.ClassName = "__InstanceCreationEvent" Then
Dim sAntecedent As String
Dim sDependent As String
sAntecedent = e.NewEvent.Properties("TargetInstance").Value.Properties("Antecedent").Value.ToString() + ControlChars.CrLf
sDependent = e.NewEvent.Properties("TargetInstance").Value.Properties("Dependent").Value.ToString() + ControlChars.CrLf
If sDependent.Contains(CAM_DEV_ID) Then
iCreatedFired += 1
If (iCreatedFired = 1) Then
e.NewEvent.Dispose()
Return
End If
iCreatedFired = 0
iRemovedFired = 0
Dim _delegate As New SetMessageCallback(AddressOf MessageCallback)
Me.Invoke(_delegate, New Object() {True})
End If
ElseIf e.NewEvent.ClassPath.ClassName = "__InstanceDeletionEvent" Then
Dim sAntecedent As String
Dim sDependent As String
sAntecedent = e.NewEvent.Properties("TargetInstance").Value.Properties("Antecedent").Value.ToString() + ControlChars.CrLf
sDependent = e.NewEvent.Properties("TargetInstance").Value.Properties("Dependent").Value.ToString() + ControlChars.CrLf
If sDependent.Contains(CAM_DEV_ID) Then
iRemovedFired += 1
If (iRemovedFired = 1) Then
e.NewEvent.Dispose()
Return
End If
iCreatedFired = 0
iRemovedFired = 0
Dim _delegate As New SetMessageCallback(AddressOf MessageCallback)
Me.Invoke(_delegate, New Object() {False})
End If
End If
e.NewEvent.Dispose()
End Sub

Related

Converting a list to an array for a web service

I'm currently trying to convert my searchList in the web app from a list to an array so that it can be consumed in the web method. Right now, I'm using a web reference which only allows arrays to be passed and returned. I'd like to just simply convert the list to an array, but it looks like that won't work. I've tried looking online but each scenario I've found hasn't been similar enough to where I'm able to solve this. Any idea on the best way to do this?
Web App
Protected Function SearchCustomer()
Dim searchList As List(Of prxCustomerWebService1.Customer)
Dim objCustomerWS As New prxCustomerWebService1.CustomerWS
searchList = Cache("CustomerData")
'arr = searchList.ToArray
If (ddlSearchSpecs.Text = "Contains") Then
searchList = objCustomerWS.GetContains(tbSearch.Text, ddlSearchFields.Text, searchList)
ElseIf (ddlSearchSpecs.Text = "Starts With") Then
searchList = objCustomerWS.GetStartsWith(tbSearch.Text, ddlSearchFields.Text, searchList)
Else
searchList = objCustomerWS.GetExact(tbSearch.Text, ddlSearchFields.Text, searchList)
End If
If searchList.Count = 0 Then
lMessage.Text = "No Customers Found"
End If
Return searchList
End Function
Web Method
<WebMethod(description:="Gets customers that contain a specific value")> _
Public Function GetContains(ByVal sStringContains As String, ByVal sPropertyName As String, ByVal oListOfCustomers List(Of Customer))
oListOfCustomers()
Return CustomerFactory.GetContains(sStringContains, sPropertyName, oListOfCustomers)
End Function
Logic
Public Shared Function GetContains(ByVal sStringContains As String, ByVal sPropertyName As String, ByVal oListOfCustomers As List(Of Customer))
Dim oCustomerData As New CustomerData
Dim oNewListOfCustomers As New List(Of Customer)
Dim iIndex As Integer
Dim propertyInfo As PropertyInfo
propertyInfo = GetType(Customer).GetProperty(sPropertyName)
If IsNothing(oListOfCustomers) = False AndAlso oListOfCustomers.Count > 0 Then
Try
For iIndex = 0 To oListOfCustomers.Count - 1
If (propertyInfo.GetValue(oListOfCustomers.Item(iIndex)).ToString.Trim.ToLower.Contains(sStringContains.ToLower) = True) Then
oNewListOfCustomers.Add(oListOfCustomers.Item(iIndex))
End If
Next
Catch ex As Exception
Return True
End Try
End If
Return oNewListOfCustomers
End Function

How do I print to the default printer on my Laptop from a VB.NET app I deployed to a IIS 8 server?

I've developed a VB.Net App using Visual studio 2015 on my Laptop which will print a rdlc local report for each selected row from a Gridview control directly to my laptop's default printer (which is a network printer) using the Microsoft code for 'walkthrough: Printing a Local Report without Preview' (and runs successfully on my local IIS express). When I deploy this App to a virtual company windows 2012 server that has IIS8 running, it no longer sees the default printer on my laptop (and tries to use the default printer on the windows 2012 server). I've searched the web to no success. I assume it's possible because when I use the reportviewer control in other apps I've developed and deployed on the Windows 2012 server, it can see the list of printers from my local laptop. Any ideas?
Here's the relevant VB code I'm using now...
Imports System.Management
Imports System
Imports System.IO
Imports System.Data
Imports System.Data.SqlClient
Imports System.Text
Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.Drawing.Printing
Imports System.Collections.Generic
Imports Microsoft.Reporting.WebForms
Partial Class _Default
Inherits System.Web.UI.Page
Implements IDisposable
Private m_currentPageIndex As Integer
Private m_streams As IList(Of Stream)
Public Shared ViewID As String
Public Shared UserID As String
Public Shared StampID As String
Public Shared GridViewQry As String
Public Shared OpenCntr As Integer = 0
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim sqlConnection2 As New SqlConnection("DataSource=AOXWEBAPP1\SQLEXPRESS;Initial Catalog=ManufacturingApps;User ID=AppUser;Password=#ppus3r;ApplicationIntent=ReadWrite")
Dim cmd2 As New SqlCommand
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1))
Response.Cache.SetNoStore()
OpenCntr = OpenCntr + 1
ViewID = Request.QueryString("ViewID")
If ViewID = "" Then
Response.Redirect("http://AOXWEBAPP1.SCOTT.COM/login/login.aspx")
Else
UserID = Request.QueryString("UserID")
StampID = Request.QueryString("StampID")
End If
cmd2.CommandText = "UpDate Super_FinalChk SET Selected=1 WHERE Printed = 1"
cmd2.Connection = sqlConnection2
sqlConnection2.Open()
cmd2.ExecuteNonQuery()
sqlConnection2.Close()
If OpenCntr = 1 Then
GridViewQry = "SELECT [Printed], [Customer], [AssySN], [Dte], [AssyPartNbr], [Operator], [PrintDate] FROM [Super_FinalChk] ORDER BY [Dte]"
End If
Dim adapter As New SqlDataAdapter(GridViewQry, sqlConnection2)
Dim superfinalchk As New DataSet("SqlDataSource1")
adapter.Fill(superfinalchk, "Super_FinalChkVw")
If (superfinalchk.Tables.Count > 0) Then
PrintATRs.DataSource = superfinalchk
If Not IsPostBack Then
PrintATRs.DataBind()
End If
Else
TextBox1.Text = "Unable to Connect to Database"
End If
' TextBox1.Text = DefaultPrinterName()
End Sub
' Routine to provide to the report renderer, in order to
' save an image for each page of the report.
Private Function CreateStream(ByVal name As String, ByVal fileNameExtension As String, ByVal encoding As Encoding, ByVal mimeType As String, ByVal willSeek As Boolean) As Stream
Dim stream As Stream = New MemoryStream()
m_streams.Add(stream)
Return stream
End Function
' Export the given report as an EMF (Enhanced Metafile) file.
Private Sub Export(ByVal report As LocalReport)
Dim deviceInfo As String = "<DeviceInfo>" &
"<OutputFormat>EMF</OutputFormat>" &
"<PageWidth>8.5in</PageWidth>" &
"<PageHeight>11in</PageHeight>" &
"<MarginTop>0.25in</MarginTop>" &
"<MarginLeft>0.50in</MarginLeft>" &
"<MarginRight>0.50in</MarginRight>" &
"<MarginBottom>0.25in</MarginBottom>" &
"</DeviceInfo>"
Dim warnings As Warning()
m_streams = New List(Of Stream)()
report.Render("Image", deviceInfo, AddressOf CreateStream, warnings)
For Each stream As Stream In m_streams
stream.Position = 0
Next
End Sub
' Handler for PrintPageEvents
Private Sub PrintPage(ByVal sender As Object, ByVal ev As PrintPageEventArgs)
Dim pageImage As New Metafile(m_streams(m_currentPageIndex))
' Adjust rectangular area with printer margins.
Dim adjustedRect As New Rectangle(ev.PageBounds.Left - CInt(ev.PageSettings.HardMarginX),
ev.PageBounds.Top - CInt(ev.PageSettings.HardMarginY),
ev.PageBounds.Width,
ev.PageBounds.Height)
' Draw a white background for the report
ev.Graphics.FillRectangle(Brushes.White, adjustedRect)
' Draw the report content
ev.Graphics.DrawImage(pageImage, adjustedRect)
' Prepare for the next page. Make sure we haven't hit the end.
m_currentPageIndex += 1
ev.HasMorePages = (m_currentPageIndex < m_streams.Count)
End Sub
Private Sub PrintRep()
If m_streams Is Nothing OrElse m_streams.Count = 0 Then
Throw New Exception("Error: no stream to print.")
End If
Dim printDoc As New PrintDocument()
If Not printDoc.PrinterSettings.IsValid Then
**
It FAILS HERE!!!!
**
Throw New Exception("Error: cannot find the printer.")
Else
AddHandler printDoc.PrintPage, AddressOf PrintPage
m_currentPageIndex = 0
printDoc.Print()
End If
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
If m_streams IsNot Nothing Then
For Each stream As Stream In m_streams
stream.Close()
Next
m_streams = Nothing
End If
End Sub
Private Function LoadSuperFinalChkVwData(AssySN As String) As DataTable
Dim sqlConnection1 As New SqlConnection("Data Source=AOXWEBAPP1\SQLEXPRESS;Initial Catalog=ManufacturingApps;User ID=AppUser;Password=#ppus3r;ApplicationIntent=ReadWrite")
Dim querystring As String = "SELECT * FROM dbo.Super_FinalChkVw WHERE AssySN = '" & AssySN & "'"
Dim adapter As New SqlDataAdapter(querystring, sqlConnection1)
Dim superfinalchkvw As New DataSet("DataSet1")
adapter.Fill(superfinalchkvw, "Super_FinalChkVw")
Return superfinalchkvw.Tables(0)
End Function
Protected Sub Print_Click(sender As Object, e As EventArgs) Handles Print.Click
Dim report As New LocalReport()
Dim sqlConnection2 As New SqlConnection("Data Source=AOXWEBAPP1\SQLEXPRESS;Initial Catalog=ManufacturingApps;User ID=AppUser;Password=#ppus3r;ApplicationIntent=ReadWrite")
Dim cmd2 As New SqlCommand
Dim cudate As DateTime
Dim AssySN As String
Dim cntr As Integer = 0
Dim SelectCount As Integer = 0
cudate = DateTime.Now
cmd2.Parameters.AddWithValue("#cudate", cudate)
For Each row As GridViewRow In PrintATRs.Rows
cntr = cntr + 1
Dim cb As CheckBox = DirectCast(row.FindControl("checkbox3"), CheckBox)
AssySN = row.Cells(3).Text
If cb.Checked Then
SelectCount = SelectCount + 1
report.ReportPath = "..\..\Manufacture\Superiox\ATR.rdlc"
report.DataSources.Clear()
report.DataSources.Add(New ReportDataSource("DataSet1", LoadSuperFinalChkVwData(AssySN)))
Export(report)
PrintRep()
cmd2.CommandText = "UpDate Super_FinalChk SET Selected=0, Printed=1, PrintDate=#cudate WHERE AssySN = '" & AssySN & "';"
cmd2.Connection = sqlConnection2
sqlConnection2.Open()
cmd2.ExecuteNonQuery()
sqlConnection2.Close()
End If
Next
Dim adapter As New SqlDataAdapter(GridViewQry, sqlConnection2)
Dim superfinalchk As New DataSet("SqlDataSource1")
adapter.Fill(superfinalchk, "Super_FinalChkVw")
PrintATRs.DataSource = superfinalchk
PrintATRs.DataBind()
If SelectCount > 0 Then
TextBox1.Text = "Reports Have Been Printed!"
Else
TextBox1.Text = "Please Select Reports to Print!"
End If
End Sub

Cannot refer to an instance member of a class from a shared method

How you get a public shared function outside of a Protected Sub, use the values from within a protected sub to postBack to the same webpage. The postback reply works, but the query of the function fails at (Line 44 Char 17 "fqdom = dom & ".forest.local")
Imports System
Imports System.IO
Imports System.DirectoryServices
Imports System.DirectoryServices.AccountManagement
Imports System.DirectoryServices.ActiveDirectory
Partial Class _Default
Inherits System.Web.UI.Page
Dim dom As String
Dim Group1 As String
Dim Group2 As String
Dim usrname As String
Dim fqdom As String
Dim netdom As String
Private Function GetDataFromArrayList() As ArrayList
Dim DomainList As New ArrayList()
DomainList.Add(New ListItem("d1", "dom1"))
DomainList.Add(New ListItem("d2", "dom2"))
Return DomainList
End Function
Protected Sub Selection_Changed(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
For Each item As ListItem In GetDataFromArrayList()
DropDownList1.Items.Add(item)
Next
End If
End Sub
Public Shared Function GetGroups() As ArrayList
Dim groupList As New ArrayList()
Dim usrname As String
Dim fqdom As String
'Dim netdom As String
Dim groupCheck As String
fqdom = dom & ".forest.local"
Dim entry As System.DirectoryServices.DirectoryEntry
Dim searcher As System.DirectoryServices.DirectorySearcher
Dim result As System.DirectoryServices.SearchResult
Try
entry = New System.DirectoryServices.DirectoryEntry("LDAP://" & fqdom)
searcher = New DirectorySearcher()
searcher.SearchRoot = entry
searcher.Filter = "(samAccountName=" & usrname & ")"
searcher.PropertiesToLoad.Add("memberOf")
result = searcher.FindOne()
Dim groupCount As Integer = result.Properties("memberOf").Count
For groupCounter As Integer = 0 To groupCount - 1
groupCheck = CStr(result.Properties("memberOf")(groupCounter))
groupCheck = groupCheck.Remove(groupCheck.LastIndexOf(",CN="))
groupCheck = groupCheck.Replace("CN=", "")
groupList.Add(groupCheck)
Next groupCounter
Catch ex As Exception
End Try
Return groupList
End Function
Protected Sub Button1_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Load
If IsPostBack Then
Dim name As Boolean = False
If Not TextBox1.Text = String.Empty Then
name = True
End If
If name = False Then
StatusLabel.Text = "Update Status: Please Enter Name"
ElseIf name = True Then
Group1 = "groupb1"
Group2 = "groupb2"
Try
form1.Visible = False
Dim groups As New ArrayList()
groups = GetGroups()
Dim group As String
For Each group In groups
'NameLabel.Text = group
If (group.Contains(Group1)) Then
Group1.Text = "User: " & usrname & " is in group1"
End If
If (group.Contains(Group2)) Then
Group1.Text = "User: " & usrname & " is in group2"
End If
Next
fqdn.Text = "Domain: " & dom & ".forest.local"
NameLabel.Text = "User: " & usrname
Catch ex As Exception
End Try
Else
StatusLabel.Text = "Upload status: Error Please Retry later"
End If
End If
End Sub
End Class
Remove the Shared keyword from the method, so replace
Public Shared Function GetGroups() As ArrayList
with
Public Function GetGroups() As ArrayList
You cannot use instance variables like dom from within a Shared method.
You could also make those fields Shared. But that's not a good idea in ASP.NET since it could cause locks and concurrency issues and every request shared the same values(even of different users).
It's also not necessary since you want to use that method from a page method(button-click), so you need an instance of the page anyway.
If you need to persist a value across postback you can use a different way like using ViewState, Session or a HiddenField.

convert from httppostedfile to htmlinputfile

how do I convert an httppostedfile to an htmlinputfile? I'm working with an old mess of an app and so far have been able to refactor it so it makes a bit of sense, but this particular mess is too tangled to be worth the effort :S.
Thanks, as usual, for the help
relevant code:
collection:
Imports System.IO
Imports System.Web.UI.HtmlControls
Public Class ArchivosCollection
Inherits CollectionBase
Default Public Property Item(ByVal index As Integer) As HtmlInputFile
Get
Return MyBase.List(index)
End Get
Set(ByVal Value As HtmlInputFile)
MyBase.List(index) = Value
End Set
End Property
Public Function Add(ByVal oArchivo As HtmlInputFile) As Integer
Return MyBase.List.Add(oArchivo)
End Function
Public Function getDataSource() As DataTable
Dim dt As New DataTable
Dim oArchivo As HtmlInputFile
Dim fila As DataRow
Dim orden As Integer = 0
dt.Columns.Add("documento", GetType(System.String))
dt.Columns.Add("tipo", GetType(System.String))
For Each oArchivo In list
If Not oArchivo.Disabled Then
fila = dt.NewRow()
fila("documento") = Trim(Path.GetFileName(oArchivo.PostedFile.FileName))
fila("tipo") = Trim(oArchivo.PostedFile.ContentType)
dt.Rows.Add(fila)
End If
Next
Return dt
End Function
Public Function ExisteArchivo(ByVal Nombre As String) As Boolean
For Each oArchivo As HtmlInputFile In list
If Not oArchivo.Disabled Then
If Path.GetFileName(oArchivo.PostedFile.FileName) = Nombre Then
Return True
End If
End If
Next
Return False
End Function
Public Function EliminarArchivo(ByVal Nombre As String) As Boolean
For Each oArchivo As HtmlInputFile In list
If Not oArchivo.Disabled Then
If Path.GetFileName(oArchivo.PostedFile.FileName) = Nombre Then
oArchivo.Disabled = True
Return True
End If
End If
Next
End Function
End Class
old code:
Private Sub btnAgregarDocumento_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAgregarDocumento.Click
Try
If Not (Me.fleDocumento.PostedFile Is Nothing) Then
If Trim(Me.fleDocumento.PostedFile.FileName) = "" Then
Throw New Exception(rm.GetString("errorDebeEscogerUnArchivo"))
End If
If Not Servicios.isValidUploadType(Me.fleDocumento.PostedFile.FileName, ConfigurationManager.AppSettings("Filtros Upload")) Then
Throw New Exception(rm.GetString("errorExtensionNovalida"))
End If
Dim oArchivosOT As ArchivosCollection
If Session("oArchivosOT") Is Nothing Then
oArchivosOT = New ArchivosCollection
Else
oArchivosOT = Session("oArchivosOT")
End If
If oArchivosOT.ExisteArchivo(Path.GetFileName(Me.fleDocumento.PostedFile.FileName)) Then
Throw New Exception(rm.GetString("errorArchivoYaExiste"))
End If
oArchivosOT.Add(Me.fleDocumento)
Me.dgDocumentos.DataSource = oArchivosOT.getDataSource()
Me.dgDocumentos.DataBind()
Session("oArchivosOT") = oArchivosOT
If Request.QueryString("desde") = "proy" Then
ClientScript.RegisterStartupScript(Page.GetType, "msg", "<script>window.opener.document.Form1.refGridDocs.click();</script>")
End If
Else
Throw New Exception(rm.GetString("errorDebeEscogerUnArchivo"))
End If
Catch exc As Exception
ClientScript.RegisterStartupScript(Page.GetType, "msg", Servicios.MsgBox(exc.Message))
End Try
End Sub
new code (partial):
Dim archivos As HttpFileCollection = Request.Files
Dim colArchivos As ArchivosCollection = IIf(Session("oArchivosOT") Is Nothing, New ArchivosCollection(), Session("oArchivosOT"))
Dim i
For i = 0 To archivos.Count
colArchivos.Add(DirectCast(archivos(i), HtmlInputFile))
Next
Session("oArchivosOT") = colArchivos
The PostedFile property of the HtmlInputFile object is a HttpPostedFile object - you can simply access it for each HtmlInputFile.

Cookie being deleted unexpectedly by the application

I am having an issue with a cookie that keeps getting deleted by the application. When you go into the application, if the cookie does not exist, it gets created. This works fine and everything in the cookie is stored correctly.
When I click on a link to go to another page, once everything loads completely, the cookie gets deleted from the file system. Even stranger than that, the values from the cookie remain until the browser is closed. That is the application appears to be retaining the values even though the cookie does not exist on the local file system. The next time you enter the application, the cookie is recreated so any values stored are lost.
Now, I have done some tweaking on the code to see what could be causing it. I found that I am adding the cookie to the Response object any time I make a change to the cookie. The cookie is also being added to the Response object when the page load is completed. My initial thought was that adding the cookie multiple times to the Response object could be causing the issue. I commented out the code in the page load complete event and the cookie hung around until the next postback. Then I put in some logic to keep the application from putting the cookie into the Response object more than once, and then I lost the cookie again at the same point as before.
All of the code for handling cookies is in my "base page" that all pages inherit from. The page that seems to be loosing the cookie is my search page. I am including the code from both of those pages.
BasePage.vb
Public Class BasePage
Inherits Page
#Region "attributes"
Private _cookie As HttpCookie
Private _savedCookie As Boolean
Private Const COOKIE_NAME As String = "KDOELog"
Private Const COOKIE_COLUMNS As String = "cols"
Private Const COOKIE_SEARCH_BRANCH As String = "b"
Private Const COOKIE_SEARCH_COLLECTOR As String = "c"
Private Const COOKIE_SEARCH_CONF_NUMBER As String = "a"
Private Const COOKIE_SEARCH_NA_NUMBER As String = "n"
Private Const COOKIE_SEARCH_CUST_NUMBER As String = "u"
Private Const COOKIE_SEARCH_INV_NUMBER As String = "i"
Private Const COOKIE_SEARCH_CONTRACT As String = "t"
Private Const COOKIE_SEARCH_ORDER_TYPE As String = "y"
Private Const COOKIE_SEARCH_DSR_NUMBER As String = "r"
Private Const COOKIE_SEARCH_DSM_NUMBER As String = "m"
Private Const COOKIE_SEARCH_EXCEPTION As String = "e"
Private Const COOKIE_SEARCH_START_DATE As String = "s"
Private Const COOKIE_SEARCH_END_DATE As String = "d"
Private Const COOKIE_PAGE_INDEX As String = "pg"
Private Const COOKIE_SORT_COLUMN As String = "sc"
Private Const COOKIE_SORT_DIRECTION As String = "sd"
Private Const SESSION_USER As String = "user"
#End Region
#Region "constructor"
Public Sub New()
_savedCookie = False
End Sub
#End Region
#Region "events"
Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If IsPostBack = False Then
' determines whether or not to show the link for Node Search
Dim myMaster As Food = DirectCast(Me.Master, Food)
If AuthenticatedUser.IsCorporateAdmin Or AuthenticatedUser.IsBranchAdmin Then
myMaster.ShowNodeItemLink = True
Else
myMaster.ShowNodeItemLink = False
End If
End If
End Sub
Private Sub Page_LoadComplete(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.LoadComplete
If _savedCookie = False Then Response.Cookies.Add(_cookie)
End Sub
Private Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
If IsNothing(Request.Cookies(COOKIE_NAME)) Then
_cookie = New HttpCookie(COOKIE_NAME)
_cookie.Expires = New Date(2999, 12, 31)
_cookie.Values.Add(COOKIE_COLUMNS, GetDefaultColumnList())
_cookie.Values.Add(COOKIE_SEARCH_BRANCH, String.Empty)
_cookie.Values.Add(COOKIE_SEARCH_COLLECTOR, String.Empty)
_cookie.Values.Add(COOKIE_SEARCH_CONF_NUMBER, String.Empty)
_cookie.Values.Add(COOKIE_SEARCH_NA_NUMBER, String.Empty)
_cookie.Values.Add(COOKIE_SEARCH_CUST_NUMBER, String.Empty)
_cookie.Values.Add(COOKIE_SEARCH_INV_NUMBER, String.Empty)
_cookie.Values.Add(COOKIE_SEARCH_CONTRACT, String.Empty)
_cookie.Values.Add(COOKIE_SEARCH_ORDER_TYPE, String.Empty)
_cookie.Values.Add(COOKIE_SEARCH_DSR_NUMBER, String.Empty)
_cookie.Values.Add(COOKIE_SEARCH_DSM_NUMBER, String.Empty)
_cookie.Values.Add(COOKIE_SEARCH_EXCEPTION, String.Empty)
_cookie.Values.Add(COOKIE_SEARCH_START_DATE, String.Empty)
_cookie.Values.Add(COOKIE_SEARCH_END_DATE, String.Empty)
_cookie.Values.Add(COOKIE_PAGE_INDEX, 0)
_cookie.Values.Add(COOKIE_SORT_COLUMN, "eback_datetime")
_cookie.Values.Add(COOKIE_SORT_DIRECTION, SORT_DIRECTION_ASC)
SaveCookie()
Else
_cookie = Request.Cookies(COOKIE_NAME)
End If
If IsNothing(Session(SESSION_USER)) Then Session(SESSION_USER) = New User(Context.User.Identity.Name)
End Sub
#End Region
#Region "methods"
Protected Function GetColumnList() As String()
Return Server.HtmlEncode(_cookie(COOKIE_COLUMNS)).Split(",")
End Function
Private Function GetDefaultColumnList() As String
' set the default list of columns
Dim columnList As New StringBuilder()
columnList.Append(COL_COLLECTOR).Append(",")
columnList.Append(COL_CONF_NUM).Append(",")
columnList.Append(COL_NODE_NUM).Append(",")
columnList.Append(COL_ORDER_TYPE).Append(",")
columnList.Append(COL_CUST_NUM).Append(",")
columnList.Append(COL_ERROR_IND).Append(",")
columnList.Append(COL_DSR_NUM).Append(",")
columnList.Append(COL_DSR_NAME).Append(",")
columnList.Append(COL_DSM_NUM).Append(",")
columnList.Append(COL_CONTRACT).Append(",")
columnList.Append(COL_NA_NUM).Append(",")
columnList.Append(COL_NA_SUB).Append(",")
columnList.Append(COL_INV_NUM).Append(",")
columnList.Append(COL_CONF_DATE).Append(",")
columnList.Append(COL_LINE_ITEMS).Append(",")
columnList.Append(COL_DELV_DATE).Append(",")
columnList.Append(COL_SALES_AMT).Append(",")
columnList.Append(COL_BRANCH)
Return columnList.ToString()
End Function
Protected Function HasSearchValues() As Boolean
Return CBool(_cookie(COOKIE_SEARCH_BRANCH) > String.Empty Or _
_cookie(COOKIE_SEARCH_COLLECTOR) > String.Empty Or _
_cookie(COOKIE_SEARCH_CONF_NUMBER) > String.Empty Or _
_cookie(COOKIE_SEARCH_NA_NUMBER) > String.Empty Or _
_cookie(COOKIE_SEARCH_CUST_NUMBER) > String.Empty Or _
_cookie(COOKIE_SEARCH_INV_NUMBER) > String.Empty Or _
_cookie(COOKIE_SEARCH_CONTRACT) > String.Empty Or _
_cookie(COOKIE_SEARCH_ORDER_TYPE) > String.Empty Or _
_cookie(COOKIE_SEARCH_DSR_NUMBER) > String.Empty Or _
_cookie(COOKIE_SEARCH_DSM_NUMBER) > String.Empty Or _
_cookie(COOKIE_SEARCH_EXCEPTION) > String.Empty Or _
_cookie(COOKIE_SEARCH_START_DATE) > String.Empty Or _
_cookie(COOKIE_SEARCH_END_DATE) > String.Empty)
End Function
Protected Sub ResetSearchValues()
_cookie(COOKIE_SEARCH_BRANCH) = String.Empty
_cookie(COOKIE_SEARCH_COLLECTOR) = String.Empty
_cookie(COOKIE_SEARCH_CONF_NUMBER) = String.Empty
_cookie(COOKIE_SEARCH_NA_NUMBER) = String.Empty
_cookie(COOKIE_SEARCH_CUST_NUMBER) = String.Empty
_cookie(COOKIE_SEARCH_INV_NUMBER) = String.Empty
_cookie(COOKIE_SEARCH_CONTRACT) = String.Empty
_cookie(COOKIE_SEARCH_ORDER_TYPE) = String.Empty
_cookie(COOKIE_SEARCH_DSR_NUMBER) = String.Empty
_cookie(COOKIE_SEARCH_DSM_NUMBER) = String.Empty
_cookie(COOKIE_SEARCH_EXCEPTION) = String.Empty
_cookie(COOKIE_SEARCH_START_DATE) = String.Empty
_cookie(COOKIE_SEARCH_END_DATE) = String.Empty
_cookie(COOKIE_PAGE_INDEX) = 0
_cookie(COOKIE_SORT_COLUMN) = "eback_datetime"
_cookie(COOKIE_SORT_DIRECTION) = SORT_DIRECTION_ASC
SaveCookie()
End Sub
Protected Sub SaveCookie()
If _savedCookie = False Then
Response.Cookies.Add(_cookie)
_savedCookie = True
End If
End Sub
Protected Sub SetColumnList(ByVal ColumnList As String)
_cookie(COOKIE_COLUMNS) = ColumnList
SaveCookie()
End Sub
#End Region
#Region "properties"
Public ReadOnly Property AuthenticatedUser() As User
Get
If IsNothing(Session(SESSION_USER)) Then Session(SESSION_USER) = New User(Context.User.Identity.Name)
Return DirectCast(Session(SESSION_USER), User)
End Get
End Property
Public ReadOnly Property UserName() As String
Get
Return Context.User.Identity.Name
End Get
End Property
Public Property SearchBranch() As String
Get
Return _cookie(COOKIE_SEARCH_BRANCH)
End Get
Set(ByVal value As String)
_cookie(COOKIE_SEARCH_BRANCH) = value
End Set
End Property
Public Property SearchCollector() As String
Get
Return _cookie(COOKIE_SEARCH_COLLECTOR)
End Get
Set(ByVal value As String)
_cookie(COOKIE_SEARCH_COLLECTOR) = value
End Set
End Property
Public Property SearchConfirmationNumber() As String
Get
Return _cookie(COOKIE_SEARCH_CONF_NUMBER)
End Get
Set(ByVal value As String)
_cookie(COOKIE_SEARCH_CONF_NUMBER) = value
End Set
End Property
Public Property SearchNationalAccountNumber() As String
Get
Return _cookie(COOKIE_SEARCH_NA_NUMBER)
End Get
Set(ByVal value As String)
_cookie(COOKIE_SEARCH_NA_NUMBER) = value
End Set
End Property
Public Property SearchCustomerNumber() As String
Get
Return _cookie(COOKIE_SEARCH_CUST_NUMBER)
End Get
Set(ByVal value As String)
_cookie(COOKIE_SEARCH_CUST_NUMBER) = value
End Set
End Property
Public Property SearchInvoiceNumber() As String
Get
Return _cookie(COOKIE_SEARCH_INV_NUMBER)
End Get
Set(ByVal value As String)
_cookie(COOKIE_SEARCH_INV_NUMBER) = value
End Set
End Property
Public Property SearchContract() As String
Get
Return _cookie(COOKIE_SEARCH_CONTRACT)
End Get
Set(ByVal value As String)
_cookie(COOKIE_SEARCH_CONTRACT) = value
End Set
End Property
Public Property SearchOrderType() As String
Get
Return _cookie(COOKIE_SEARCH_ORDER_TYPE)
End Get
Set(ByVal value As String)
_cookie(COOKIE_SEARCH_ORDER_TYPE) = value
End Set
End Property
Public Property SearchDsrNumber() As String
Get
Return _cookie(COOKIE_SEARCH_DSR_NUMBER)
End Get
Set(ByVal value As String)
_cookie(COOKIE_SEARCH_DSR_NUMBER) = value
End Set
End Property
Public Property SearchDsmNumber() As String
Get
Return _cookie(COOKIE_SEARCH_DSM_NUMBER)
End Get
Set(ByVal value As String)
_cookie(COOKIE_SEARCH_DSM_NUMBER) = value
End Set
End Property
Public Property SearchErrorType() As String
Get
Return _cookie(COOKIE_SEARCH_EXCEPTION)
End Get
Set(ByVal value As String)
_cookie(COOKIE_SEARCH_EXCEPTION) = value
End Set
End Property
Public Property SearchStartDate() As String
Get
Return _cookie(COOKIE_SEARCH_START_DATE)
End Get
Set(ByVal value As String)
_cookie(COOKIE_SEARCH_START_DATE) = value
End Set
End Property
Public Property SearchEndDate() As String
Get
Return _cookie(COOKIE_SEARCH_END_DATE)
End Get
Set(ByVal value As String)
_cookie(COOKIE_SEARCH_END_DATE) = value
End Set
End Property
Public Property PageIndex() As String
Get
Return _cookie(COOKIE_PAGE_INDEX)
End Get
Set(ByVal value As String)
_cookie(COOKIE_PAGE_INDEX) = value
End Set
End Property
Public Property SortColumn() As String
Get
Return _cookie(COOKIE_SORT_COLUMN)
End Get
Set(ByVal value As String)
_cookie(COOKIE_SORT_COLUMN) = value
End Set
End Property
Public Property SortDirection() As String
Get
Return _cookie(COOKIE_SORT_DIRECTION)
End Get
Set(ByVal value As String)
_cookie(COOKIE_SORT_DIRECTION) = value
End Set
End Property
#End Region
End Class
Search.aspx.vb
Public Partial Class Search
Inherits BasePage
#Region "attributes"
#End Region
#Region "events"
Private Sub btnColumnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnColumnSave.Click
Dim columns As New StringBuilder
If chkCollector.Checked Then columns.Append(COL_COLLECTOR).Append(",")
If chkAckNumber.Checked Then columns.Append(COL_CONF_NUM).Append(",")
If chkNodeNumber.Checked Then columns.Append(COL_NODE_NUM).Append(",")
If chkOrderType.Checked Then columns.Append(COL_ORDER_TYPE).Append(",")
If chkCustNumber.Checked Then columns.Append(COL_CUST_NUM).Append(",")
If chkCustName.Checked Then columns.Append(COL_CUST_NAME).Append(",")
If chkOrderExceptions.Checked Then columns.Append(COL_ERROR_IND).Append(",")
If chkDsrNumber.Checked Then columns.Append(COL_DSR_NUM).Append(",")
If chkDsrName.Checked Then columns.Append(COL_DSR_NAME).Append(",")
If chkDsmNumber.Checked Then columns.Append(COL_DSM_NUM).Append(",")
If chkDsmName.Checked Then columns.Append(COL_DSM_NAME).Append(",")
If chkContract.Checked Then columns.Append(COL_CONTRACT).Append(",")
If chkNationalAcct.Checked Then columns.Append(COL_NA_NUM).Append(",")
If chkNatAcctSub.Checked Then columns.Append(COL_NA_SUB).Append(",")
If chkInvoiceNumber.Checked Then columns.Append(COL_INV_NUM).Append(",")
If chkAckDateTime.Checked Then columns.Append(COL_CONF_DATE).Append(",")
If chkLineItem.Checked Then columns.Append(COL_LINE_ITEMS).Append(",")
If chkDeliveryDate.Checked Then columns.Append(COL_DELV_DATE).Append(",")
If chkSalesAmount.Checked Then columns.Append(COL_SALES_AMT).Append(",")
If chkBranch.Checked Then columns.Append(COL_BRANCH).Append(",")
' remove the last comma from the list
columns = columns.Remove(columns.Length - 1, 1)
SetColumnList(columns.ToString())
SaveCookie()
ManageGridColumns()
End Sub
Private Sub btnEndDate_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnEndDate.Click
calEndDate.Visible = Not calEndDate.Visible
If calEndDate.Visible Then
Try
calEndDate.SelectedDate = Date.Parse(txtEndDate.Text)
Catch
calEndDate.SelectedDate = Now
End Try
End If
modSearch.Show()
End Sub
Private Sub btnSearchReset_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearchReset.Click
ddlBranch.SelectedIndex = 0
SearchBranch = ddlBranch.SelectedValue
ddlCollectorType.SelectedIndex = 0
SearchCollector = ddlCollectorType.SelectedValue
ddlOrderType.SelectedIndex = 0
SearchOrderType = ddlOrderType.SelectedValue
ddlErrorCode.SelectedIndex = 0
SearchErrorType = ddlErrorCode.SelectedValue
SearchConfirmationNumber = String.Empty
SearchNationalAccountNumber = String.Empty
SearchCustomerNumber = String.Empty
SearchInvoiceNumber = String.Empty
SearchContract = String.Empty
SearchDsrNumber = String.Empty
'SearchDsmNumber = String.Empty
SetDsmInfo()
SearchStartDate = Now.ToShortDateString()
SearchEndDate = Now.ToShortDateString()
SaveCookie()
SetSearchWindow()
modSearch.Show()
End Sub
Private Sub btnSearchSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearchSearch.Click
SearchBranch = ddlBranch.SelectedValue
SearchCollector = ddlCollectorType.SelectedValue
SearchConfirmationNumber = txtAckNumber.Text
SearchCustomerNumber = txtCustomerNumber.Text
SearchInvoiceNumber = txtInvoiceNumber.Text
SearchDsrNumber = txtDsrNumber.Text
SearchDsmNumber = txtDsmNumber.Text
SearchNationalAccountNumber = txtNationalAccountNumber.Text
SearchContract = txtContract.Text
SearchErrorType = ddlErrorCode.SelectedValue
SearchOrderType = ddlOrderType.SelectedValue
SearchStartDate = txtStartDate.Text
SearchEndDate = txtEndDate.Text
SaveCookie()
PageIndex = 0
dgResults.CurrentPageIndex = 0
BindResults()
End Sub
Private Sub btnStartDate_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnStartDate.Click
calStartDate.Visible = Not calStartDate.Visible
If calStartDate.Visible Then
Try
calStartDate.SelectedDate = Date.Parse(txtStartDate.Text)
Catch
calStartDate.SelectedDate = Now
End Try
End If
modSearch.Show()
End Sub
Private Sub calEndDate_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles calEndDate.SelectionChanged
txtEndDate.Text = calEndDate.SelectedDate.ToShortDateString()
calEndDate.Visible = False
modSearch.Show()
End Sub
Private Sub calStartDate_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles calStartDate.SelectionChanged
txtStartDate.Text = calStartDate.SelectedDate.ToShortDateString()
calStartDate.Visible = False
modSearch.Show()
End Sub
Private Sub dgResults_PageIndexChanged(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridPageChangedEventArgs) Handles dgResults.PageIndexChanged
PageIndex = e.NewPageIndex
dgResults.CurrentPageIndex = e.NewPageIndex
BindResults()
End Sub
Private Sub dgResults_SortCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridSortCommandEventArgs) Handles dgResults.SortCommand
If SortColumn.Equals(e.SortExpression) Then
If SortDirection = SORT_DIRECTION_ASC Then
SortDirection = SORT_DIRECTION_DESC
Else
SortDirection = SORT_DIRECTION_ASC
End If
Else
SortColumn = e.SortExpression
SortDirection = SORT_DIRECTION_ASC
End If
PageIndex = 0
dgResults.CurrentPageIndex = 0
BindResults()
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If IsPostBack = False Then
SetDsmInfo()
txtStartDate.Text = Now.ToShortDateString()
txtEndDate.Text = Now.ToShortDateString()
BindBranches()
BindCollectorTypes()
BindTransmissionTypes()
BindErrorCodes()
SetupColumnWindow()
ManageGridColumns()
If HasSearchValues() Then
SetSearchWindow()
dgResults.CurrentPageIndex = CInt(PageIndex)
BindResults()
Else
modSearch.Show()
End If
End If
End Sub
#End Region
#Region "methods"
Private Sub BindBranches()
If AuthenticatedUser.IsCorporateAdmin Then
Dim branches As New BranchCollection
branches.Load()
ddlBranch.DataSource = branches
ddlBranch.DataTextField = "BranchDescription"
ddlBranch.DataValueField = "BranchName"
ddlBranch.DataBind()
Else
Dim myBranch As New Branch(AuthenticatedUser.Division)
ddlBranch.Items.Clear()
ddlBranch.Items.Add(New ListItem(myBranch.BranchDescription, myBranch.BranchName))
ddlBranch.Enabled = False
End If
End Sub
Private Sub BindCollectorTypes()
Dim types As New OrderTypeCollection
types.Load()
ddlCollectorType.DataSource = types
ddlCollectorType.DataTextField = "eb_order_description"
ddlCollectorType.DataValueField = "eb_order_type"
ddlCollectorType.DataBind()
End Sub
Private Sub BindErrorCodes()
Dim codes As New KDOE_Library.BusinessLayer.ErrorTypeCollection
codes.Load()
ddlErrorCode.DataSource = codes
ddlErrorCode.DataTextField = "eb_error_desc"
ddlErrorCode.DataValueField = "eb_error_type"
ddlErrorCode.DataBind()
End Sub
Private Sub BindResults()
Dim results As New ConfirmationHeaderCollection()
results.Search(SearchCollector, SearchConfirmationNumber, SearchBranch, SearchCustomerNumber, SearchInvoiceNumber, _
SearchDsrNumber, SearchDsmNumber, SearchNationalAccountNumber, SearchContract, SearchErrorType, _
SearchOrderType, SearchStartDate, SearchEndDate)
results.SortExpression = TranslateSortExpression(SortColumn)
results.SortDirection = IIf(SortDirection.Equals(SORT_DIRECTION_ASC), _
ConfirmationHeaderCollection.SortOrder.Ascending, _
ConfirmationHeaderCollection.SortOrder.Descending)
results.Sort(results)
dgResults.DataSource = results
dgResults.DataBind()
lblResultCount.Text = String.Format("{0} records found", results.Count.ToString("#,###,###"))
End Sub
Private Sub BindTransmissionTypes()
Dim transTypes As New TransTypeCollection
transTypes.Load()
ddlOrderType.DataSource = transTypes
ddlOrderType.DataTextField = "eb_trans_desc"
ddlOrderType.DataValueField = "eb_trans_type"
ddlOrderType.DataBind()
End Sub
Private Sub HideAllColumns()
For i As Integer = 0 To dgResults.Columns.Count - 1
dgResults.Columns(i).Visible = False
Next
End Sub
Private Sub ManageGridColumns()
HideAllColumns()
Dim columns() As String = GetColumnList()
For i As Integer = 0 To columns.Length - 1
Try
dgResults.Columns(CInt(columns(i))).Visible = True
Catch
' do nothing if an error is detected because it indicates a dirty cookie
End Try
Next
End Sub
Private Sub SetupColumnWindow()
Dim columns() As String = GetColumnList()
For i As Integer = 0 To columns.Length - 1
Try
Select Case CInt(columns(i))
Case COL_COLLECTOR
chkCollector.Checked = True
Case COL_CONF_NUM
chkAckNumber.Checked = True
Case COL_NODE_NUM
chkNodeNumber.Checked = True
Case COL_ORDER_TYPE
chkOrderType.Checked = True
Case COL_CUST_NUM
chkCustNumber.Checked = True
Case COL_CUST_NAME
chkCustName.Checked = True
Case COL_ERROR_IND
chkOrderExceptions.Checked = True
Case COL_DSR_NUM
chkDsrNumber.Checked = True
Case COL_DSR_NAME
chkDsrName.Checked = True
Case COL_DSM_NUM
chkDsmNumber.Checked = True
Case COL_DSM_NAME
chkDsmName.Checked = True
Case COL_CONTRACT
chkContract.Checked = True
Case COL_NA_NUM
chkNationalAcct.Checked = True
Case COL_NA_SUB
chkNatAcctSub.Checked = True
Case COL_INV_NUM
chkInvoiceNumber.Checked = True
Case COL_CONF_DATE
chkAckDateTime.Checked = True
Case COL_LINE_ITEMS
chkLineItem.Checked = True
Case COL_DELV_DATE
chkDeliveryDate.Checked = True
Case COL_SALES_AMT
chkSalesAmount.Checked = True
Case COL_BRANCH
chkBranch.Checked = True
Case Else
' do nothing
End Select
Catch
' do nothing because the entry is not an actual column number
' i.e. the cookie has dirty data
End Try
Next
End Sub
Private Sub SetDsmInfo()
If AuthenticatedUser.IsDsm Then
Dim theService As New DsmService.DsmService
theService.PreAuthenticate = True
theService.Credentials = New System.Net.NetworkCredential("someuser", "somepassword", "somedomain")
Dim myDsm As DsmService.Dsm = theService.GetDsmByName(AuthenticatedUser.FirstName, AuthenticatedUser.LastName)
If IsPostBack Then
SearchDsmNumber = myDsm.DsmNumber
Else
txtDsmNumber.Text = myDsm.DsmNumber
End If
txtDsmNumber.Enabled = False
Else
'txtDsmNumber.Text = String.Empty
SearchDsmNumber = String.Empty
txtDsmNumber.Enabled = True
End If
End Sub
Private Sub SetSearchWindow()
Try
ddlBranch.SelectedValue = SearchBranch
ddlCollectorType.SelectedValue = SearchCollector
txtAckNumber.Text = SearchConfirmationNumber
txtNationalAccountNumber.Text = SearchNationalAccountNumber
txtCustomerNumber.Text = SearchCustomerNumber
txtInvoiceNumber.Text = SearchInvoiceNumber
txtContract.Text = SearchContract
ddlOrderType.SelectedValue = SearchOrderType
txtDsrNumber.Text = SearchDsrNumber
txtDsmNumber.Text = SearchDsmNumber
ddlErrorCode.SelectedValue = SearchErrorType
txtStartDate.Text = SearchStartDate
calStartDate.SelectedDate = CDate(SearchStartDate)
txtEndDate.Text = SearchEndDate
calEndDate.SelectedDate = CDate(SearchEndDate)
Catch
' do nothing because an error would be caused by dirty data from the cookie
End Try
End Sub
Private Function TranslateSortExpression(ByVal SortExpression As String) As ConfirmationHeaderCollection.SortColumn
Dim retVal As ConfirmationHeaderCollection.SortColumn = ConfirmationHeaderCollection.SortColumn.eback_datetime
Select Case SortExpression
Case "ebcollector"
retVal = ConfirmationHeaderCollection.SortColumn.ebcollector
Case "eback"
retVal = ConfirmationHeaderCollection.SortColumn.eback
Case "ebnode"
retVal = ConfirmationHeaderCollection.SortColumn.ebnode
Case "ebordertype"
retVal = ConfirmationHeaderCollection.SortColumn.ebordertype
Case "ebcust"
retVal = ConfirmationHeaderCollection.SortColumn.ebcust
Case "CustomerName"
retVal = ConfirmationHeaderCollection.SortColumn.CustomerName
Case "eberror"
retVal = ConfirmationHeaderCollection.SortColumn.eberror
Case "ebslm"
retVal = ConfirmationHeaderCollection.SortColumn.ebslm
Case "DsrName"
retVal = ConfirmationHeaderCollection.SortColumn.DsrName
Case "DsmNumber"
retVal = ConfirmationHeaderCollection.SortColumn.DsmNumber
Case "DsmName"
retVal = ConfirmationHeaderCollection.SortColumn.DsmName
Case "ebcontract"
retVal = ConfirmationHeaderCollection.SortColumn.ebcontract
Case "ebna"
retVal = ConfirmationHeaderCollection.SortColumn.ebna
Case "ebnasub"
I think that I have found the answer. The cookie hasn't been removed in a while, so this looks like it. I tried several other things trying to find the issue, and I had finally given up on finding the solution by tweaking my code, so I took to the internet. It was on MS's website that I found this little gem.
If you do not set the cookie's expiration, the cookie is created but it is not stored on the user's hard disk. Instead, the cookie is maintained as part of the user's session information. When the user closes the browser, the cookie is discarded. A non-persistent cookie like this is useful for information that needs to be stored for only a short time or that for security reasons should not be written to disk on the client computer. For example, non-persistent cookies are useful if the user is working on a public computer, where you do not want to write the cookie to disk.
http://msdn.microsoft.com/en-us/library/ms178194.aspx
So the issue here is the fact that the cookie has an expiration date when the cookie is initially created. However, reading the cookie from the Request object does not include the expiration date. So, I fixed it by setting the expiration date before adding the cookie back to the Response object.

Resources