Solved

Airline dbConnect.Close() unassigned.

Posted on 2012-04-06
12
413 Views
Last Modified: 2012-04-06
Error      1      Use of unassigned local variable 'dbConnection'      C:\Course Technology\CIS Programming\ASP .NET Programming\Data Files\Chapter.09\Chapter\SkywardAviation\Registration.aspx.cs      30      17      C:\...\SkywardAviation\

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsPostBack
            && enrollmentForm.ActiveViewIndex == 0)
            hiddenPassword.Value = password.Text;
    }
    protected void Page_LoadComplete(object sender, EventArgs e)
        {
             SqlConnection dbConnection;
if (Page.IsPostBack
            && enrollmentForm.ActiveViewIndex == 3)
        {
            dbConnection
                = new SqlConnection(
                    "Data Source=.\\SQLEXPRESS; AttachDbFilename=C:\\Course Technology\\CIS Programming\\ASP .NET Programming\\Data Files\\Chapter.09\\Chapter\\SkywardAviation.mdf; Integrated Security=True; User Instance=True");
            }
                             
            try
            {
                dbConnection.Open();
                SqlCommand sqlCommand = new SqlCommand(
                "INSERT INTO FrequentFlyers (last, first,"
                + " phone, email, password, cardType,"
                + " expireMonth, expireYear, cardnumber,"
                + " cardholder, address, city, state, zip,"
                + " travelerType, homeAirport, class, seat,"
                + " meal) VALUES("
                + "'" + lastName.Text + "',"
                + "'" + firstName.Text + "',"
                + "'" + telephone.Text + "',"
                + "'" + email.Text + "',"
                + "'" + hiddenPassword.Value + "',"
                + "'" + creditcard.Text + "',"
                + "'" + expireMonth.Text + "',"
                + "'" + expireYear.Text + "',"
                + "'" + cardnumber.Text + "',"
                + "'" + cardholder.Text + "',"
                + "'" + address.Text + "',"
                + "'" + city.Text + "',"
                + "'" + state.Text + "',"
                + "'" + zip.Text + "',"
                + "'" + travelerType.Text + "',"
                + "'" + homeAirport.Text + "',"
                + "'" + serviceClass.Text + "',"
                + "'" + seatPreference.Text + "',"
                + "'" + mealRequest.Text + "',)",
                dbConnection);
            sqlCommand.ExecuteNonQuery();
            sqlCommand = new SqlCommand(
                "SELECT IDENT_CURRENT('FrequentFlyers')",
                dbConnection);
            SqlDataReader lastID=
                sqlCommand.ExecuteReader();
            if (lastID.Read())
                successString.Text += "<h3>Enrollment Sucessful</h3>" +
                "<p>Your frequent flyer number is " +
                lastID.GetValue(0) + ".</p>";
        }
       catch (SqlException exception)
       {
            successString.Text += "<p>Error code "
                + exception.Number
                + ": " + exception.Message + "</p>";
}
dbConnection.Close();
       
}
}

this is homework.  I just have this error.  I do not understand why I am getting this error.  Thank you.  It says that the dbConnect.Open() is unassigned.  I really appreciate the patience of the experts.
homework-image.pdf
0
Comment
Question by:assaultkitty
  • 5
  • 5
  • 2
12 Comments
 
LVL 74

Expert Comment

by:käµfm³d 👽
Comment Utility
This is because the only place you initialized your dbConnect variable is within the body of your if block. What happens if your if is never entered? You need to make sure all paths through your code prior to your usage of dbConnect either initialize this variable or return from the function (if appropriate).
0
 
LVL 16

Expert Comment

by:Vikram Singh Saini
Comment Utility
For code part:

dbConnection
                = new SqlConnection(
                    "Data Source=.\\SQLEXPRESS; AttachDbFilename=C:\\Course Technology\\CIS Programming\\ASP .NET Programming\\Data Files\\Chapter.09\\Chapter\\SkywardAviation.mdf; Integrated Security=True; User Instance=True");

Open in new window


I would like to share something. Why don't you put the .mdf file in App_Data folder? As it is meant for such tasks. And then write connection string as:

string conString = @"Data Source=.\\SQLEXPRESS; AttachDbFilename=|DataDirectory|\SkywardAviation.mdf; Integrated Security=True; User Instance=True";

Open in new window


Second if you have noticed we have added verbatim (@) before conString value otherwise compiler would throw error for newline constant in string for //.

So I assume that actually the error is newline constant (something like that) but compiler is pointing to other one. Try suggestions and let us know if problem still persists.
0
 
LVL 74

Expert Comment

by:käµfm³d 👽
Comment Utility
@vs00saini

EE wrapped her connection string when she pasted it into the text box during the creation of his question. If you copy/paste to a text editor, you will see that it is only one line  = )
0
 

Author Comment

by:assaultkitty
Comment Utility
I am not getting a newline constant error. I am getting the following error:


Error      1      Use of unassigned local variable 'dbConnection'      C:\Course Technology\CIS Programming\ASP .NET Programming\Data Files\Chapter.09\Chapter\SkywardAviation\Registration.aspx.cs      30      17      C:\...\SkywardAviation\


Neither of the suggestion from the experts worked. Also, I looked on Google first before I asked. I could not find a proper solution.
0
 
LVL 74

Expert Comment

by:käµfm³d 👽
Comment Utility
Neither of the suggestion from the experts worked.
That's rather bold, since I didn't actually suggest code, but rather what you needed to do to correct the issue. Please show what you did to try to correct the issue. I assure you that your issue is as I mentioned.
0
 
LVL 16

Accepted Solution

by:
Vikram Singh Saini earned 500 total points
Comment Utility
@kaufmed

Yes! You are right. Actually I thought that otherwise. And your first comment is true for solution. I'm just elaborating it codewise.


protected void Page_LoadComplete(object sender, EventArgs e)
        {
             SqlConnection dbConnection = new SqlConnection(
                    "Data Source=.\\SQLEXPRESS; AttachDbFilename=C:\\Course Technology\\CIS Programming\\ASP .NET Programming\\Data Files\\Chapter.09\\Chapter\\SkywardAviation.mdf; Integrated Security=True; User Instance=True");

if (Page.IsPostBack
            && enrollmentForm.ActiveViewIndex == 3)
        {
             // your code part here
            // we have initialized dbConnection out of if so that in any case it would be initialized
        }
0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 

Author Comment

by:assaultkitty
Comment Utility
I am sorry Kaufmed. I tried your suggest, too.  I did put the connection string on one line.  The error did not resolve itself.  I apologize.  We are almost there.  I will cut and paste the suggestion so that you can see what I am talking about. I do know what a connection string is.  

Here is the code that I used for the suggestions.

First suggestion.  I pasted the connection string on one line.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsPostBack
            && enrollmentForm.ActiveViewIndex == 0)
            hiddenPassword.Value = password.Text;
    }
    protected void Page_LoadComplete(object sender, EventArgs e)
        {
             SqlConnection dbConnection;
if (Page.IsPostBack
            && enrollmentForm.ActiveViewIndex == 3)
        {
            dbConnection= new SqlConnection("Data Source=.\\SQLEXPRESS; AttachDbFilename=C:\\Course Technology\\CIS Programming\\ASP .NET Programming\\Data Files\\Chapter.09\\Chapter\\SkywardAviation.mdf; Integrated Security=True; User Instance=True");
            }
                             
            try
            {
                dbConnection.Open();
                SqlCommand sqlCommand = new SqlCommand(
                "INSERT INTO FrequentFlyers (last, first,"
                + " phone, email, password, cardType,"
                + " expireMonth, expireYear, cardnumber,"
                + " cardholder, address, city, state, zip,"
                + " travelerType, homeAirport, class, seat,"
                + " meal) VALUES("
                + "'" + lastName.Text + "',"
                + "'" + firstName.Text + "',"
                + "'" + telephone.Text + "',"
                + "'" + email.Text + "',"
                + "'" + hiddenPassword.Value + "',"
                + "'" + creditcard.Text + "',"
                + "'" + expireMonth.Text + "',"
                + "'" + expireYear.Text + "',"
                + "'" + cardnumber.Text + "',"
                + "'" + cardholder.Text + "',"
                + "'" + address.Text + "',"
                + "'" + city.Text + "',"
                + "'" + state.Text + "',"
                + "'" + zip.Text + "',"
                + "'" + travelerType.Text + "',"
                + "'" + homeAirport.Text + "',"
                + "'" + serviceClass.Text + "',"
                + "'" + seatPreference.Text + "',"
                + "'" + mealRequest.Text + "',)",
                dbConnection);
            sqlCommand.ExecuteNonQuery();
            sqlCommand = new SqlCommand(
                "SELECT IDENT_CURRENT('FrequentFlyers')",
                dbConnection);
            SqlDataReader lastID=
                sqlCommand.ExecuteReader();
            if (lastID.Read())
                successString.Text += "<h3>Enrollment Sucessful</h3>" +
                "<p>Your frequent flyer number is " +
                lastID.GetValue(0) + ".</p>";
        }
       catch (SqlException exception)
       {
            successString.Text += "<p>Error code "
                + exception.Number
                + ": " + exception.Message + "</p>";
}
    dbConnection.Close();
       
}
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsPostBack
            && enrollmentForm.ActiveViewIndex == 0)
            hiddenPassword.Value = password.Text;
    }
    protected void Page_LoadComplete(object sender, EventArgs e)
        {
             SqlConnection dbConnection;
if (Page.IsPostBack
            && enrollmentForm.ActiveViewIndex == 3)
        {
            string conString = @"Data Source=.\\SQLEXPRESS; AttachDbFilename=|DataDirectory|\SkywardAviation.mdf; Integrated Security=True; User Instance=True";
        }
                             
            try
            {
                dbConnection.Open();
                SqlCommand sqlCommand = new SqlCommand(
                "INSERT INTO FrequentFlyers (last, first,"
                + " phone, email, password, cardType,"
                + " expireMonth, expireYear, cardnumber,"
                + " cardholder, address, city, state, zip,"
                + " travelerType, homeAirport, class, seat,"
                + " meal) VALUES("
                + "'" + lastName.Text + "',"
                + "'" + firstName.Text + "',"
                + "'" + telephone.Text + "',"
                + "'" + email.Text + "',"
                + "'" + hiddenPassword.Value + "',"
                + "'" + creditcard.Text + "',"
                + "'" + expireMonth.Text + "',"
                + "'" + expireYear.Text + "',"
                + "'" + cardnumber.Text + "',"
                + "'" + cardholder.Text + "',"
                + "'" + address.Text + "',"
                + "'" + city.Text + "',"
                + "'" + state.Text + "',"
                + "'" + zip.Text + "',"
                + "'" + travelerType.Text + "',"
                + "'" + homeAirport.Text + "',"
                + "'" + serviceClass.Text + "',"
                + "'" + seatPreference.Text + "',"
                + "'" + mealRequest.Text + "',)",
                dbConnection);
            sqlCommand.ExecuteNonQuery();
            sqlCommand = new SqlCommand(
                "SELECT IDENT_CURRENT('FrequentFlyers')",
                dbConnection);
            SqlDataReader lastID=
                sqlCommand.ExecuteReader();
            if (lastID.Read())
                successString.Text += "<h3>Enrollment Sucessful</h3>" +
                "<p>Your frequent flyer number is " +
                lastID.GetValue(0) + ".</p>";
        }
       catch (SqlException exception)
       {
            successString.Text += "<p>Error code "
                + exception.Number
                + ": " + exception.Message + "</p>";
}
    dbConnection.Close();
       
}
}
0
 
LVL 74

Expert Comment

by:käµfm³d 👽
Comment Utility
Please reread my first comment, and be sure you understand what I indicating. As a simplified example, the following is what you have. For the sake of simplicity, when I say "initialization," think "new".

SqlConnection dbConnection;  // 1

if (true)   // 2
{
    dbConnection = new SqlConnection("some string");
}

dbConnection.Open();   // 3

Open in new window


In the above, these are the three things going on:

1.

A variable of type SqlConnection is being declared

2.

An if statement initializes the variable

3.

The instantiated variable has a method called against it
In the above, I have hard-coded the condition for the if to true, so it will always execute, and the variable will always be initialized. Since the variable is initialized, the call to the method in #3 will run just fine, because there is an object in memory to execute the method against. Now, what if I take that same code, and I change the hard-coded value for #2 in this way:

SqlConnection dbConnection;  // 1

if (false)   // 2
{
    dbConnection = new SqlConnection("some string");
}

dbConnection.Open();   // 3

Open in new window


Now the condition for the if can never be true (i.e. it's always false), which means the variable never gets initialized. This is a problem.

When a variable isn't properly initialized, it's value defaults to null.* It is very bad to have null variables, and the reason is that you cannot call a method against a null variable--there is nothing in memory to execute against. If we left the code with the hard-coded false for #2, then #3 will raise an exception because you are trying to execute a method against null. This both can never happen and does not make sense. You must be sure to initialize your variables--no matter what conditions your code may or may not check. There are a couple of ways you can solve your issue, but rather than just telling you an answer (which is rather taboo on EE since this is technically a homework question), I am trying to get you to think about why you are getting the behavior you are getting.

* This is only for reference types. I didn't want to get too deep into that with you though, so I generalized. Value types cannot be null.
0
 

Author Comment

by:assaultkitty
Comment Utility
Here is the textbook I am using to do this program.  It is not the answer you are giving me.  I have to do 9.1 Project in the book for to turn in. I just want to make sure that it is working before I do the project.  I understand what you are say.  I just want you to look at the book to see what I have to do.
homework-image.pdf
Project.pdf
homework-1.pdf
0
 
LVL 74

Expert Comment

by:käµfm³d 👽
Comment Utility
According to the instructions on page 473, I believe the authors intended for you to put the try/catch within the body of the if block (i.e. before the if's closing brace). You currently have your try/catch outside of the body of the if block. The wording of that part of the question is a bit confusing.
0
 

Author Comment

by:assaultkitty
Comment Utility
I almost overlooked your message.  I found it and it is working.  The website came up.  You are an EXPERT.  I think your attentiveness and understanding.
0
 

Author Closing Comment

by:assaultkitty
Comment Utility
This one did the trick.  I do not know what to add to the comments in this statement.  This author is a mess.
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

User art_snob (http://www.experts-exchange.com/M_6114203.html) encountered strange behavior of Android Web browser on his Mobile Web site. It took a while to find the true cause. It happens so, that the Android Web browser (at least up to OS ver. 2.…
Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now