ASP.NET - can't insert data and hours in database (dataset) - asp.net

I'm creating an application where people can insert an event with information such as eventname, location, date, hours, ...
There are 3 steps. the first 2 steps with the inserts were succesfully inserted. But at step 3 where they have to insert a startDay (Startdag), endDay(Einddag), starthour(startUurt), endHour(eindUur) I can't get it fixed.
In the presentationlayer I'm using the calendarExtender for Startday and Endday with format d MMMM yyyy with and target txt_sDag and txt_eDag
In dataset "DAL_Planit3.xsd" I've given endDay and startDay as type "datetime" and startHour and endHour as type String (becoz we will only read it, we won't be doing anything with it).
Can someone please help me?
StepThree.aspx.vb
Protected Sub btn_next_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_next.Click
Try
Dim BLLdata As New BLL_Data
Dim eventID As Integer = Session.Item("eventID")
Dim plaatsID As Integer = Session.Item("plaatsID")
Dim data As New CL_Data
data.Einddag = txt_eDag.Text
data.Startdag = CDate(txt_sDag.Text)
data.Einddag = CDate(txt_eDag.Text)
data.Einduur = txt_eUur.Text
data.StartUur = txt_sUur.Text
data.FKEvenementId = eventID
data.FKPlaatsId = plaatsID
BLLdata.insertData(data)
lbl_feedback.Text = "Data succesful inserted!"
Catch ex As Exception
lbl_feedback.Text = "Data not inserted! " + ex.Message
End Try
End Sub
End Class
*BLL_Data.vb*
' INSERT DATA
Public Function insertData(ByVal data As CL_Data) As String
Dim feedback As String = Nothing
Try
adapterDatum3.Insert(data.Startdag, data.Einddag, data.StartUur, data.Einduur, data.FKPlaatsId, data.FKEvenementId)
'adapterDatum.Insert(data.Startdag, data.Einddag, data.StartUur, data.Einduur, data.FKPlaatsId, data.FKEvenementId)
feedback = "Data is toegevoegd"
Catch ex As Exception
feedback = ex.Message
End Try
Return feedback
End Function
CL_Data
Public Class CL_Data
Private iDataId As Integer
Public Property DataID() As Integer
Get
Return iDataId
End Get
Set(ByVal value As Integer)
iDataId = value
End Set
End Property
Private dStartDag As Date
Public Property Startdag() As Date
Get
Return dStartDag
End Get
Set(ByVal value As Date)
dStartDag = value
End Set
End Property
Private dEindDag As Date
Public Property Einddag() As Date
Get
Return dEindDag
End Get
Set(ByVal value As Date)
dEindDag = value
End Set
End Property
Private tStartUur As String
Public Property StartUur() As String
Get
Return tStartUur
End Get
Set(ByVal value As String)
tStartUur = value
End Set
End Property
Private tEindUur As String
Public Property Einduur() As String
Get
Return tEindUur
End Get
Set(ByVal value As String)
tEindUur = value
End Set
End Property
Private iFKPlaatsId As Integer
Public Property FKPlaatsId() As Integer
Get
Return iFKPlaatsId
End Get
Set(ByVal value As Integer)
iFKPlaatsId = value
End Set
End Property
Private iFKEvenementId As Integer
Public Property FKEvenementId() As Integer
Get
Return iFKEvenementId
End Get
Set(ByVal value As Integer)
iFKEvenementId = value
End Set
End Property
End Class

Related

asp.net web service error on production and not locally

Hope i am posting in the right area!
I have an asp.net/vb web service, built in VS2012. The project is running locally under .net 4.0 but the project was created to use .net 2.0 as that is what the production server runs.
The web service runs fine locally, but on the production server, I get an error (i hope the formatting works):-
BC30068: Expression is a value and therefore cannot be the target of an assignment.
This is my function and properties:-
Public Class JobData
Private m_ID As Integer
Public Property ID() As Integer
Get
Return m_ID
End Get
Set(value As Integer)
m_ID = value
End Set
End Property
Private m_MAID As Integer
Public Property MAID() As Integer
Get
Return m_MAID
End Get
Set(value As Integer)
m_MAID = value
End Set
End Property
Private m_DateAdded As DateTime
Public Property DateAdded() As DateTime
Get
Return m_DateAdded
End Get
Set(value As DateTime)
m_DateAdded = value
End Set
End Property
Private m_ClientID As Integer
Public Property ClientID() As Integer
Get
Return m_ClientID
End Get
Set(value As Integer)
m_ClientID = value
End Set
End Property
Private m_JobRef As String
Public Property JobRef() As String
Get
Return m_JobRef
End Get
Set(value As String)
m_JobRef = value
End Set
End Property
Private m_JobTitle As String
Public Property JobTitle() As String
Get
Return m_JobTitle
End Get
Set(value As String)
m_JobTitle = value
End Set
End Property
Private m_Location As String
Public Property Location() As String
Get
Return m_Location
End Get
Set(value As String)
m_Location = value
End Set
End Property
Private m_JobType As String
Public Property JobType() As String
Get
Return m_JobType
End Get
Set(value As String)
m_JobType = value
End Set
End Property
Private m_Salary As String
Public Property Salary() As String
Get
Return m_Salary
End Get
Set(value As String)
m_Salary = value
End Set
End Property
Private m_SalaryTerm As String
Public Property SalaryTerm() As String
Get
Return m_SalaryTerm
End Get
Set(value As String)
m_SalaryTerm = value
End Set
End Property
Private m_BriefDescription As String
Public Property BriefDescription() As String
Get
Return m_BriefDescription
End Get
Set(value As String)
m_BriefDescription = value
End Set
End Property
Private m_MoreDetails As String
Public Property MoreDetails() As String
Get
Return m_MoreDetails
End Get
Set(value As String)
m_MoreDetails = value
End Set
End Property
Private m_DetailsDocument As String
Public Property DetailsDocument() As String
Get
Return m_DetailsDocument
End Get
Set(value As String)
m_DetailsDocument = value
End Set
End Property
Private m_ClosingDate As DateTime
Public Property ClosingDate() As DateTime
Get
Return m_ClosingDate
End Get
Set(value As DateTime)
m_ClosingDate = value
End Set
End Property
Private m_CompanyName As String
Public Property CompanyName() As String
Get
Return m_CompanyName
End Get
Set(value As String)
m_CompanyName = value
End Set
End Property
' User for HTML
Public Property HTMLData() As String
Get
Return m_Data
End Get
Set(value As String)
m_Data = value
End Set
End Property
Private m_Data As String
End Class
Public Class JobBoard
Public Property Name() As String
Get
Return m_Name
End Get
Set(value As String)
m_Name = value
End Set
End Property
Private m_Name As String
Public Property WSID() As String
Get
Return m_WSID
End Get
Set(value As String)
m_WSID = value
End Set
End Property
Private m_WSID As String
Public Property JobDetails() As List(Of JobData)
Get
Return m_JobDetails
End Get
Set(value As List(Of JobData))
m_JobDetails = value
End Set
End Property
Private m_JobDetails As List(Of JobData)
End Class
Public Shared Function getJobsForWSID(ByVal wsid As String, ByRef mj As JobBoard) As JobBoard
Dim mysql As String = RWP.OtherFormats.masterSelect(wsid).ToString.Trim
' HttpContext.Current.Response.Write(mysql) : HttpContext.Current.Response.End()
Dim Conn As New MySqlConnection(dbconn)
Dim da As New MySqlDataAdapter(mysql, Conn)
Dim dt As New DataTable
Conn.Open()
da.Fill(dt)
Dim mytask As DataRow() = dt.[Select]
If dt.Rows.Count > 0 Then
For Each dr As DataRow In mytask
' THIS LINE CAUSES THE ERROR
mj.JobDetails.Add(New JobData() With {.ID = dr("id"), .MAID = dr("master_agency_id"), .DateAdded = dr("date_added"), .ClientID = dr("client_id"), .JobRef = ts(dr("job_ref")), .JobTitle = ts(dr("job_title")), .Location = ts(dr("location")), .JobType = ts(dr("job_type")), .Salary = ts(dr("salary")), .SalaryTerm = ts(dr("salary_term")), .BriefDescription = ts(dr("brief_desc")), .MoreDetails = ts(dr("more_details")), .DetailsDocument = ts(dr("details_document")), .ClosingDate = dr("closing_date"), .CompanyName = dr("company_name")})
Next
End If
da = Nothing
Conn.Close()
Conn.Dispose()
Conn = Nothing
dt = Nothing
Return mj
End Function
This is the compiler output:-
D:\inetpub\vhosts\api.rankcareers.co.uk\httpdocs\App_Code\acesapiws1.vb(254) : error BC30068: Expression is a value and therefore cannot be the target of an assignment.
mj.JobDetails.Add(New JobData() With {.ID = dr("id"), .MAID = dr("master_agency_id"), .DateAdded = dr("date_added"), .ClientID = dr("client_id"), .JobRef = ts(dr("job_ref")), .JobTitle = ts(dr("job_title")), .Location = ts(dr("location")), .JobType = ts(dr("job_type")), .Salary = ts(dr("salary")), .SalaryTerm = ts(dr("salary_term")), .BriefDescription = ts(dr("brief_desc")), .MoreDetails = ts(dr("more_details")), .DetailsDocument = ts(dr("details_document")), .ClosingDate = dr("closing_date"), .CompanyName = dr("company_name")})
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
D:\inetpub\vhosts\api.rankcareers.co.uk\httpdocs\App_Code\acesapiws1.vb(254) : error BC32017: Comma, ')', or a valid expression continuation expected.
mj.JobDetails.Add(New JobData() With {.ID = dr("id"), .MAID = dr("master_agency_id"), .DateAdded = dr("date_added"), .ClientID = dr("client_id"), .JobRef = ts(dr("job_ref")), .JobTitle = ts(dr("job_title")), .Location = ts(dr("location")), .JobType = ts(dr("job_type")), .Salary = ts(dr("salary")), .SalaryTerm = ts(dr("salary_term")), .BriefDescription = ts(dr("brief_desc")), .MoreDetails = ts(dr("more_details")), .DetailsDocument = ts(dr("details_document")), .ClosingDate = dr("closing_date"), .CompanyName = dr("company_name")})
Can anyone suggest why this would be?

Convert string to list of custom objects

Say I have an object Fish with properties like
Public Property ID As Integer
Public Property Name As String
Public Property Type As Integer
Public Property Age As Integer
And I have a string that looks like this:
"Fishes[0].ID=1&Fishes[0].Name=Fred&Fishes[0].Type=1&Fishes[0].Age=3&Fishes[1].ID=2&Fishes[1].Name=George&Fishes[1].Type=2&Fishes[1].Age=5&..."
Is there any way of converting/casting/whatever my string into a list of Fish objects? I can't seem to find anything to help. I do have some control over the format of the string if that would make things easier.
Many thanks
What you need to do is to parse the input string to look for Fishes[X].PROPNAME=VALUE pattern. Loop through all matches found in the string and add into or set the existing object in Dictionary. Use X as each object key in the Dictionary.
Create Fish structure:
Structure Fish
Public ID As String
Public Name As String
Public Type As Integer
Public Age As Integer
End Structure
Codes to process the input string:
Dim Fishes As New Dictionary(Of String, Fish)
Dim m As Match = Regex.Match(str, "Fishes\[(?<key>\d+)]\.(?<prop>.+?)=(?<value>[^&]+)", RegexOptions.IgnoreCase)
Do While m.Success
Dim key As String = m.Groups("key").Value.Trim.ToUpper
Dim prop As String = m.Groups("prop").Value.Trim.ToUpper
Dim value As String = m.Groups("value").Value
' if the key not yet exist in the Dictionary, create and add into it.
If Not Fishes.ContainsKey(key) Then
Fishes.Add(key, New Fish)
End If
Dim thisFish As Fish = Fishes(key) ' get the Fish object for this key
' determine the object property to set
Select Case prop
Case "ID" : thisFish.ID = value
Case "NAME" : thisFish.Name = value
Case "TYPE" : thisFish.Type = CInt(value)
Case "AGE" : thisFish.Age = CInt(value)
End Select
Fishes(key) = thisFish ' since the Fish object is declared as Structure,
' update the Dictionary item of key with the modified object.
' If Fish is declared as Class, then this line is useless
m = m.NextMatch()
Loop
Try this ..
Structure Test
Dim ID As String
Dim Name As String
Dim Type As Integer
Dim Age As Integer
End Structure
In your Button click event ..
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim Fishes As New List(Of Test)
Dim Fish As New Test
Fish.ID = "GF"
Fish.Name = "Gold Fish"
Fish.Age = 1
Fish.Type = 1
Fishes.Add(Fish)
MsgBox(Fishes(0).Name)
End Sub
this is vb.net converted
Public Partial Class test
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs)
If Not IsPostBack Then
End If
End Sub
Public Sub MYtest()
Dim ls As New List(Of Fish)()
Dim f As New Fish()
f.ID = 1
f.Name = "My name"
f.Type = "My type"
f.Age = 20
ls.Add(f)
End Sub
End Class
Public Class Fish
Public Property ID() As Integer
Get
Return m_ID
End Get
Set
m_ID = Value
End Set
End Property
Private m_ID As Integer
Public Property Name() As String
Get
Return m_Name
End Get
Set
m_Name = Value
End Set
End Property
Private m_Name As String
Public Property Type() As String
Get
Return m_Type
End Get
Set
m_Type = Value
End Set
End Property
Private m_Type As String
Public Property Age() As Integer
Get
Return m_Age
End Get
Set
m_Age = Value
End Set
End Property
Private m_Age As Integer
End Class
In the comments you mentioned that this is via ASP.Net MVC. The ModelBinder will do everything for you.
public ActionResult UpdateFish(IList<Fish> listOfFish)
{
//the ModelBinder will figure out that the user has posted a list of Fish instances.
//do something with listOfFish
return View(listOfFish);
}

Looking for a Full S.DS.AM Sample with many AD extensions already written

System.DirectoryServices.AccountManagement can be extended to support additional properties for reading and writing AD properties.
Is anyone aware of a full/complete sample implementation that works for AD, Exchange 2003 or 2010?
There isn't anything online that I know of, but you are welcome to my collection (which I've included).
One thing you'll probably notice about my code is that I've almost completely replaced the standard get/set operations with my own code which writes directly to the underlying DirectoryEntry. This is because the built in set operation is not designed to handle data types which are arrays of arrays (such as the jpegPhoto attribute which is an array of byte arrays, with each byte array representing a picture).
First is a bunch of extension methods which I use for my various get/set operations.
''' <summary>
''' Checks if an attribute is available on the underlying object.
''' </summary>
<Extension()> _
Public Function IsAttributeDefined(ByVal prin As Principal, ByVal attribute As String) As Boolean
'since some attributes may not exist in all schemas check to see if it exists first
Dim uo As DirectoryEntry = DirectCast(prin.GetUnderlyingObject(), DirectoryEntry)
'check for property, if it's not found return an empty array
Return uo.Properties.Contains(attribute)
End Function
#Region "Get Helpers"
''' <summary>
''' This function is the foundation for retrieving data
''' </summary>
<Extension()> _
Public Function ExtensionGetAttributeObject(ByVal prin As Principal, ByVal attribute As String) As Object()
'check if the attribute exists on this object
If IsAttributeDefined(prin, attribute) Then
'if property exists then return the data
Dim dirObj As DirectoryEntry = prin.GetUnderlyingObject()
Dim val As Object() = (From c As Object In dirObj.Properties(attribute) Select c).ToArray()
Return val
Else
'return an empty array if the attribute is not defined
Return New Object(-1) {}
End If
End Function
''' <summary>
''' This is the primary function for retrieving attributes that contain only one value
''' </summary>
<Extension()> _
Public Function ExtensionGetSingleValue(ByVal prin As Principal, ByVal attribute As String) As Object
'get the object
Dim attributeValues() As Object = ExtensionGetAttributeObject(prin, attribute)
'if the item length = 1 then return the first value, else don't
If attributeValues.Length = 1 Then
Return attributeValues(0)
Else
Return Nothing
End If
End Function
''' <summary>
''' Returns the string value of an attribute
''' </summary>
''' <remarks>(null if no value found)</remarks>
<Extension()> _
Public Function ExtensionGetSingleString(ByVal prin As Principal, ByVal attribute As String) As String
Dim o As Object = ExtensionGetSingleValue(prin, attribute)
If o IsNot Nothing Then
Return o.ToString()
Else
Return String.Empty
End If
End Function
''' <summary>
''' Returns all of the strings contained in a multi-value attribute
''' </summary>
<Extension()> _
Public Function ExtensionGetMultipleString(ByVal prin As Principal, ByVal attribute As String) As String()
'get the object array for this attribute
Dim attributeValues() As Object = ExtensionGetAttributeObject(prin, attribute)
'create a string array of the same length as the object array
Dim array As String() = New String(attributeValues.Length - 1) {}
'and copy over all items, converting them to strings as we go
For i As Integer = 0 To attributeValues.Length - 1
array(i) = attributeValues(i).ToString()
Next
'return the string array
Return array
End Function
''' <summary>
''' Returns the date value of an attribute
''' </summary>
''' <remarks>(null if no value found)</remarks>
<Extension()> _
Public Function ExtensionGetSingleDate(ByVal prin As Principal, ByVal attribute As String) As String
Dim o As Object = ExtensionGetSingleValue(prin, attribute)
If o IsNot Nothing Then
Dim dt As DateTime = Convert.ToDateTime(o)
Return dt
Else
Return Nothing
End If
End Function
''' <summary>
''' Returns the principle represented by a column containing a single distinguished name
''' </summary>
<Extension()> _
Public Function ExtensionGetSingleDistinguishedName(ByVal prin As Principal, ByVal attribute As String) As Principal
'get the distinguished name of the object as a string
Dim dn As String = ExtensionGetSingleString(prin, attribute)
'check for null
If String.IsNullOrEmpty(dn) Then
Return Nothing
End If
'get the principal represented by the DN
Dim prinF As Principal = Principal.FindByIdentity(prin.Context, dn)
'if it exists then prepare to return it
If prinF IsNot Nothing Then
'if the object is a userprincipal then get the user detailed principal for it.
If TypeOf prinF Is UserPrincipal Then
prinF = UserDetailedPrinciple.FindByIdentity(prin.Context, prinF.Name)
End If
'return the principal
Return prinF
End If
'if all else fails return nothing
Return Nothing
End Function
<Extension()> _
Public Function ExtensionGetMultipleDistinguishedNames(ByVal prinParent As Principal, ByVal attribute As String) As Principal()
'get the distinguished name of the object as a string
Dim dn() As String = ExtensionGetMultipleString(prinParent, attribute)
'array to hold list of principles
Dim al As New List(Of Principal)()
For Each d As String In dn
'get the principal represented by the DN
Dim prin As Principal = Principal.FindByIdentity(prinParent.Context, d)
'if it exists then prepare to return it
If prin IsNot Nothing Then
'if the object is a userprincipal then get the user detailed principal for it.
If TypeOf prin Is UserPrincipal Then
prin = UserDetailedPrinciple.FindByIdentity(prin.Context, prin.Name)
ElseIf TypeOf prin Is GroupPrincipal Then
prin = GroupPrincipal.FindByIdentity(prin.Context, prin.Name)
End If
'return the principal
al.Add(prin)
End If
Next
'return list of principles
Return al.ToArray()
End Function
''' <summary>
''' Gets the bytes contained in an Octet String
''' </summary>
<Extension()> _
Public Function ExtentsionGetBytes(ByVal prin As Principal, ByVal attribute As String) As Byte()
'get the data
Dim o As Object = ExtensionGetSingleValue(prin, attribute)
'check for nulls
If o Is Nothing Then
Return Nothing
End If
'get the byte array
Dim byteArray() As Byte = DirectCast(o, Byte())
'return the data
Return byteArray
End Function
''' <summary>
''' Gets the image contained in an Octet String type attribute
''' </summary>
<Extension()> _
Public Function ExtensionGetImage(ByVal prin As Principal, ByVal attribute As String) As Image
'get bytes for attribute
Dim bytearray() As Byte = ExtentsionGetBytes(prin, attribute)
'if none returned return nothing
If bytearray Is Nothing Then
Return Nothing
End If
'read the bytes into a memory stream
Dim ms As New MemoryStream(bytearray)
'convert the memory stream to a bitmap and return it
Return New Bitmap(ms)
End Function
<Extension()> _
Public Function ExtensionGetImages(ByVal prin As Principal, ByVal attribute As String) As Image()
'get all values in attribute
Dim vals() As Object = ExtensionGetAttributeObject(prin, attribute)
'array to hold images to be returned
Dim al As New List(Of Image)()
For Each o As Object In vals
'get bytes
Dim bytearray() As Byte = DirectCast(o, Byte())
'if no data skip entry
If bytearray Is Nothing Then
Continue For
End If
'read the bytes into a memory stream
Dim ms As New MemoryStream(bytearray)
'convert the memory stream to a bitmap and add to the array
al.Add(New Bitmap(ms))
Next
'return the list of images as an array.
Return al.ToArray()
End Function
#End Region
#Region "Set Helpers"
Private Sub ExtensionSetDE(ByVal de As DirectoryEntry, ByVal attribute As String, ByVal value As Object)
'check value, if it's null then don't add (null means clear only)
If value IsNot Nothing Then
de.Properties(attribute).Add(value)
End If
End Sub
<Extension()> _
Public Sub ExtensionSetValue(ByVal prin As Principal, ByVal attribute As String, ByVal value As Object)
Dim uo As DirectoryEntry = prin.GetUnderlyingObject()
uo.Properties(attribute).Clear()
ExtensionSetDE(uo, attribute, value)
End Sub
<Extension()> _
Public Sub ExtensionSetStringValue(ByVal prin As Principal, ByVal attribute As String, ByVal value As String)
If String.IsNullOrEmpty(value) Then
value = Nothing
End If
ExtensionSetValue(prin, attribute, value)
End Sub
<Extension()> _
Public Sub ExtensionSetMultipleValueDirect(ByVal prin As Principal, ByVal attribute As String, ByVal values() As Object)
'Normal ExtensionSet does not support saving array type values (octet string)
' so we set it directly on the underlying object
Dim uo As DirectoryEntry = prin.GetUnderlyingObject()
uo.Properties(attribute).Clear()
If values IsNot Nothing Then
For Each v As Object In values
ExtensionSetDE(uo, attribute, v)
Next
End If
End Sub
<Extension()> _
Public Sub ExtensionSetImage(ByVal prin As Principal, ByVal attribute As String, ByVal img As Image)
'set data to attribute
ExtensionSetValue(prin, attribute, img.SaveImageToByteArray())
End Sub
<Extension()> _
Public Sub ExtensionSetImages(ByVal prin As Principal, ByVal attribute As String, ByVal img() As Image)
'array list to hold the values temporarily
Dim al As New ArrayList()
'convert each image into a byte array
For Each i As Image In img
al.Add(i.SaveImageToByteArray())
Next
'set image array as value on attribute
ExtensionSetMultipleValueDirect(prin, attribute, al.ToArray())
End Sub
<Extension()> _
Public Function SaveImageToByteArray(ByVal img As Image) As Byte()
'create a memory strea
Dim ms As New MemoryStream()
'write the image to the stream
img.Save(ms, Imaging.ImageFormat.Jpeg)
'save data to a byte array
Dim bytes() As Byte = ms.ToArray()
Return bytes
End Function
<Extension()> _
Public Sub ExtensionSetMultipleDistinguishedNames(ByVal prin As Principal, ByVal attribute As String, ByVal dns() As Principal)
'convert user principles into distinguished names
Dim sc As New ArrayList()
For Each u As UserDetailedPrinciple In dns
sc.Add(u.DistinguishedName)
Next
ExtensionSetMultipleValueDirect(prin, attribute, sc.ToArray())
End Sub
''' <summary>
''' Helps set the Thumbnail photo by resizing main photo and also saving original (possibly resized to 300xvariable)
''' to JpegPhoto.
''' </summary>
''' <param name="imgO">The iamge to use as the users thumbnail photo</param>
''' <remarks>You still NEED to call .Save() after calling this sub
''' as this sub does not call save().
''' </remarks>
<Extension()> _
Public Sub SetUserPhoto(ByVal prin As Principal, ByVal imgO As Image)
'resize the image for thumbnail
Dim imgN As Bitmap = ResizeImage(imgO, 100)
'check if we need to resize for medium sized image (300px high max
Dim imgM As Bitmap
If imgO.Height > 300 Then
imgM = ResizeImage(imgO, 300)
Else
imgM = imgO
End If
'save small image to the users profile
ExtensionSetImage(prin, "thumbnailPhoto", imgN)
'save original to the jpegPhoto attribute
ExtensionSetImages(prin, "jpegPhoto", New Image() {imgM})
End Sub
Private Function ResizeImage(ByVal imgO As Bitmap, ByVal Height As Integer) As Bitmap
'if the image is smaller/equal to the requested height return original
If imgO.Height <= Height Then
Return imgO
End If
'images are fixedHeightxVariable, so we need to calculate the variable portion
Dim width As Integer = (Convert.ToDecimal(imgO.Width) / Convert.ToDecimal(imgO.Height)) * Height
'resize the image
Dim imgN As New Bitmap(width, Height)
Dim g As Graphics = Graphics.FromImage(imgN)
g.SmoothingMode = Drawing2D.SmoothingMode.AntiAlias
g.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
'draw in resized form
g.DrawImage(imgO, 0, 0, width, Height)
'return resized image
Return imgN
End Function
<Extension()> _
Public Function Rename(ByVal prin As Principal, ByVal NewName As String) As Principal
'escape commas
NewName = NewName.Replace(",", "\,")
'get directory object for move
Dim de As DirectoryEntry = prin.GetUnderlyingObject()
'move
de.Rename(String.Format("CN={0}", NewName))
de.CommitChanges()
'get the new object by name and return it
Return New ADConnection(prin.Context).GetPrincipalByName(prin.Guid.ToString())
End Function
#End Region
Here is the code in action in my custion UserPrinciple:
<DirectoryObjectClass("user")> _
<DirectoryRdnPrefix("CN")> _
Public Class UserDetailedPrinciple
Inherits UserPrincipal
<DirectoryProperty("initials")> _
Public Property MiddleInitial() As String
Get
Return ExtensionGetSingleString("initials")
End Get
Set(ByVal value As String)
ExtensionSetStringValue("initials", value)
End Set
End Property
<DirectoryProperty("wWWHomePage")> _
Public Property HomePage() As String
Get
Return ExtensionGetSingleString("wWWHomePage")
End Get
Set(ByVal value As String)
ExtensionSetStringValue("wWWHomePage", value)
End Set
End Property
<DirectoryProperty("url")> _
Public Property URLs() As String()
Get
Return ExtensionGetMultipleString("url")
End Get
Set(ByVal value As String())
ExtensionSetMultipleValueDirect("url", value)
End Set
End Property
<DirectoryProperty("info")> _
Public Property Notes() As String
Get
Return ExtensionGetSingleString("info")
End Get
Set(ByVal value As String)
ExtensionSetStringValue("info", value)
End Set
End Property
Public ReadOnly Property ObjectType() As String
Get
Dim types() As String = ExtensionGetMultipleString("objectClass")
Return types.Last()
End Get
End Property
<DirectoryProperty("thumbnailPhoto")> _
Public Property ThumbnailPhoto() As Image
Get
Return ExtensionGetImage("thumbnailPhoto")
End Get
Set(ByVal value As Image)
ExtensionSetImage("thumbnailPhoto", value)
End Set
End Property
<DirectoryProperty("thumbnailLogo")> _
Public Property ThumbnailLogo() As Image
Get
Return ExtensionGetImage("thumbnailLogo")
End Get
Set(ByVal value As Image)
ExtensionSetImage("thumbnailLogo", value)
End Set
End Property
<DirectoryProperty("jpegPhoto")> _
Public Property JpegPhoto() As Image()
Get
Return ExtensionGetImages("jpegPhoto")
End Get
Set(ByVal value As Image())
ExtensionSetImages("jpegPhoto", value)
End Set
End Property
<DirectoryProperty("title")> _
Public Property Title() As String
Get
Return ExtensionGetSingleString("title")
End Get
Set(ByVal value As String)
ExtensionSetStringValue("title", value)
End Set
End Property
<DirectoryProperty("department")> _
Public Property Department() As String
Get
Return ExtensionGetSingleString("department")
End Get
Set(ByVal value As String)
ExtensionSetStringValue("department", value)
End Set
End Property
<DirectoryProperty("company")> _
Public Property Company() As String
Get
Return ExtensionGetSingleString("company")
End Get
Set(ByVal value As String)
ExtensionSetStringValue("company", value)
End Set
End Property
<DirectoryProperty("manager")> _
Public Property Manager() As UserDetailedPrinciple
Get
Dim mgr As UserDetailedPrinciple = ExtensionGetSingleDistinguishedName("manager")
If mgr IsNot Nothing Then
If Me.Guid <> mgr.Guid Then
Return mgr
End If
End If
Return Nothing
End Get
Set(ByVal value As UserDetailedPrinciple)
'check for nulls
If value Is Nothing Then
ExtensionSetStringValue("manager", Nothing)
Else
ExtensionSetStringValue("manager", value.DistinguishedName)
End If
End Set
End Property
<DirectoryProperty("assistant")> _
Public Property Assistant() As UserDetailedPrinciple
Get
Dim assist As UserDetailedPrinciple = ExtensionGetSingleDistinguishedName("assistant")
If assist IsNot Nothing Then
Return assist
End If
Return Nothing
End Get
Set(ByVal value As UserDetailedPrinciple)
'check for nulls
If value Is Nothing Then
ExtensionSetStringValue("assistant", Nothing)
Else
ExtensionSetStringValue("assistant", value.DistinguishedName)
End If
End Set
End Property
<DirectoryProperty("directReports")> _
Public Property DirectReports() As Principal()
Get
Dim dReports As Principal() = ExtensionGetMultipleDistinguishedNames("directReports")
Return dReports
End Get
Set(ByVal value As Principal())
ExtensionSetMultipleDistinguishedNames("directReports", value)
End Set
End Property
<DirectoryProperty("homePhone")> _
Public Property HomePhone() As String
Get
Return ExtensionGetSingleString("homePhone")
End Get
Set(ByVal value As String)
ExtensionSetStringValue("homePhone", value)
End Set
End Property
<DirectoryProperty("pager")> _
Public Property Pager() As String
Get
Return ExtensionGetSingleString("pager")
End Get
Set(ByVal value As String)
ExtensionSetStringValue("pager", value)
End Set
End Property
<DirectoryProperty("otherTelephone")> _
Public Property OtherTelephone() As String()
Get
Return ExtensionGetMultipleString("otherTelephone")
End Get
Set(ByVal value As String())
ExtensionSetMultipleValueDirect("otherTelephone", value)
End Set
End Property
<DirectoryProperty("physicalDeliveryOfficeName")> _
Public Property PhysicalLocation() As String
Get
Return ExtensionGetSingleString("physicalDeliveryOfficeName")
End Get
Set(ByVal value As String)
ExtensionSetStringValue("physicalDeliveryOfficeName", value)
End Set
End Property
<DirectoryProperty("l")> _
Public Property AddressCity() As String
Get
Return ExtensionGetSingleString("l")
End Get
Set(ByVal value As String)
ExtensionSetStringValue("l", value)
End Set
End Property
<DirectoryProperty("postOfficeBox")> _
Public Property AddressPOBox() As String
Get
Return ExtensionGetSingleString("postOfficeBox")
End Get
Set(ByVal value As String)
ExtensionSetStringValue("postOfficeBox", value)
End Set
End Property
<DirectoryProperty("st")> _
Public Property AddressState() As String
Get
Return ExtensionGetSingleString("st")
End Get
Set(ByVal value As String)
ExtensionSetStringValue("st", value)
End Set
End Property
<DirectoryProperty("streetAddress")> _
Public Property Address() As String
Get
Return ExtensionGetSingleString("streetAddress")
End Get
Set(ByVal value As String)
ExtensionSetStringValue("streetAddress", value)
End Set
End Property
<DirectoryProperty("postalCode")> _
Public Property AddressZipCode() As String
Get
Return ExtensionGetSingleString("postalCode")
End Get
Set(ByVal value As String)
ExtensionSetStringValue("postalCode", value)
End Set
End Property
<DirectoryProperty("c")> _
Public Property AddressCountry() As String
Get
Return ExtensionGetSingleString("c")
End Get
Set(ByVal value As String)
ExtensionSetStringValue("c", value)
End Set
End Property
<DirectoryProperty("whenCreated")> _
Public ReadOnly Property Created() As Nullable(Of DateTime)
Get
Return ExtensionGetSingleDate("whenCreated")
End Get
End Property
<DirectoryProperty("whenChanged")> _
Public ReadOnly Property LastModified() As Nullable(Of DateTime)
Get
Return ExtensionGetSingleDate("whenChanged")
End Get
End Property
Public Sub New()
MyBase.New(ADConnection.CurrentADPrincipalContext)
End Sub
Public Sub New(ByVal context As PrincipalContext)
MyBase.New(context)
End Sub
Public Overloads Shared Function FindByIdentity(ByVal context As PrincipalContext, ByVal identityValue As String) As UserDetailedPrinciple
Return DirectCast(Principal.FindByIdentityWithType(context, GetType(UserDetailedPrinciple), identityValue), UserDetailedPrinciple)
End Function
Public Overloads Shared Function FindByIdentity(ByVal context As PrincipalContext, ByVal identityType As IdentityType, ByVal identityValue As String) As UserDetailedPrinciple
Return DirectCast(Principal.FindByIdentityWithType(context, GetType(UserDetailedPrinciple), identityType, identityValue), UserDetailedPrinciple)
End Function
End Class

WCF - Can I use an existing type to be passed through my WCF service

I have a service. I have an existing class of business objects. What I would like to know is how can I pass a class through WCF from the business object assembly without having to create a new class in my WCF site while appending or tags?
Here is an existing UDT:
Namespace example: Application.BusinessObjects.Appointments
Public Structure AppointmentResource
Private _id As String
Private _type As ResourceTypeOption
Private _name As String
Property id() As String
Get
Return _id
End Get
Set(ByVal value As String)
_id = value
End Set
End Property
Property type() As ResourceTypeOption
Get
Return CType(_type, Int32)
End Get
Set(ByVal value As ResourceTypeOption)
_type = value
End Set
End Property
Property Name() As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
Public Sub New(ByVal id As String, ByVal type As ResourceTypeOption, ByVal name As String)
_id = id
_type = type
_name = name
End Sub
End Structure
Here is the same one I created with the data contract attributes:
Namespace example: Application.Service.Appointments
<DataContract()> _
Public Structure AppointmentResource
Private _id As String
Private _type As ResourceTypeOption
Private _name As String
<DataMember()> _
Property id() As String
Get
Return _id
End Get
Set(ByVal value As String)
_id = value
End Set
End Property
<DataMember()> _
Property type() As ResourceTypeOption
Get
Return CType(_type, Int32)
End Get
Set(ByVal value As ResourceTypeOption)
_type = value
End Set
End Property
<DataMember()> _
Property Name() As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
Public Sub New(ByVal id As String, ByVal type As ResourceTypeOption, ByVal name As String)
_id = id
_type = type
_name = name
End Sub
End Structure
There is an easy way to share types between client and service, just by adding reference to shared type assembly to your client BEFORE adding the service reference.
You can find the detailed scenario and sample project there:
http://blog.walteralmeida.com/2010/08/wcf-tips-and-tricks-share-types-between-server-and-client.html
ResourceTypeOption also appears to be a custom class, so you would to define that as part of the contract in its own class. The client has to know about that and so it needs its own contract. Clients already know how to deal with CLR types like string. Any other custom types would also have to be defined in the contract.

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