C# .NET - Error:Trying to Redirect from LogIn to ZephyrIndex Page

Asked By Elvin
28-Sep-11 11:40 PM
Code for Login.aspx.cs page >>>>>>>>":

using System;
using System.Collections.Generic;
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;

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

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
             
            // Setting connection object
           // SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["useThisConnStringYOOOOO!"].ConnectionString);
           SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString2"].ConnectionString);

            //Opening the connection
            con.Open();

            string cmdStr = "select count(*) from UserAccounts where Username = '" + TextBox1.Text + "'";

            SqlCommand Checkuser = new SqlCommand(cmdStr,con);

            int temp = Convert.ToInt32(Checkuser.ExecuteScalar().ToString());
  
            if (temp == 1)
            {
                string cmdStr2 = "select Password from UserAccounts where Password = '" + TextBox2.Text + "'";
                SqlCommand pass = new SqlCommand(cmdStr2, con);

               // string password = pass.ExecuteScalar().ToString();
                string password = pass.ToString();
                con.Close();
                
                if (password == TextBox2.Text)
                {
                    Session["New"] = TextBox1.Text;
                    Response.Redirect("ZephyrIndex.aspx");
                }
                else
                {
                    Label1.Visible = true;
                    Label1.Text = "Invalid Password. Try Again Please.";
                }
            }
                else
                {
                     Label1.Visible = true;
                    Label1.Text = "Invalid Username. Try Again Please.";
                }

            }
        }
    }


Results:  I ran the page and set it as Start Up page and entered Username and Password but got just no error except that it actually did not redirect me to the ZephyrIndex.aspx page. But the minor issue is that the message from label in LogIn page says "Invalid Password . Try Again".
Can you help me?



CODE FOR WEB>CONFIG>>>>>>:
<?xml version="1.0"?>
<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="Zephyr_Air_DB2ConnectionString" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Zephyr_Air_DB2.accdb;
   Persist Security Info=True"   oviderName="System.Data.OleDb" />           
   -->
    
    <!--
<add name="ConnectionString" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\CyBeRfOrCe\Desktop\Zephyr_Air_DB2.accdb"
   providerName="System.Data.OleDb" /> 
    -->
    
   <add name="ConnectionString2" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\tblsZephyrAir.mdf;Integrated Security=True;User Instance=True"
   providerName="System.Data.SqlClient" />
   

    <!--<add name="useThisConnStringYOOOOO!" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\C:\USERS\USERPCONE\DOCUMENTS\VISUAL STUDIO 2008\PROJECTS\ZEPHYRAIR2\ZEPHYRAIR2\APP_DATA\TBLSZEPHYRAIR.MDF;Integrated Security=True;User Instance=True"
   providerName="System.Data.SqlClient" />   -->
 </connectionStrings>
  
  
  
<system.web>

<compilation debug="true">
<assemblies>
<add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Data.DataSetExtensions, 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.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
</assemblies>
</compilation>
       
<authentication mode="Windows"/>

<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.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>
</compilers>
</system.codedom>
  
<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>



>>>>>>>WHAT DID I DO WRONG? <<<<<<<<<<<

  Web Star replied to Elvin
28-Sep-11 11:49 PM
Message are cleared told you password is invalid as you put in your code when password of database are not match to input password in textbox on login page. So you are not able to redirect to index page.

Better is You need to debug this program and you will check value for password which you are getting from database, actually problem is you are writing query to get count(*) if that Username  exists in database where as comparing that count first and than password to another query thats wrong you need to both in single query as

select username from UserAccounts where Username = '" + TextBox1.Text + " ' And  Password = '" + TextBox2.Text + "'";

And than you get valid login status
  Anoop S replied to Elvin
29-Sep-11 01:11 AM
You can refer this code for validating username password

string strConn = "Your Connection string";
SqlConnection cn = new SqlConnection(strConn);
try {
  cn.Open();
  SqlCommand cm = new SqlCommand("SELECT COUNT(*) FROM users WHERE username=? AND password=?;", cn);
  cm.Parameters.AddWithValue("?", TextBoxUsername.Text);
  cm.Parameters.AddWithValue("?", TextBoxPassword.Text);
  int count = Convert.ToInt32(cm.ExecuteScalar());
  if ((count > 0)) {
  // user successfully logged on
  // do something ->Redirect to some other Page
  } else {
  lblError.Text = "Logon failed";
  }
} catch (Exception ex) {
  lblError.Text = ex.Message();
   
} finally {
  cn.Close();
}
  dipa ahuja replied to Elvin
29-Sep-11 02:05 AM
Untitled document
Try this simple code by checking both username and password at a same time

protected void BtnLogin_Click(object sender, EventArgs e)
   {
     String conn = "<Your connectionSTring>";      
    SqlConnection connection = new SqlConnection(conn);
     connection.Open();
 
     string q = "select Count(*) from users where  username='" + txtuname.Text + "' AND pwd ='" + txtpwd.Text + "'";
 
     SqlCommand comm = new SqlCommand(q, connection);
     int result = (int)comm.ExecuteScalar();
 
     if(result>0)
     {
       Session["user"] = txtuname.Text.ToString();
       Response.Redirect("home.aspx");
     }
     else
     {
       lblerror.Text = "Either username or password in incorrect !";        
    }
     connection.Close();
   }
 
If you password is incorrect it will show you the error
Now at home page write this in page load
 
protected void Page_Load(object sender, EventArgs e)
   {
     if (Session["user"] != null)
     {
       Label1.Text = "Welcome " + Session["user"].ToString();
     }
 
  }
 
  Elvin replied to Anoop S
29-Sep-11 06:38 AM
I did the following:

using System;
using System.Collections.Generic;
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;

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

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            string strConn = "ConnectionString2";
            SqlConnection cn = new SqlConnection(strConn);
            try
            {
                cn.Open();
                SqlCommand cm = new SqlCommand("SELECT COUNT(*) FROM UserAccounts WHERE Username=? AND Password=?;", cn);
                cm.Parameters.AddWithValue("?", TextBox1.Text);
                cm.Parameters.AddWithValue("?", TextBox2.Text);
                int count = Convert.ToInt32(cm.ExecuteScalar());
                if ((count > 0))
                {
                    // user successfully logged on
                    // do something ->Redirect to some other Page
                    Response.Redirect("ZephyrIndex.aspx");
                }
                else
                {
                    Label1.Text = "Logon failed";
                }
            }
            catch (Exception ex)
            {
                Label1.Text = ex.Message;

            }
            finally
            {
                cn.Close();
            }
  
          
        }
       }
    }

I got an error that says:

Format of the initialization string does not conform to specification starting at index 0.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentException: Format of the initialization string does not conform to specification starting at index 0.

Source Error:

Line 25:         {
Line 26:             string strConn = "ConnectionString2";
Line 27:             SqlConnection cn = new SqlConnection(strConn);
Line 28:             try
Line 29:             {
  Elvin replied to Web Star
29-Sep-11 06:49 AM
Got the following Error:

Input string was not in a correct format.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.FormatException: Input string was not in a correct format.

Source Error:

Line 36:             SqlCommand Checkuser = new SqlCommand(cmdStr,con);
Line 37: 
Line 38:             int temp = Convert.ToInt32(Checkuser.ExecuteScalar().ToString());
Line 39:             
Line 40:             if (temp == 1)


HERE IS MY CODE FROM Login.aspx.cs:
using System;
using System.Collections.Generic;
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;

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

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
             
            // Setting connection object
           // SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["useThisConnStringYOOOOO!"].ConnectionString);
           SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString2"].ConnectionString);

            //Opening the connection
            con.Open();

            string cmdStr = "select Username from UserAccounts where Username = '" + TextBox1.Text + "'";

            SqlCommand Checkuser = new SqlCommand(cmdStr,con);

            int temp = Convert.ToInt32(Checkuser.ExecuteScalar().ToString());
            
            if (temp == 1)
            {
                string cmdStr2 = "select Password from UserAccounts where Password = '" + TextBox2.Text + "'";
                SqlCommand pass = new SqlCommand(cmdStr2, con);

               // string password = pass.ExecuteScalar().ToString();
                string password = pass.ToString();
                con.Close();
                
                if (password == TextBox2.Text)
                {
                    Session["New"] = TextBox1.Text;
                    Response.Redirect("ZephyrIndex.aspx");
                }
                else
                {
                    Label1.Visible = true;
                    Label1.Text = "Invalid Password. Try Again Please.";
                }
            }
                else
                {
                     Label1.Visible = true;
                    Label1.Text = "Invalid Username. Try Again Please.";
                }

            }
        }
    }


  Elvin replied to Web Star
29-Sep-11 06:56 AM
Got the same error as previous also read reply to you first for first post. This is the second relating to the same error as first reply. I did changes to the previous code section where I deleted ExecuteScalar() since it dealt with counting I guess, and got error:

Server Error in '/' Application.

Input string was not in a correct format.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.FormatException: Input string was not in a correct format.


Line 36: SqlCommand Checkuser = new SqlCommand(cmdStr,con);
 Line 37:
  Line 38: int temp = Convert.ToInt32(Checkuser.ToString());
Line 39: // ExecuteScalar(). 
Line 40: if (temp == 1)
  Web Star replied to Elvin
29-Sep-11 08:07 AM
you need to first read the article for how can use DataReader and DataAdapter and Sql parmaeter then you will yourself get the error clue
In you code you are using Checkuser.ToString() which is wrong you can't get directly any value by command object.
Please first read the basic concept and learn how can debug the program.

hope this help you
Create New Account
help
Response.Redirect I have create an error page but when any error occurs it is not getting redirected to that page i am getting error as Server Error in ' / Final Project' Application. Redirect URI cannot contain newline characters. Description: An unhandled exception occurred of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.ArgumentException: Redirect URI cannot contain newline characters. Source Error: Line 109: { Line 110: string errormessage = ex
Run time Error:ArgumentException was unhandled by user code. Code is below and yellow background on code section indicates where the error occurred. I am doing a school project . Please help: using System; using System.Collections; using Web.Configuration; using System.Data.SqlTypes; namespace zephyrAir2 { public partial class logIn : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { / / Declaring variables for login controls and setting each using a tblsZephyrAir.mdb database I created and have them redirected to the ZephyrIndex.aspx page which is the Home Page in other words. It says" ArgumentException was unhandled by user code. " It also says " Keyword not supported: 'c: \ users \ userpcone \ downloads use oldbbconnection, oledbcommand, oledbdataadapter Hope this much resolved ur issue use it on this way <%@ Page Language = " C# " Debug = "true" %> <%@ import Namespace = "CrystalDecisions.CrystalReports.Engine" %> <%@ import Namespace = "CrystalDecisions.Shared" %> <%@ import Namespace
ImageButton Refresh .NET Framework Hallo NG, I have got a Problem on an ASP.Net Page. This page shows some data in a tree view and in a drop down list. There are permanently on the button expand all, there will be sometime a problem with the ASP Page. Invalid postback or callback argument. Event validation is enabled using EnableEventValidation = "true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.ArgumentException: Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation = "true" / > in configuration or <%@ Page EnableEventValidation = "true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from
find in page error I have a user control, this user control resides on a page, and this page uses a master page. On the user control, there are an input text box and a button, when the user clicks the button, the application needs to find the text on the page and highlight it. Here is the code, but it gave me an error. I have searched the web, this is a common code I found on the web used for search. Do you know what caused the error and how to solve the error? Thanks. < script type = "text / javascript" language = "javascript"> var NS4
Craete tiff Image Page by Page .NET Framework Hi, Please help me to write a dll in C# , that will read P C# Discussions MemoryStream (1) EncoderParameters (1) ImageCodecInfo (1) FileStream (1) FrameDimension (1) SelectActiveFrame (1) ArgumentException (1) EncoderValue (1) Last time I needed to mess with multi-page TIFs, I used ImageMan (ActiveX at the time). Perhaps an off-the-shelf like this Encoder.SaveFlag, (long)EncoderValue.MultiFrame); ep.Param[1] = new EncoderParameter(Encoder.Compression, imgCompression); } else { / / / / Single page / / ep = new EncoderParameters(1); ep.Param[0] = new EncoderParameter(Encoder.Compression, imgCompression); } / / / / Save the first page / / imgTif.Save(singleStream, CodecInfo, ep); if (tifsStream.Length > 1) { ep = new EncoderParameters(2); ep.Param ep = null; Image tifImage = null; try { tifImage = Image.FromStream(tifStream); int pgCount = tifImage.GetFrameCount(FrameDimension.Page); multiStream = new System.IO.MemoryStream[pgCount]; for (int i = 0; i < pgCount; i++) { tifImage.SelectActiveFrame(FrameDimension.Page, i); multiStream[i] = new System.IO.MemoryStream(); long imgCompression = GetCompression(tifImage); ep = new EncoderParameters(1