0

I have a form in which you can enter your email and then receives instructions on resetting the password. It has a textbox (txtEmail), a Submit button (btnResetPassword) and a lblMessage.

My C# code looks like this:

protected void btnResetPassword_Click(object sender, EventArgs e)
{
    string CS = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

    using (SqlConnection con = new SqlConnection(CS))
    {
        SqlCommand cmd = new SqlCommand("spResetPassword", con);
        cmd.CommandType = CommandType.StoredProcedure;

        SqlParameter paramEmail = new SqlParameter("@Email", txtEmail.Text);
        cmd.Parameters.Add(paramEmail);

        con.Open();

        SqlDataReader rdr = cmd.ExecuteReader();

        while (rdr.Read())
        {
            if (Convert.ToBoolean(rdr["ReturnCode"]))
            {
                SendPasswordResetEmail(rdr["Email"].ToString(), rdr["UniqueId"].ToString());
                lblMessage.Text = "An email with instructions to reset your password is sent to your registered email";
            }
            else
            {
                lblMessage.ForeColor = System.Drawing.Color.Red;
                lblMessage.Text = "Username not found!";
            }
        }
    }
} 

I then have a method SendPasswordResetEmail(string email, string ID) which works fine (SMTP).

The stored procedure is:

CREATE PROC Spresetpassword @Email NVARCHAR(100) 
AS 
BEGIN 
    DECLARE @UserId INT 

    SELECT @UserId = id 
    FROM dbo.turiststbl 
    WHERE email = @Email 

    IF (@UserId IS NOT NULL) 
    BEGIN 
        --If username exists 
        DECLARE @GUID UNIQUEIDENTIFIER 

        SET @GUID = Newid() 

        INSERT INTO tblresetpasswordrequests (id, userid, resetrequestdatetime)
        VALUES (@GUID, @UserId, Getdate()) 

        SELECT 
            1 AS ReturnCode, 
            @GUID AS UniqueId, 
            @Email AS Email 
    END 
    ELSE 
    BEGIN 
        --If username does not exist 
        SELECT 
            0 AS ReturnCode, 
            NULL AS UniqueId, 
            NULL AS Email 
    END
END

When I enter my email, I get the following error:

See Screenshot Here

What can I do?
Edit: Database files are not local, they are on a remote server

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
bashbin
  • 415
  • 1
  • 7
  • 21
  • Seems you have a database connection string problem. Can you mention current DB connection string? – Tetsuya Yamamoto Apr 06 '17 at 02:14
  • From the web.config file: @TetsuyaYamamoto – bashbin Apr 06 '17 at 02:16
  • Please don't post screen shots of error messages. See where it says “Copy exception detail to the clipboard”? Click that and post the message to your question. – Dour High Arch Apr 06 '17 at 02:18
  • Try removing the `InitialCatalog` part on your connection string and it should working fine (I'll post an answer as clarification for this). – Tetsuya Yamamoto Apr 06 '17 at 02:20
  • @DourHighArch Well, the error message is way too long. Here is the clipboard of the details http://www.heypasteit.com/clip/YALKQ – bashbin Apr 06 '17 at 02:23
  • @TetsuyaYamamoto Hmm, now it's displaying this additional information: Additional information: An attempt to attach an auto-named database for file C:\Users\Hp-Pc\Desktop\VizitoSiteMaster\Vizito\App_Data\aspnet-Vizito-20170305102044.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share. – bashbin Apr 06 '17 at 02:26
  • @Arti You need to use direct file path instead of `DataDirectory` on connection string if you want to use `LocalDb` instance. Give me a few minutes to compose full answer for your problems. – Tetsuya Yamamoto Apr 06 '17 at 02:29
  • @TetsuyaYamamoto Alright, thank you for trying! It's worth mentioning that I have other parts of web page that get data from my SQL server database just fine, but in this case where I used a different method (with stored procedure) - not. I'm looking forward to your answer – bashbin Apr 06 '17 at 02:35

1 Answers1

0

The problem origins from connection string inside web.config file:

<connectionStrings> 
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;
    AttachDbFilename=|DataDirector‌​y|\aspnet-Vizito-201‌​70305102044.mdf;
    Init‌​ial Catalog=aspnet-Vizito-20170305102044;
    Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>

Here you're attempting to use LocalDb instance by mentioning AttachDbFilename parameter on connecting string attribute, and it shouldn't use Initial Catalog parameter on the same string.

Hence, by removing Initial Catalog part, the connection string should be like this:

<connectionStrings> 
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;
    AttachDbFilename=|DataDirector‌​y|\aspnet-Vizito-201‌​70305102044.mdf;
    Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>

Additionally, if the database file placed outside of App_Data directory inside the project, you may require full file path to refer its location as this:

<connectionStrings> 
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;
    AttachDbFilename=C:\Users\Hp-Pc\Desktop\VizitoSiteMaster\Vizito\App_Data\aspn‌​et-Vizito-2017030510‌​2044.mdf;
    Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>

Update:

According to OP explaining that the DB takes place on remote server instance, the connection string should use Initial Catalog like this:

<connectionStrings> 
    <add name="DefaultConnection" connectionString="Data Source=[server address];
    Init‌​ial Catalog=aspnet-Vizito-20170305102044; User Id=[user ID]; Password=[password]; 
    Integrated Security=SSPI" providerName="System.Data.SqlClient" />
</connectionStrings>

NB: Replace [server address] with remote server IP address (with port if exists), [user ID] & [password] with user credentials used on the remote server.

References:

SQL Server Connection String

Cannot attach the file *.mdf as database

An attempt to attach an auto-named database for file ....database1.mdf failed

Community
  • 1
  • 1
Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61
  • Pardon me, I should have mentioned that the database is not local. It's on a remote server, therefore app_data folder is empty. As I can see, there is no .mdf file on my project folder – bashbin Apr 06 '17 at 02:50
  • If the DB is in remote server, avoid using `LocalDb` instance, use `Initial Catalog` and place the connection string depending on the server address & DB name instead. But I'll leave `LocalDb` problem explanations in case someone encounters same problem in the future. – Tetsuya Yamamoto Apr 06 '17 at 02:52
  • Nice! I actually fixed the problem by typing SqlConnection con = new SqlConnection("Data Source = myServerAddress; Initial Catalog = myDataBase; User Id = myUsername; Password = myPassword;"); instead of just SqlConnection conn = new SqlConnection(CS); Thank you @TetsuyaYamamoto – bashbin Apr 06 '17 at 03:02