Danish character not supported - asp.net

I am working on a site thath has to also support Danish characters (the supported languages will increase in the future).
I am using a database table - lets call it Strings - where I create a record for each string I display on my site. For example, the greeting message in the login page is entered in the database like this:
ID | Description | Text | Lang_code
1 | login | Log In | en
This is the code that pulls the lang_code from the database:
Public Shared Function GetLanguageCodeFromBrowser()
Dim language_code As String
Dim databaseConnection As New DBConnectionAdapter
Dim DataReader, DataReader1 As MySqlDataReader
Dim serverVar As String = HttpContext.Current.Request.ServerVariables("HTTP_ACCEPT_LANGUAGE")
language_code = LCase(serverVar)
Dim Query As String = "SELECT language_code FROM languages WHERE language_code = '" & LCase(language_code) & "' AND disabled = 0"
Dim Query1 As String = "SELECT language_code FROM languages WHERE language_code = '" & LCase(Left(language_code, 2)) & "' AND disabled = 0"
Dim cmdSelect As New MySqlCommand(Query, databaseConnection.connectionWebServices)
Dim cmdSelect1 As New MySqlCommand(Query1, databaseConnection.connectionWebServices)
Try
databaseConnection.OpenWebServices()
DataReader = cmdSelect.ExecuteReader
If Not DataReader.Read Then
DataReader.Dispose()
DataReader1 = cmdSelect1.ExecuteReader
If Not DataReader1.Read Then
DataReader1.Dispose()
Return language_code = "en"
Else
Return DataReader1("language_code")
End If
DataReader1 = Nothing
DataReader1.Dispose()
Else
Return DataReader("language_code")
End If
DataReader = Nothing
DataReader.Dispose()
Catch ex As Exception
' TODO Error handling
HttpContext.Current.Response.Write(ex.Message)
Finally
databaseConnection.CloseWebServices()
End Try
databaseConnection = Nothing
End Function
And I use it in the MasterPage's Page_Init event like this:
Session("language_code") = Language_from_Browser.GetLanguageCodeFromBrowser
Everything works fine in English, but when it comes to Danish, some characters are mangled.
I have tried changing this in web.config:
<globalization
fileEncoding="ISO-8859-1"
requestEncoding="ISO-8859-1"
responseEncoding="ISO-8859-1"
culture="auto"
/>
Still not working properly.
Please note that I have a default.aspx page in each one of my folders, so I dont have to bother with URL rewriting (that's how I see it a least)

Related

Pull Outlook OfficeLocation using Alias

While referencing Return list of names and email address from outlook to vb.net listbox I am trying to fill in a ASP:Textbox with the Office Location of the user.
Currently I pull the current logged in user. The user's username on their PC is also their Outlook Alias. With that being said, I am trying to use the username/Alias to pull the Office location within Outlook. I currently have the following issue with my coding:
'get logged in user(works)
Dim username As String
Dim User As System.Security.Principal.IPrincipal
User = System.Web.HttpContext.Current.User
username = User.Identity.Name.Substring(3)
'Office Location of User
Dim itemx As String
'Create an Outlook application.
Dim oApp As Outlook._Application = New Outlook.Application()
'Get the MAPI namespace.
Dim oNS As Outlook.NameSpace = oApp.Session
'Get the Global Address List.
Dim oALs As Outlook.AddressLists = oNS.AddressLists
Dim oGal As Outlook.AddressList = oALs.Item(1)
'Get all the entries.
Dim oEntries As Outlook.AddressEntries = oGal.AddressEntries
For Each entry In oEntries
If oEntries.GetExchangeUser.Alias = username Then
itemx = oEntries.GetExchangeUser.OfficeLocation
End If
Next
Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment.
If you are building a solution that runs in a server-side context, you should try to use components that have been made safe for unattended execution. Or, you should try to find alternatives that allow at least part of the code to run client-side. If you use an Office application from a server-side solution, the application will lack many of the necessary capabilities to run successfully. Additionally, you will be taking risks with the stability of your overall solution. Read more about that in the Considerations for server-side Automation of Office article in MSDN.
As a workaround you may consider using EWS, see EWS Managed API, EWS, and web services in Exchange for more information. Or just a low-level API on which Outlook is based on - Extended MAPI.
Main thing that I learned was that you need a password and username to access outlook.
Get user ID from PC (Alias for Outlook):
Dim usernameQuery As String
Dim UserQ As System.Security.Principal.IPrincipal
UserQ = System.Web.HttpContext.Current.User
usernameQuery = User.Identity.Name.Substring(3).ToUpper
UserText.Text = usernameQuery
Then:
Call function like so:
'outlook office location **************************************************
LocationText.Text = GetUserInfo(usernameQuery, "physicaldeliveryofficename")
'OTHER OPTIONS YOU CAN QUERY
'Dim svalue As String = GetUserInfo(UserAccount, "mail")
'Dim svalue As String = GetUserInfo(UserAccount, "givenName")
'Dim svalue As String = GetUserInfo(UserAccount, "sn")
'Dim svalue As String = GetUserInfo(UserAccount, "l")
'Dim svalue As String = GetUserInfo(UserAccount, "st")
'Dim svalue As String = GetUserInfo(UserAccount, "streetAddress")
'Dim svalue As String = GetUserInfo(UserAccount, "postalCode")
'Dim svalue As String = GetUserInfo(UserAccount, "telephoneNumber")
'Dim svalue As String = GetUserInfo(useraccount, "co")
'txtName.Text = GetUserInfo(UserAccount, "givenName") & " " & GetUserInfo(UserAccount, "sn")
'txtPhone.Text = GetUserInfo(UserAccount, "telephoneNumber")
'********************************************************************************
Function:
Public Function GetUserInfo(ByVal inSAM As String, ByVal inType As String) As String
Try
Dim sPath As String = "LDAP://"full_path"/DC="path_value",DC="path_value",DC="path_value" "
Dim SamAccount As String = Right(inSAM, Len(inSAM) - InStr(inSAM, "\"))
Dim myDirectory As New DirectoryEntry(sPath, "username", "password") 'pass the user account and password for your Enterprise admin.
Dim mySearcher As New DirectorySearcher(myDirectory)
Dim mySearchResultColl As SearchResultCollection
Dim mySearchResult As SearchResult
Dim myResultPropColl As ResultPropertyCollection
Dim myResultPropValueColl As ResultPropertyValueCollection
'Build LDAP query
mySearcher.Filter = ("(&(objectClass=user)(samaccountname=" & SamAccount & "))")
mySearchResultColl = mySearcher.FindAll()
'I expect only one user from search result
Select Case mySearchResultColl.Count
Case 0
Return "Null"
Exit Function
Case Is > 1
Return "Null"
Exit Function
End Select
'Get the search result from the collection
mySearchResult = mySearchResultColl.Item(0)
''Get the Properites, they contain the usefull info
myResultPropColl = mySearchResult.Properties
If myResultPropColl.Contains(inType) Then
myResultPropValueColl = myResultPropColl.Item(inType)
Return CStr(myResultPropValueColl.Item(0))
End If
'displayname, mail
'Retrieve from the properties collection the display name and email of the user
'myResultPropValueColl = myResultPropColl.Item(inType)
'Return CStr(myResultPropValueColl.Item(0))
Catch ex As System.Exception
End Try
Return "Null"
End Function
FYI-
full_path = "value"."value"."value"

Windows Search Service : Search Partial Content

I am trying to search in content of the documents uploaded into a folder. It is working fine if i am giving a word to search. It is not working if i m giving part of work. e.g. If I search with Microsoft, It lists documents. but if i search with Micro it is not returning any result
Following is my code..
strQuery = String.Format("SELECT System.FileDescription, System.FileName, System.ItemPathDisplay, System.ItemUrl " & _ " FROM SystemIndex WHERE scope ='file:{0}' and Contains(*, '*{1}*')", folderpath, strText)
''' Rendered query
''' SELECT System.FileDescription, System.FileName, System.ItemPathDisplay, System.ItemUrl FROM SystemIndex WHERE scope ='file:c:\documents\UserDocumentFolder' and Contains(*, '*Micro*')
Dim connString As String = "Provider=Search.CollatorDSO.1;Extended Properties='Application=Windows';"
Dim cn As New System.Data.OleDb.OleDbConnection(connString)
cn.Open()
Dim _Adaptor As New System.Data.OleDb.OleDbDataAdapter(strQuery, cn)
Try
_Adaptor.Fill(_tempTable)
Catch oleEx As OleDb.OleDbException
General.WriteUnhandledError(oleEx)
Catch ex0 As Exception
General.WriteUnhandledError(ex0)
End Try
If _tempTable IsNot Nothing And _tempTable.Rows.Count > 0 Then
''''' FOUND
Else
''''' NOT FOUND
End If

How to deal with SqlDataReader null values in VB.net

I have the follwoing code that performs a query and returns a result. However, I looked around and found some examples to take care of null values but I get an error: "Invalid attempt to read when no data is present." I also got the error: "Conversion from type 'DBNull' to type 'Decimal' is not valid."
Can someone help me out with this code to prevent null values from crashing my program?
Private Sub EFFICIENCY_STACKRANK_YTD(ByVal EMPLOYEE As String)
Dim queryString As String = "SELECT " & _
" (SELECT CAST(SUM(TARGET_SECONDS) AS DECIMAL)/ CAST(SUM(ROUTE_SECONDS) AS DECIMAL) FROM dbo.APE_BUSDRIVER_MAIN WITH(NOLOCK) WHERE APE_AREA_OBJID = " & lblAreaOBJID.Text & " AND EMPLOYEE_NAME = '" & EMPLOYEE & "' AND YEAR_TIME = '" & cbYear.Text & "' AND ACTIVE = 1) AS RESULT1" & _
" FROM dbo.APE_BUSDRIVER_MAIN "
Using connection As New SqlConnection(SQLConnectionStr)
Dim command As New SqlCommand(queryString, connection)
connection.Open()
Dim reader As SqlDataReader = command.ExecuteReader()
If reader.Read Then
RESULT1 = reader("RESULT1")
Else
RESULT1 = 0
End If
End Using
End Sub
You have opened the reader, but have not asked it to actually read anything.
After this line:
Dim reader As SqlDataReader = command.ExecuteReader()
add
If reader.Read() Then
and wrap the result reading into this if statement, i.e.
If reader.Read() Then
Dim index As Integer = reader.GetOrdinal("RESULT1")
If reader.IsDBNull(index) Then
RESULT1 = String.Empty
Else
RESULT1 = reader(index)
End If
End If
Note that this works because your SQL should only return a single record. In the event that you were reading multiple records, you would need to call the Read statement in a loop until there were no more records, i.e.
Do While reader.Read()
Loop
I wanted to provide another, more-advanced, answer as an option. Many classes can be extended in .NET like this.
If you are regularly performing "Is NULL" checks like this in your applications, you can choose to extend the DataReader class once to have additional functions available everywhere in your application. Here is an example that creates an extension called "ReadNullAsString()" onto the data reader class. This makes a function that always returns String.Empty when a DbNull is encountered.
Part 1, place this module code in a new class file in App_Code if application is a website, otherwise place where ever you prefer. There are two overloads, one for the field's ordinal position (aka index), and one for the field's ColumnName.
Public Module DataReaderExtensions
''' <summary>
''' Reads fieldName from Data Reader. If fieldName is DbNull, returns String.Empty.
''' </summary>
''' <returns>Safely returns a string. No need to check for DbNull.</returns>
<System.Runtime.CompilerServices.Extension()> _
Public Function ReadNullAsEmptyString(ByVal reader As IDataReader, ByVal fieldName As String) As String
If IsDBNull(reader(fieldName)) Then
Return String.Empty
Else
Return reader(fieldName)
End If
Return False
End Function
''' <summary>
''' Reads fieldOrdinal from Data Reader. If fieldOrdinal is DbNull, returns String.Empty.
''' </summary>
''' <returns>Safely returns a string. No need to check for DbNull.</returns>
<System.Runtime.CompilerServices.Extension()> _
Public Function ReadString(ByVal reader As IDataReader, ByVal fieldOrdinal As Integer) As String
If IsDBNull(reader(fieldOrdinal)) Then
Return ""
Else
Return reader(fieldOrdinal)
End If
Return False
End Function
End Module
Step 2, call the new extension like so:
' no need to check for DbNull now, this functionality is encapsulated in the extension module.
RESULT1 = reader.ReadNullAsEmptyString(index)
'or
RESULT1 = reader.ReadNullAsEmptyString("RESULT1")

How do I make this asp.net email go to a database?

I ave a contact form (VS 2010 / VB / .net4), and when the client fills out the form, I get an email -- which I like, but ....
For instance, here's an e-mail I got:
Email: ivy_league_alum-at-yahoo.com
Subject: Do you guys integrate PPT?
Message: I'm looking for a PPT integrator in the Michigan area.
First_Name: Tim
Last_Name: Dewar
Organization: American Axle
Browser: Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.7 (KHTML, like
Gecko) Chrome/16.0.912.75 Safari/535.7
IP Address: 184.60.79.96
Server Date & Time: 1/13/2012 11:28:59 AM
This is just a lead-generating company, so we're gonna get a lot of emails and we're gonna want them organized.
It was suggested by Jon P that I use a database to gather all these emails I'm getting, instead of MS Excel (which I wouldn't know how to do anyway). So I downloaded SQL Server Express. So now what do I do? Can someone please tell me what I have to add to the code, specifically, or what I have to do, so I can gather these emails in an organized manner? Thanks!
Addendum (I know this is long):
Specifically, my email code is:
<%# Page Title="Contact Health Nutts" Language="VB"
MasterPageFile="~/Site.master" AutoEventWireup="false"
CodeFile="contact.aspx.vb" Inherits="contact" %>
Protected Sub SubmitForm_Click(ByVal sender As Object, ByVal e As System.EventArgs)
If Not Page.IsValid Then Exit Sub
Dim SendResultsTo As String = "jason.weber-at-healthynutts.com"
Dim smtpMailServer As String = "smtp.healthynutts.com"
Dim smtpUsername As String = "jason.weber-at-healthynutts.com"
Dim smtpPassword As String = "********"
Dim MailSubject As String = "Form Results"
Try
Dim txtQ As TextBox = Me.FormContent.FindControl("TextBoxQ")
If txtQ IsNot Nothing Then
Dim ans As String = ViewState("hf1")
If ans.ToLower <> txtQ.Text.ToLower Or ans.ToUpper <> txtQ.Text.ToUpper Then
Me.YourForm.ActiveViewIndex = 3
Exit Sub
End If
End If
Dim FromEmail As String = SendResultsTo
Dim msgBody As StringBuilder = New StringBuilder()
Dim sendCC As Boolean = False
For Each c As Control In Me.FormContent.Controls
Select Case c.GetType.ToString
Case "System.Web.UI.WebControls.TextBox"
Dim txt As TextBox = CType(c, TextBox)
If txt.ID.ToLower <> "textboxq" Then
msgBody.Append(txt.ID & ": " & txt.Text & vbCrLf & vbCrLf)
End If
If txt.ID.ToLower = "email" Then
FromEmail = txt.Text
End If
If txt.ID.ToLower = "subject" Then
MailSubject = txt.Text
End If
Case "System.Web.UI.WebControls.CheckBox"
Dim chk As CheckBox = CType(c, CheckBox)
If chk.ID.ToLower = "checkboxcc" Then
If chk.Checked Then sendCC = True
Else
msgBody.Append(chk.ID & ": " & chk.Checked & vbCrLf & vbCrLf)
End If
Case "System.Web.UI.WebControls.RadioButton"
Dim rad As RadioButton = CType(c, RadioButton)
msgBody.Append(rad.ID & ": " & rad.Checked & vbCrLf & vbCrLf)
Case "System.Web.UI.WebControls.DropDownList"
Dim ddl As DropDownList = CType(c, DropDownList)
msgBody.Append(ddl.ID & ": " & ddl.SelectedValue & vbCrLf & vbCrLf)
End Select
Next
msgBody.AppendLine()
msgBody.Append("Browser: " & Request.UserAgent & vbCrLf & vbCrLf)
msgBody.Append("IP Address: " & Request.UserHostAddress & vbCrLf & vbCrLf)
msgBody.Append("Server Date & Time: " & DateTime.Now & vbCrLf & vbCrLf)
Dim myMessage As System.Net.Mail.MailMessage = New System.Net.Mail.MailMessage()
myMessage.To.Add(SendResultsTo)
myMessage.From = New System.Net.Mail.MailAddress(FromEmail)
myMessage.Subject = MailSubject
myMessage.Body = msgBody.ToString
myMessage.IsBodyHtml = False
If sendCC Then myMessage.CC.Add(FromEmail)
Dim basicAuthenticationInfo As New System.Net.NetworkCredential(smtpUsername, smtpPassword)
Dim MailObj As New System.Net.Mail.SmtpClient(smtpMailServer)
MailObj.Credentials = basicAuthenticationInfo
MailObj.Send(myMessage)
Me.YourForm.ActiveViewIndex = 1
Catch
Me.YourForm.ActiveViewIndex = 2
End Try
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
If Not Page.IsPostBack Then
Dim lbl As Label = Me.FormContent.FindControl("labelq")
If lbl IsNot Nothing Then
Dim rq(3) As String
rq(0) = "Is fire hot or cold?"
rq(1) = "Is ice hot or cold?"
rq(2) = "Is water wet or dry?"
Dim ra(3) As String
ra(0) = "hot"
ra(1) = "cold"
ra(2) = "wet"
Dim rnd As New Random
Dim rn As Integer = rnd.Next(0, 3)
lbl.Text = rq(rn)
ViewState("hf1") = ra(rn)
End If
End If
End Sub
</script> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server"> <h1>CONTACT HEALTH
NUTTS AND WORK FROM THE COMFORT OF YOUR OWN HOME!
Enter your Email Address:
* Required
* Please enter a valid email address.
Subject:
* Required
Please type your message below:
* Required
First Name:
* Required
Last Name:
* Required
Phone Number:
* Required
* Please enter a valid U.S. phone number (including dashes).
City:
* Required
State/Province:
* Required
Your message has been sent. Thank you for contacting us.
Due to technical difficulty, your message may NOT have been sent.
You did not correctly answer the anti-spam question. Please go back and try again.
Don't take this the wrong way, but judging by what you've said about your lack of coding abilities, it may work out cheaper for you to get someone else to do the work for you. A competent coder should be able to knock something out for you in about an hour, probably less if he doesn't stop for coffee.
If you do really really want to do it yourself, then first off, you're going to have to find out if the hosting packing for the website includes a database or not.
Assuming you don't host the website on your local machine, then having a version of SQL Express on your machine will help you develop the code, but you won't be able to deploy it.
Completely ignoring that though, steps you want to go through are:
Create the database in SQL, then create the relevant database
table
Create a connection from the website to the database using ADO.Net
Create the code to insert the contact form data into the database table
You then need to think about how you're going to view the data once it's been collected, so you're either going to have to write something or learn SQL.
If you want some code samples to help you get going, then we need to know what language you're using (it should be C# or VB.Net) and posting the code for the contact form would help as well (obviously deleting any sensitive details, such as usernames and passwords).
EDIT:
Once you've created the database, this script should give you a basic table structure in SQL Express:
CREATE TABLE [dbo].[tblEmails](
[EmailID] [int] IDENTITY(1,1) NOT NULL,
[EmailAddress] [nvarchar](200) NOT NULL,
[Subject] [nvarchar](200) NOT NULL,
[Message] [nvarchar](max) NOT NULL,
[FirstName] [nvarchar](50) NOT NULL,
[LastName] [nvarchar](50) NOT NULL,
[PhoneNumber] [nvarchar](20) NOT NULL,
[City] [nvarchar](50) NOT NULL,
[State] [nvarchar](50) NOT NULL,
CONSTRAINT [PK_tblEmails2] PRIMARY KEY CLUSTERED
(
[EmailID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
To use it, right click on the database in SQL Express, click New Query, paste the above into the window, then hit the Execute button, refresh the database and you shouldn't see the table.
Here is a good tutorial if you're using ajax too.
http://dotnetslackers.com/articles/aspnet/Developing-an-AJAX-and-ASP-NET-4-0-Based-Online-E-mail-System-Part1.aspx

Using 2 databases for Session information in ASP.NET [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
This post was originally trying to find the problem, which I thought was a web.config issue. I also thought it was something in the code behind of my master page. All the text up here is part of the process of finding out the problem, scroll to the bottom for the most recent updates.
My website allows users to type a code into a textbox. If a recognized code is entered, the page will refresh and display a welcome message to that user, otherwise an error message will come up. I am putting their manually entered code into a session so that their name can be pulled up. I can't get the session to stay between pages. All of my code is on the master page's vb page and I don't know what I am doing wrong.
I have been told to make sure EnableSessionState="true" but that doesn't work on master pages.
I've been told to check IIS settings, but I can't because I don't have permissions to it.
Tried SessionState cookieless="UseUri" and somehow that created a never-ending redirect loop.
I have debugged the functions and they DO return values.
The textbox DOES go away when I enter a code and the welcome message gets displayed with the user's first and last name, so I know that works.
I've checked to make sure there is no Session.Abandon code anywhere in the site.
I added a Watch to every instance of Session("IB") on the page and they are filled correctly when I enter a code into the textbox. Then when I click on a link to move to another page, the debugger stops on the very first line in my Page_Load, Dim ib As String = CType(Session.Item("IB"), String) and all of my watched IB variables immediately turn into Nothing.
Here is the code behind for the master page:
Imports System.Data
Imports System.Data.SqlClient
Imports System.Data.OleDb
Partial Class MasterPage
Inherits System.Web.UI.MasterPage
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Dim BAccount As String = CType(Session("BAccount"), String)
If Not IsPostBack Then
If Session("BAccount") Is Nothing Then
'no such value in session state, show textbox for IB to enter code
IBText.Visible = True
IBTextBox.Visible = True
IBTextBoxButton.Visible = True
lbNotIB.Visible = False
Else
'call function
GetSessionValues(BAccount)
End If
End If
End Sub
Protected Function GetSessionValues(ByVal Code As String) As Boolean
Dim FirstName As String = CType(Session("First_Name"), String)
Dim LastName As String = CType(Session("Last_Name"), String)
Dim Name As String = CType(Session("Name"), String)
If GetAccountName(FirstName, LastName) Then
'hide textbox
IBText.Visible = False
IBTextBox.Visible = False
IBTextBoxButton.Visible = False
'show welcome message to user if IB code exists in database
lblIB.Visible = True
lblIB.Text = "Welcome, " + Session("First_Name") + " " + Session("Last_Name") + "."
lbNotIB.Visible = True
lbNotIB.Text = "Not " + Session("First_Name") + " " + Session("Last_Name") + "?"
Return True
ElseIf GetBackUpAccountName(Name) Then
'hide textbox
IBText.Visible = False
IBTextBox.Visible = False
IBTextBoxButton.Visible = False
'show welcome message to user if IB code exists in database
lblIB.Visible = True
lblIB.Text = "Welcome, " + Session("Name") + "."
lbNotIB.Visible = True
lbNotIB.Text = "Not " + Session("Name") + "?"
Return True
Else
'IB code not found
'shows error message in red
lblIB.ForeColor = Drawing.Color.Red
lblIB.Text = "Account not found, please try again."
Return False
End If
End Function
Private Function GetAccountName(ByRef FirstName As String, ByRef LastName As String) As Boolean
'declare variable
Dim BAccount As String = CType(Session("BAccount"), String)
'sql statement for baccount information
Dim sql As String = "SELECT BAccount, First_Name, Last_Name FROM IB INNER JOIN IB_BUISNESS_INFORMATION ON (IB.IB_ID = IB_BUISNESS_INFORMATION.IB_ID) WHERE BAccount = #BAccount"
Using conn As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("IBConnectionString").ConnectionString)
Using cmd As New SqlCommand(sql, conn)
cmd.Parameters.AddWithValue("#BAccount", SqlDbType.VarChar)
cmd.Parameters("#BAccount").Value = IBTextBox.Text
If IBTextBox.Text Is Nothing Then
cmd.Parameters("#BAccount").Value = DBNull.Value
Else
cmd.Parameters("#BAccount").Value = IBTextBox.Text
End If
conn.Open()
Using rdr As SqlDataReader = cmd.ExecuteReader
If (rdr.Read) Then
FirstName = rdr("First_Name").ToString()
LastName = rdr("Last_Name").ToString()
Return True
Else
Return False
End If
End Using
conn.Close()
End Using
End Using
End Function
Private Function GetBackUpAccountName(ByRef Name As String) As Boolean
'declare variable
Dim BAccount As String = CType(Session("BAccount"), String)
'sql statement for baccount information in case BAccount is not found, search here next
Dim backupsql As String = "SELECT BAccount, Name FROM brokermaster WHERE BAccount = ?"
Using conn As New OleDbConnection(System.Configuration.ConfigurationManager.ConnectionStrings("BackUpConnectionString").ConnectionString)
Using cmd As New OleDbCommand(backupsql, conn)
cmd.Parameters.AddWithValue("?", SqlDbType.VarChar)
cmd.Parameters("?").Value = IBTextBox.Text
If IBTextBox.Text Is Nothing Then
cmd.Parameters("?").Value = DBNull.Value
Else
cmd.Parameters("?").Value = IBTextBox.Text
End If
conn.Open()
Using backuprdr As OleDbDataReader = cmd.ExecuteReader
If (backuprdr.Read) Then
Name = backuprdr("Name").ToString()
Return True
Else
Return False
End If
End Using
conn.Close()
End Using
End Using
End Function
Protected Sub CustomValidator1_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles CustomValidator1.ServerValidate
'declare variables
Dim FirstName As String = CType(Session("First_Name"), String)
Dim LastName As String = CType(Session("Last_Name"), String)
Dim Name As String = CType(Session("Name"), String)
If (Not GetSessionValues(args.Value)) Then
args.IsValid = False
Else
args.IsValid = True
End If
If GetAccountName(FirstName, LastName) Then
'set session variables
Session("First_Name") = FirstName
Session("Last_Name") = LastName
'hide textbox
IBText.Visible = False
IBTextBox.Visible = False
IBTextBoxButton.Visible = False
args.IsValid = True
'show welcome message to user if IB code exists in database
lblIB.Visible = True
lblIB.Text = "Welcome, " + Session("First_Name") + " " + Session("Last_Name") + "."
ElseIf GetBackUpAccountName(Name) Then
'set session variables
Session("Name") = Name
'hide textbox
IBText.Visible = False
IBTextBox.Visible = False
IBTextBoxButton.Visible = False
args.IsValid = True
'show welcome message to user if IB code exists in database
lblIB.Visible = True
lblIB.Text = "Welcome, " + Session("Name") + "."
Else
'IB code not found
args.IsValid = False
'shows error message in red
lblIB.ForeColor = Drawing.Color.Red
lblIB.Text = "Account not found, please try again."
End If
End Sub
Protected Sub IBTextBoxButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles IBTextBoxButton.Click
If Page.IsValid Then
'declare variables
Dim LSD As String = CType(Session("LSD"), String)
Dim LSC As String = CType(Session("LSC"), String)
Dim BAccount As String = CType(Session("BAccount"), String)
Session("BAccount") = IBTextBox.Text
'add session variable
If GetCompanyName(LSD) Then
Session("LSD") = LSD
End If
'add session variable
If GetWebsite(LSC) Then
Session("LSC") = LSC
End If
End If
End Sub
Private Function GetCompanyName(ByRef LSD As String) As Boolean
'declare variable
Dim BAccount As String = CType(Session("BAccount"), String)
'sql statement to get company information
Dim sql As String = "SELECT Company_Name, BAccount FROM IB_CONTACT_INFORMATION INNER JOIN IB_BUISNESS_INFORMATION ON (IB_CONTACT_INFORMATION.IB_ID = IB_BUISNESS_INFORMATION.IB_ID) WHERE BAccount = #BAccount"
Using conn As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("IBConnectionString").ConnectionString)
Using cmd As New SqlCommand(sql, conn)
cmd.Parameters.AddWithValue("#BAccount", SqlDbType.VarChar)
cmd.Parameters("#BAccount").Value = IBTextBox.Text
If IBTextBox.Text Is Nothing Then
cmd.Parameters("#BAccount").Value = DBNull.Value
Else
cmd.Parameters("#BAccount").Value = IBTextBox.Text
End If
conn.Open()
Using rdr As SqlDataReader = cmd.ExecuteReader
If (rdr.Read) Then
LSD = rdr("Company_Name").ToString()
Return True
Else
Return False
End If
End Using
conn.Close()
End Using
End Using
End Function
Private Function GetWebsite(ByRef LSC As String) As Boolean
'declare variable
Dim BAccount As String = CType(Session("BAccount"), String)
'sql statement for website information
Dim sql As String = "SELECT TOP 1 WebSites, BAccount FROM IB_WEBSITES INNER JOIN IB_BUISNESS_INFORMATION ON (IB_WEBSITES.IB_ID = IB_BUISNESS_INFORMATION.IB_ID) WHERE BAccount = #BAccount"
Using conn As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("IBConnectionString").ConnectionString)
Using cmd As New SqlCommand(sql, conn)
cmd.Parameters.AddWithValue("#BAccount", SqlDbType.VarChar)
cmd.Parameters("#BAccount").Value = IBTextBox.Text
If IBTextBox.Text Is Nothing Then
cmd.Parameters("#BAccount").Value = DBNull.Value
Else
cmd.Parameters("#BAccount").Value = IBTextBox.Text
End If
conn.Open()
Using rdr As SqlDataReader = cmd.ExecuteReader
If (rdr.Read) Then
LSC = rdr("WebSites").ToString()
Return True
Else
Return False
End If
End Using
conn.Close()
End Using
End Using
End Function
Protected Sub lbNotIB_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lbNotIB.Click
'if user is not IB that currently holds session, this will destroy the session and allow them to enter different code
Session.Abandon()
Response.Redirect(Request.RawUrl)
End Sub
End Class
aspx:
<asp:Label ID="IBText" runat="server" Text="Enter your IB code here:"></asp:Label>
<asp:TextBox ID="IBTextBox" runat="server"></asp:TextBox>
<asp:Button ID="IBTextBoxButton" runat="server" Text="Submit" />
<asp:CustomValidator ID="CustomValidator1" runat="server"
ControlToValidate="IBTextBox" ForeColor="Red"
OnServerValidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
<asp:Label ID="lblIB" runat="server" Text=""></asp:Label>
web.config:
<sessionState mode="InProc" cookieless="false" timeout="20" sqlConnectionString="Data Source=***;Initial Catalog=***;Persist Security Info=True;User ID=***;Password=***">
</sessionState>
UPDATE:
Hah! I finally got it! So there are 2 problems here.
I did not have <httpModules> set in my web.config.
I needed to add:
<httpModules>
<add name="Session" type="System.Web.SessionState.SessionStateModule"/>
</httpModules>
Reference
Now the problem is that I have information being pulled from 2 databases for these Sessions but have only 1 database listed in the <sessionState> section of my web.config file. I tried adding a 2nd <sessionState> but it threw an error.
Is there a way to include the 2nd database?
If I don't, half of my sessions will stay throughout the website, and half will disappear. By the way, I didn't have anything to do with the database creation, this was all done way before my time.
I tried this in web.config but it also doesn't work:
<sessionState mode="InProc"
cookieless="false"
timeout="20"
sqlConnectionString="IBConnectionString, BackUpConnectionString">
</sessionState>
Yet another update:
Here's another thing I tried, suggested by a user on the asp.net forums. This generated a 500 internal server error as well, so that makes me think that having 2 instances of <sessionState> is not something that is allowed.
<sessionState mode="SQLServer"
cookieless="false"
timeout="20"
sqlConnectionString="IBConnectionString">
</sessionState>
<sessionState mode="SQLServer"
cookieless="false"
timeout="20"
sqlConnectionString="BackUpConnectionString">
</sessionState>
More:
sessionState has been changed and the site still acts like it has been, the ConnectionString must not have anything to do with the problem with the 2nd database losing it's session. It's gotta be something in the code behind, I can't think of what else could be wrong with the web.config.
<sessionState mode="InProc" timeout="20"></sessionState>
We also found out that the session variable is still there, it just won't display the user's information when it's connected to the back up database connection.
After much deliberation and frustration, I asked my boss how hard it would be to just combine the databases. Although there are more than 2400 records in the Back Up Account database, there is really no other option. I do not foresee a solution coming to me anytime soon and I have already wasted a month on this....thanks everyone for the help.
If I ever do figure something out, I will come back and edit this post!
First off, remove your code in the Init portion of the page. It is unnecssary.
Second, why are you setting the IB values of the session to True in portions of your code? It's overwriting the account number. Change both..
Session("IB") = True
to
Session("IB") = args.Value
Or just don't even mess with the session at that point..it should already be set from the IBTextBoxButton_Click Sub Routine.
Make sure session state enabled in web.config. If it is set to "StateServer" or "SQLServer", change it to "InProc" for testing purposes to rule out external failing dependencies.
<sessionState mode="InProc" />
Also, I have seen exceptions get thrown in the past that seemed to "eat" the session. Look for any try/catch blocks that might be giving you problems.
Single stepping through the code normally shows the problems, but if not, one technique I use that helps sometimes, is to litter your code with "i am here" messages.
The thinking is that sometimes it helps trigger an epiphany when you can see which line (or close to it) appears to be creating the problem.
For example, you could dump a session variable state along with an approximate line number and just output it at several spots to your web page.
You also should try to narrow down the amount of code you are debugging.
If you can isolate the problem to a smaller set of code, often this helps spot problems.
** edit **
Apparently I was just scanning. Upon actually reading your post, i see you have identified the line causing the issue. I don't see anything wrong with the line, but for some reason i want to try using a different session variable name. I don't know if that will help, but it's an easy thing to try. Maybe use a longer session variable name. Without having the debugger open in front of me, I don't know what else to check off the top of my head.

Resources