How to create session

Hi everyone,

I have created a login and I have attached the code to this post. What I now want to do is create a session. I have looked at some tutorials but they were not helpful. I am using ASP.Net with C# and SQL server.

What I want to do is - a logged in user logs in, his preference is retrieved from the database and stored. He/she can then view the page which is restricted to anonymous users, and when he/she searches for matches, the command button will initiate a query and return the matches based on the user's preferences against the database.

Please can you tell me how i can do this?
xmalcolmAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Kyle AbrahamsSenior .Net DeveloperCommented:
you can just access the session object:

Session["somevalue"] = 0;
Session["someothervalue"] = "test';

string s = session["someothervalue"];
int i = session["somevalue"];
0
xmalcolmAuthor Commented:
Here is the code.



//Aspx Login page
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
    <asp:Login ID="Login1" runat="server" onauthenticate="Login1_Authenticate">
    </asp:Login>
</asp:Content>


//Aspx.cs login page
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Xml.Serialization;
using System.Xml;
using System.IO;
using System.Xml.Xsl;
using System.Text;

public partial class LoginPage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
    {
        bool Authenticated = false;
        Authenticated = SiteLevelCustomAuthenticationMethod(Login1.UserName, Login1.Password);
        e.Authenticated = Authenticated;
        if (Authenticated == true)
        {
           
            Response.Redirect("SearchPage.aspx");
        }
    }
    
    private bool SiteLevelCustomAuthenticationMethod(string UserName, string Password)
    {
        bool boolReturnValue = false;
        // Insert code that implements a site-specific custom 
        // authentication method here.
        // This example implementation always returns false.
        string strConnection = "Data Source=XG7;Initial Catalog=Car_Share_XG;Integrated Security=True";
        SqlConnection myConn = new SqlConnection(strConnection);
        String strSQL = "Select * From tbl_Member";
        SqlCommand command = new SqlCommand(strSQL, myConn);
        SqlDataReader Dr;
        myConn.Open();
        Dr = command.ExecuteReader();
        while (Dr.Read())
        {
            if ((UserName == Dr["Member_email"].ToString()) & (Password == Dr["Member_password"].ToString()))
            {
                boolReturnValue = true;
                break;
            }
            
        }
        Dr.Close();
        return boolReturnValue;
    }
}

Open in new window

0
xmalcolmAuthor Commented:
Hi Ged, what do you exactly mean by that I can just access the session object? can you explain. And also where does this code go.

Also I know I have to make changes to the webconfig file, which I did. I am also attaching the web config file to this post. Please let me know if you see any errors.
<?xml version="1.0"?>
<!-- 
    Note: As an alternative to hand editing this file you can use the 
    web admin tool to configure settings for your application. Use
    the Website->Asp.Net Configuration option in Visual Studio.
    A full list of settings and comments can be found in 
    machine.config.comments usually located in 
    \Windows\Microsoft.Net\Framework\v2.x\Config 
-->
<configuration>
	<configSections>
		<sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
			<sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
				<section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
				<sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
					<section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere"/>
					<section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
					<section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
					<section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
				</sectionGroup>
			</sectionGroup>
		</sectionGroup>
	</configSections>
	<appSettings/>
	<connectionStrings>
  <add name="Car_Share_XGConnectionString1" connectionString="Data Source=XG7;Initial Catalog=Car_Share_XG;Integrated Security=True"
   providerName="System.Data.SqlClient" />
 </connectionStrings>
	<system.web>
		<!-- 
            Set compilation debug="true" to insert debugging 
            symbols into the compiled page. Because this 
            affects performance, set this value to true only 
            during development.
        -->
		<compilation debug="true">
			<assemblies>
				<add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
				<add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
				<add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
				<add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
			</assemblies>
		</compilation>
		<!--
            The <authentication> section enables configuration 
            of the security authentication mode used by 
            ASP.NET to identify an incoming user. 
        -->
		<!--
            The <customErrors> section enables configuration 
            of what to do if/when an unhandled error occurs 
            during the execution of a request. Specifically, 
            it enables developers to configure html error pages 
            to be displayed in place of a error stack trace.

        <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
            <error statusCode="403" redirect="NoAccess.htm" />
            <error statusCode="404" redirect="FileNotFound.htm" />
        </customErrors>
        -->
		<pages>
			<controls>
				<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
				<add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
			</controls>
		</pages>
		<httpHandlers>
			<remove verb="*" path="*.asmx"/>
			<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
			<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
			<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
		</httpHandlers>
		<httpModules>
			<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
		</httpModules>
	</system.web>
    <system.web>
        <authentication mode="Forms">
          <forms name="Login" loginUrl="login.aspx" />
        </authentication>
      </system.web>
    <location path="SearchPage.aspx">
      <system.web>
        <authorization>
          <deny users="?" />
        </authorization>
      </system.web>
  </location>
	<system.codedom>
		<compilers>
			<compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
				<providerOption name="CompilerVersion" value="v3.5"/>
				<providerOption name="WarnAsError" value="false"/>
			</compiler>
			<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" warningLevel="4" type="Microsoft.VisualBasic.VBCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
				<providerOption name="CompilerVersion" value="v3.5"/>
				<providerOption name="OptionInfer" value="true"/>
				<providerOption name="WarnAsError" value="false"/>
			</compiler>
		</compilers>
	</system.codedom>
	<!-- 
        The system.webServer section is required for running ASP.NET AJAX under Internet
        Information Services 7.0.  It is not necessary for previous version of IIS.
    -->
	<system.webServer>
		<validation validateIntegratedModeConfiguration="false"/>
		<modules>
			<remove name="ScriptModule"/>
			<add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
		</modules>
		<handlers>
			<remove name="WebServiceHandlerFactory-Integrated"/>
			<remove name="ScriptHandlerFactory"/>
			<remove name="ScriptHandlerFactoryAppServices"/>
			<remove name="ScriptResource"/>
			<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
			<add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
			<add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
		</handlers>
	</system.webServer>
	<runtime>
		<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
			<dependentAssembly>
				<assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/>
				<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
			</dependentAssembly>
			<dependentAssembly>
				<assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/>
				<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
			</dependentAssembly>
		</assemblyBinding>
	</runtime>
</configuration>

Open in new window

0
Rowby Goren Makes an Impact on Screen and Online

Learn about longtime user Rowby Goren and his great contributions to the site. We explore his method for posing questions that are likely to yield a solution, and take a look at how his career transformed from a Hollywood writer to a website entrepreneur.

Todd GerbertIT ConsultantCommented:
What you're describing is a little bit beyond one or two lines of example code.  Start here: http://msdn.microsoft.com/en-us/library/aa478948.aspx - you're probably most interested in Membership and Profile providers (membership providers will provide "login" logic, while the profile providers will store user preferences for you).
Report back with more specific questions if something's unclear.
0
xmalcolmAuthor Commented:
Yes but doesnt this mean, I have to create a seperate database? What I have got now is using the database that I have created to authenticate the users.

Which works fine - but I have no session variable to store the user's session. And when I mean store user's preferences - I mean things such as user's smoking preference, gender preference etc. My website is based on a car share scheme and i am doing this as a final year project for uni. So it doesnt need to be overly complicated.
0
xmalcolmAuthor Commented:
Ok I sort of got it work now by doing this:

protected void Login_Authenticate(object sender, AuthenticateEventArgs e)
    {
        bool Authenticated = false;
        Authenticated = SiteLevelCustomAuthenticationMethod(Login1.UserName, Login1.Password);
        e.Authenticated = Authenticated;
        if (Authenticated == true)
        {
            FormsAuthentication.SetAuthCookie(Login1.UserName.ToString(), Login1.RememberMeSet);
            Session["Username"] = Login1.UserName.ToString();
            Response.Redirect("SearchPage.aspx");
        }
    }

This allows me to be redirected to the page only if a login has been successful. My complete code so far has been attached. Now the only bit I want to do is gather preferences from the database for the user who is logged in. Any ideas anyone???
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Xml.Serialization;
using System.Xml;
using System.IO;
using System.Xml.Xsl;
using System.Text;

public partial class Login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Login_Authenticate(object sender, AuthenticateEventArgs e)
    {
        bool Authenticated = false;
        Authenticated = SiteLevelCustomAuthenticationMethod(Login1.UserName, Login1.Password);
        e.Authenticated = Authenticated;
        if (Authenticated == true)
        {
            FormsAuthentication.SetAuthCookie(Login1.UserName.ToString(), Login1.RememberMeSet);
            Session["Username"] = Login1.UserName.ToString();
            Response.Redirect("SearchPage.aspx");
        }
    }
    
    private bool SiteLevelCustomAuthenticationMethod(string UserName, string Password)
    {
        bool boolReturnValue = false;
        // Insert code that implements a site-specific custom 
        // authentication method here.
        // This example implementation always returns false.
        string strConnection = "Data Source=XG7;Initial Catalog=Car_Share_XG;Integrated Security=True";
        SqlConnection myConn = new SqlConnection(strConnection);
        String strSQL = "Select * From tbl_Member";
        SqlCommand command = new SqlCommand(strSQL, myConn);
        SqlDataReader Dr;
        myConn.Open();
        Dr = command.ExecuteReader();
        while (Dr.Read())
        {
            if ((UserName == Dr["Member_email"].ToString()) & (Password == Dr["Member_password"].ToString()))
            {
                boolReturnValue = true;
                break;
            }
            
        }
        Dr.Close();
        return boolReturnValue;
    }
}

Open in new window

0
Todd GerbertIT ConsultantCommented:
Check out the documentation on MSDN (http://msdn.microsoft.com/) for the AspNetSqlProfileProvider and the AspNetSqlMembershipProvider.
I've attached a complete, albeit simple, website as an example.

Default.aspx.txt
0
Todd GerbertIT ConsultantCommented:
...forgot the rest of the files, sorry.
Preferences.aspx.txt
web.config.txt
0
xmalcolmAuthor Commented:
Hi tgerbert,

what you have provided looks good, but the only thing is, doesnt this mean I have to create a page and it will require the user to input his/her preference every time before they search instead of jsut automatically retrieving the value from the database?
0
Todd GerbertIT ConsultantCommented:
It means they will need to login, but not that they will need to select their preference every time. The Page_Load event will retrieve the Smoking preference; it's only saved if you click the button.
Did you check any documentation on MSDN?
0
xmalcolmAuthor Commented:
Hi tgerbert,

I tried doing your solution anyway, but it doesn't seem to pick up 'Smoking' in the aspx.cs file. I have attached my Web.Config, ASPX adn ASPX.cs file. Could you have a look and let me know what am I doing wrong?
Questions.txt
aspx.txt
aspx-cs.txt
webconfig.txt
0
xmalcolmAuthor Commented:
Hi tgerbert,

I am still going through the MSDN website.
0
xmalcolmAuthor Commented:
Hi Tgerbert,

I have been looking through the MSDN and I have managed to sort out the issues. Now I dont get any error messages but how do I know if it is working?

Could you please explain to me what do these statements do?

        try
        {
            bool GenderP = Profile.GenderP;
            if (GenderP)
                lblGenderP.Text += "Male";
            else
                lblGenderP.Text += "Female";
        }
        catch
        {
            lblGenderP.Text += "Not Found";
        }

I have also attached my web.config file as I figured that the reason for my errors were because I didn't configure the web.config file properly.

<?xml version="1.0"?>
<!-- 
    Note: As an alternative to hand editing this file you can use the 
    web admin tool to configure settings for your application. Use
    the Website->Asp.Net Configuration option in Visual Studio.
    A full list of settings and comments can be found in 
    machine.config.comments usually located in 
    \Windows\Microsoft.Net\Framework\v2.x\Config 
-->
<configuration>
	<configSections>
		<sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
			<sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
				<section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
				<sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
					<section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere"/>
					<section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
					<section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
					<section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
				</sectionGroup>
			</sectionGroup>
		</sectionGroup>
	</configSections>
	<appSettings/>
	<connectionStrings>
  <add name="Car_Share_XGConnectionString1" connectionString="Data Source=XG7;Initial Catalog=Car_Share_XG;Integrated Security=True"
   providerName="System.Data.SqlClient" />
 </connectionStrings>
  
	<system.web>
		<!-- 
            Set compilation debug="true" to insert debugging 
            symbols into the compiled page. Because this 
            affects performance, set this value to true only 
            during development.
        -->
		<compilation debug="true">
			<assemblies>
				<add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
				<add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
				<add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
				<add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
			</assemblies>
		</compilation>
    <customErrors mode="Off"></customErrors>
    <profile enabled="true" defaultProvider="AspNetSqlProfileProvider">
      <properties>
        <add name="SmokeP" type="bool"/>
        <add name="GenderP" type="bool"/>
        <add name="JourneyP" type="bool"/>
      </properties>
    </profile>
		<!--
            The <authentication> section enables configuration 
            of the security authentication mode used by 
            ASP.NET to identify an incoming user. 
        -->
		<!--
            The <customErrors> section enables configuration 
            of what to do if/when an unhandled error occurs 
            during the execution of a request. Specifically, 
            it enables developers to configure html error pages 
            to be displayed in place of a error stack trace.

        <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
            <error statusCode="403" redirect="NoAccess.htm" />
            <error statusCode="404" redirect="FileNotFound.htm" />
        </customErrors>
        -->
		<pages>
			<controls>
				<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
				<add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
			</controls>
		</pages>
		<httpHandlers>
			<remove verb="*" path="*.asmx"/>
			<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
			<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
			<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
		</httpHandlers>
		<httpModules>
			<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
		</httpModules>
	</system.web>
    <system.web>
        <authentication mode="Forms">
          <forms name="Login" loginUrl="Login.aspx" />
        </authentication>
      </system.web>
    <location path="SearchPage.aspx">
      <system.web>
        <authorization>
          <deny users="?" />
        </authorization>
      </system.web>
  </location>
	<system.codedom>
		<compilers>
			<compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
				<providerOption name="CompilerVersion" value="v3.5"/>
				<providerOption name="WarnAsError" value="false"/>
			</compiler>
			<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" warningLevel="4" type="Microsoft.VisualBasic.VBCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
				<providerOption name="CompilerVersion" value="v3.5"/>
				<providerOption name="OptionInfer" value="true"/>
				<providerOption name="WarnAsError" value="false"/>
			</compiler>
		</compilers>
	</system.codedom>
	<!-- 
        The system.webServer section is required for running ASP.NET AJAX under Internet
        Information Services 7.0.  It is not necessary for previous version of IIS.
    -->
	<system.webServer>
		<validation validateIntegratedModeConfiguration="false"/>
		<modules>
			<remove name="ScriptModule"/>
			<add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
		</modules>
		<handlers>
			<remove name="WebServiceHandlerFactory-Integrated"/>
			<remove name="ScriptHandlerFactory"/>
			<remove name="ScriptHandlerFactoryAppServices"/>
			<remove name="ScriptResource"/>
			<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
			<add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
			<add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
		</handlers>
	</system.webServer>
	<runtime>
		<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
			<dependentAssembly>
				<assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/>
				<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
			</dependentAssembly>
			<dependentAssembly>
				<assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/>
				<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
			</dependentAssembly>
		</assemblyBinding>
	</runtime>
</configuration>

Open in new window

0
Todd GerbertIT ConsultantCommented:
I'll be happy to take a closer look, but I'm in the middle of a little bit of mess at work, so gimme a couple hours.
0
xmalcolmAuthor Commented:
Sure no problem
0
xmalcolmAuthor Commented:
Hi Tgerbert,

I am getting the following errors

System.FormatException: String was not recognized as a valid Boolean.

Maybe the preferences aren't getting saved.
0
Todd GerbertIT ConsultantCommented:
Here's another example that's fairly self-explanatory. You should be able to put these files into a Website project (you'll need to remove the ".txt" extensions first), and run it without any changes. There is no need to manually create a database.
To the web.config file i have added the following bits to the <configuration> section:
<location path="Login.aspx">
    <system.web>
      <authorization>
        <allow users="?"/>
      </authorization>
    </system.web>
</location>
<location path="Register.aspx">
  <system.web>
    <authorization>
      <allow users="?"/>
    </authorization>
  </system.web>
</location>

This allows users who are not yet logged in (i.e. anonymous users) to access the Login and Register pages.
These bits belong in the <system.web> section (which is inside the <configuration> tag):
<authorization>
    <deny users="?"/>
    <allow users="*"/>
</authorization>

This denies access to anonymous users, while allowing access to every other signed in user. The two "allow's" above for anonymous users override just the Login and Register page, an anonymous user attempting to access any other page will be governed by this rule (which is to deny).
<authentication mode="Forms">
    <forms defaultUrl="~/Default.aspx" loginUrl="~/Login.aspx"></forms>
</authentication>

This enables authentication, and specifies to use forms in the ASPX pages, the defaultUrl is the page to go to on successful login, and the loginUrl specifies the page that contains the login form.
<profile enabled="true">
    <properties>
        <add name="Smoking" type="bool"/>
        <add name="NumDoors" type="int"/>
        <add name="Make" type="string"/>
    </properties>
</profile>
This enables user profiles, and defines three properties of the users' profile, the property's names and their types. You access these in code using Profile.<Whatever Name You Defined Above> = <Some Value>; If you defined the property as an int, then you can only assign an int to it - that is, Profile.NumDoors = "seven" won't work because you can't assign a string to an int setting.

PreferencesWebsiteExample.zip
0
xmalcolmAuthor Commented:
Hi Tgerbert, thanks for the info but I am getting an error saying

String was not recognized as a valid Boolean. With regards to:
Profile.SmokeP = bool.Parse(rbSmokeP.SelectedValue);

My web config file currently is configured like that:
<profile enabled="true" defaultProvider="AspNetSqlProfileProvider">
      <properties>
        <add name="SmokeP" type="bool"/>
        <add name="GenderP" type="bool"/>
        <add name="JourneyP" type="bool"/>
      </properties>
    </profile>

My aspx page is configured this way:

  <asp:Label ID="lblSmokeP" runat="server" Text="Select Smoking Preference" Font-Bold="true" Font-Size=8></asp:Label>
    <asp:RadioButtonList ID="rbSmokeP" runat="server" Font-size="8">
    <asp:ListItem>Smoker</asp:ListItem>
    <asp:ListItem>Non-Smoker</asp:ListItem>
    <asp:ListItem>Both</asp:ListItem>
    </asp:RadioButtonList>
    <br />
    <br />
    <asp:Label ID="lblGenderP" runat="server" Text="Select Gender Preference" Font-Bold="true" Font-Size=8></asp:Label>
    <asp:RadioButtonList ID="rbGenderP" runat="server" Font-size="8">
    <asp:ListItem>Male</asp:ListItem>
    <asp:ListItem>Female</asp:ListItem>
    <asp:ListItem>Both</asp:ListItem>
    </asp:RadioButtonList>
    <br />
    <br />
    <asp:Label ID="lblJourneyP" runat="server" Text="Select Journey Preference (Seeking a Lift/Offering a Lift/Both)" Font-Bold="true" Font-Size=8></asp:Label>
    <asp:RadioButtonList ID="rbJourneyP" runat="server" Font-size="8">
    <asp:ListItem>Seeking</asp:ListItem>
    <asp:ListItem>Offering</asp:ListItem>
    <asp:ListItem>Both</asp:ListItem>
    </asp:RadioButtonList>  


As you can see I have radio buttons instead of checkboxes and textboxes. What am I doing wrong?
0
Todd GerbertIT ConsultantCommented:
My philosophy is give a man a fish and he eats for a day; teach a man to fish and he eats for a lifetime. So, let me answer your question with a question: Is the string value you're trying to parse a valid boolean value?
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
xmalcolmAuthor Commented:
Well no cos boolean is either 'Yes' or 'No' or 'True' or 'False' or '1' or '0'.
0
xmalcolmAuthor Commented:
I found a solution which is

Profile.SmokeP = rbSmokeP.SelectedIndex == 0;

This is because my radio buttons are not individual but 'RadioButtonList'. Which is why the above works. But Tgerbert gotta say - a very good philosophy indeed and very true.
0
Todd GerbertIT ConsultantCommented:
Right, so do you know how to make your radio button list return a value other than "Smoking," "Non-Smoking" or "Both?"
And do you want to use a boolean (which is a Yes/No kind of storage) for an option that has three possible states?
0
xmalcolmAuthor Commented:
Nope as I want to use all three states.
0
Todd GerbertIT ConsultantCommented:
So here's one possible solution...
Make your SmokeP profile property an int, not a bool, and use 0 for Both, 1 for Smoking and 2 for Non-Smoking.

<!-- web.config -->
<profile enabled="true">
	<properties>
		<add name="SmokeP" type="int"/>
	</properties>
</profile>

// C# Code-behind
Profile.SmokeP = Int32.Parse(rbSmokeP.SelectedValue);

<!-- ASPX source -->
<asp:RadioButtonList ID="rbSmokeP" runat="server">
    <asp:ListItem Value="0" Text="Both" />
    <asp:ListItem Value="1" Text="Smoking" />
    <asp:ListItem Value="2" Text="Non-Smoking" />
</asp:RadioButtonList>

Open in new window

0
xmalcolmAuthor Commented:
But would this not work?

Profile.SmokeP = rbSmokeP.SelectedIndex == 0;
0
Todd GerbertIT ConsultantCommented:
Consider all the possibilities.
1) rbSmokeP.SelectedIndex is 0, in which case rbSmokeP.SelectedIndex == 0 would evaluate to true, therefore Profile.SmokeP = true
2) rbSmokeP.SelectedIndex is 1, in which case rbSmokeP.SelectedIndex == 0 would evaluate to false, therefore Profile.SmokeP = false
3) rbSmokeP.SelectedIndex is 2, in which case rbSmokeP.SelectedIndex == 0 would evaluate to false, therefore Profile.SmokeP = false
 
0
Todd GerbertIT ConsultantCommented:
That method also depends on the ordering of the ListItems in the RadioButtonList, as opposed to the value assigned to each item. If you decided to re-arrange your list so that "Both", for example, you would need to also adjust your C# code.
0
xmalcolmAuthor Commented:
Tgerbert you are the man! Thanks I now understand the stuff and it works.
0
xmalcolmAuthor Commented:
And I went for your solution and made my states and 'int'
0
xmalcolmAuthor Commented:
Tgerbert I was wondering, Could I not have my value as 'Smoker', 'Non-Smoker' etc. and change the state type to 'String'.

And in the Aspx.cs file I could say:

Profile.SmokeP = rbSmokeP.SelectedValue;

this actually works. Because what I have done is used this line

lblSelSmokeP.Text = Profile.SmokeP.ToString();

on another page to show their selected preference.

If I change my value from 0,1... to Strings such as mentioned above, is there a problem? or Will there be any problem later?
0
Todd GerbertIT ConsultantCommented:
You can, however storing & handling an int requires less storage space and processing time, and eliminates any ambiguity. 1 is 1, there's no confusing that. But "Smoker" is not "Smoking", is not "smoking", etc.
You can use a function to change the int value into a more suitable string, for example

public SmokingPrefToString(int smoking)
{
  if(smoking == 0)
    return "No Preference";
  // etc etc
}

lblSelSmokeP.Text = SmokingPrefToString(Profile.SmokeP);

Open in new window

0
xmalcolmAuthor Commented:
Ah I see cool cool thanks Tgerbert.

Now that I have preferences stored. Do you have any idea how I could now use this to make a query. Basically what I have now is

SELECT * FROM tbl_Member

but what i want is SELECT * FROM tbl_Member WHERE (user preference of the user logged in matches those of the ones in the database)

But then again I dont want the query to match the user who is seeking a lift with other users who are also seeking a lift but with those who are 'offering' a lift. And its the same with the 'Both' scenarios. Do you have any idea how I could do this?
0
Todd GerbertIT ConsultantCommented:
You probably would be best off opening another question in the SQL zone.
0
xmalcolmAuthor Commented:
ah ok thanks for all your help Tgerbert.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.