Solved

Scope Question - "Local Variable Already Defined in Scope"

Posted on 2008-10-14
6
1,192 Views
Last Modified: 2013-12-17
Hello!

I am new to development of any kind and I have what I think is a scope problem but I do not know how to fix it.  

What I am trying to do:
The page in question (FileUpload.aspx) is a page that allows a user to upload a file to a folder.  I am trying to capture the fileid (scope_identity) and username (of the user logged in) (I have done this).  The next part is to use the username as a parameter for a stored proc that will return the guid for the username value.

After I have both the fileid and the userid (guid), I need to run an insert stored proc that inputs both to a linking table. This table has an id pk, userid, fileid.


Where I am stuck:
I had help in setting this next part up and I really do not yet fully understand everything that is happening here (at least not enough to really trouble shoot).  What I have is another page (ClientFileRepository.aspx) that has a class with several methods for retrieving data from stored procs.  On the original page (FileUpload.aspx) I am using two methods in one "if" block - one is an insert, the other a select.  The build fails and tells me that "A local variable "repository" is already defined in this scope." but if I rename it, it renames it in both instances.

At this point I am in over my head...I thought I needed them together because each returns a value I need to insert into a table.  I am at a loss as to how this should be rewritten so that I can grab both values and insert them into my table.  I assume this will require yet another method which will just complicate the matter further.

Can anyone tell me what I am doing wrong?  Any help would be appreciated!!

Thanks,
AJ
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;  //had to add to connect to sql
 
 
 
 
namespace FileTransfer2
{
    
    public partial class FileUpload : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            
        }
 
        protected void lbtnReturntoHome_Click(object sender, EventArgs e)
        {
            Response.Redirect("default.aspx");
        }
 
        
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            //lblResults.Text = "";
            
            if (FileUpload1.HasFile)
                try
                {
                    string folderPath = ConfigurationManager.AppSettings["UploadDirectory"]; 
                    string filePath = System.IO.Path.Combine(folderPath, FileUpload1.FileName); //concatenates path + file name
                    FileUpload1.SaveAs(filePath); 
 
                    lblResults.Text = "File Successfully Uploaded: <br>" + "File name: " +
                        FileUpload1.FileName + "<br>" + 
                        FileUpload1.PostedFile.ContentLength + " kb<br>" +
                        "Content type: " +
                        FileUpload1.PostedFile.ContentType;
 
                    ClientFileRepository repository = new ClientFileRepository();
                    int fileid = repository.InsertNewFile(FileUpload1.FileName, txtDescription.Text, filePath);
                    string UserName = User.Identity.Name;
 
 
                    //This is where I am having a problem
                    ClientFileRepository repository = new ClientFileRepository();
                    DataTable UserGuid = repository.GetUserGuid(UserName);
                    if (UserGuid != null && UserGuid.Rows.Count > 0)
                    {
                        string UserID = UserGuid.Rows[0]["UserId"].ToString();
                        Response.Write(UserID);
                    }
 
                    else
                    {
                        Response.Write("No userid found.");
                    }
 
 
                    lblError.Text = "";
 
                    
                }
                
                catch (Exception ex) //this should catch if jibberish is entered but it doesn't
                {
                    //lblError.Text = "Error: File was not found.";
                    Response.Write("Error: " + ex.Message);
                }
            else
            {
                txtDescription.Text = "";
                lblResults.Text = "";
                lblError.Text = "You have not specified a file.";
            }
 
                        
        }
    }
}
 
 
 
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
 
namespace FileTransfer2
{
    public class ClientFileRepository
    {
 
        public int InsertNewFile(string fileName, string description, string clientfile)
        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["FileTransferConnectionString"].ToString()))
            {
                using (SqlCommand cmd = new SqlCommand("InsertNewFile", conn)) //stored proc name
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@FileName", fileName);
                    cmd.Parameters.AddWithValue("@Description", description);
                    cmd.Parameters.AddWithValue("@ClientFile", clientfile);
                    conn.Open();
                    return int.Parse(cmd.ExecuteScalar().ToString()); //returns scope_identity from proc
                }
            }
        }
 
 
        public DataTable GetFileInfo(int id)
        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["FileTransferConnectionString"].ToString()))
            {   
                using (SqlCommand cmd = new SqlCommand("getFilebyFileID", conn)) //stored proc name
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@Id", id);
 
                    SqlDataAdapter daFilesbyId = new SqlDataAdapter(cmd);
                    DataTable FilesbyId = new DataTable();
                    conn.Open();
                    daFilesbyId.Fill(FilesbyId);
                    return FilesbyId;
                }
            }
        }
 
        public DataTable GetUserGuid(string UserName)
        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["FileTransferConnectionString"].ToString()))
            {
                using (SqlCommand cmd = new SqlCommand("getUserID", conn))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@UserName", UserName);
 
                    SqlDataAdapter daGetUserGuid = new SqlDataAdapter(cmd);
                    DataTable UserGuid = new DataTable();
                    conn.Open();
                    daGetUserGuid.Fill(UserGuid);
                    return UserGuid;
                }
            }
        }
 
 
        
    }
}
 
 
SQL:
 
ALTER proc [dbo].[getUserID]
	@UserName nvarchar(256)
 
AS
 
select
	u.UserId
 
from aspnet_Users u
where u.UserName = @UserName

Open in new window

0
Comment
Question by:AJ0424
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
6 Comments
 
LVL 14

Expert Comment

by:CyrexCore2k
ID: 22717997
Change

ClientFileRepository repository = new ClientFileRepository();

to

repository = new ClientFileRepository();
0
 
LVL 16

Assisted Solution

by:Gyanendra Singh
Gyanendra Singh earned 100 total points
ID: 22718087
remove this line

//This is where I am having a problem
                    ClientFileRepository repository = new ClientFileRepository();
0
 
LVL 16

Accepted Solution

by:
CuteBug earned 300 total points
ID: 22718139
You are declaring "ClientFileRepository repository" two times in the same scope at Line numbers 49 and 55.
Both these lines are in the same scope i.e. within the same pair of curly brackets. {}

The two declarations confuse the compiler, that's why it generates the error. The compiler finds that you have already declared a variable of the same name before.

So you have two options to solve the error
1. Remove the statement at line 55
2. Change the statement at line 55 to
                repository = new ClientFileRepository();
           This will cause the object created at line 49 to be disposed and made available for Garbage collection. The variable will now point to a new object at line 55.
    But looking at the flow of the code, this will not give you the expected results.

   So my opinion is to go with the first option. Remove line 55.
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 26

Assisted Solution

by:Anurag Thakur
Anurag Thakur earned 100 total points
ID: 22718502
i dont think that the statement at line no. 55 ClientFileRepository repository = new ClientFileRepository(); is required at all
0
 

Author Comment

by:AJ0424
ID: 22720196
Thanks everyone!  That worked perfectly and now I have a better understanding of what that code is actually doing!

I appreciate it!!
AJ
0
 

Author Closing Comment

by:AJ0424
ID: 31506169
Thank you all very much - I hope you don't mind, I split the points since you all helped me.

CuteBug, I especially appreciate the explanation behind your answer - it cleared up a bit of the mystery for me!

Thanks,
AJ
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
AJAX ModalPopupExtender will Not Hide in Asp.net 1 40
Name Space error VS2015 1 38
ASP.net Markup for Sub Menu 2 46
Record locking on classic ASP 3 41
In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
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.…
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…
Finding and deleting duplicate (picture) files can be a time consuming task. My wife and I, our three kids and their families all share one dilemma: Managing our pictures. Between desktops, laptops, phones, tablets, and cameras; over the last decade…

696 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