pcs
pcs

Reputation: 1854

How to use GUID for adding records in c#?

I am creating student records using c# and asp .net. For this, I added 5 fields - name, class, section, address and image.

When inserting student1.jpg, it works fine. Problem appears When I insert second record for same name (student1.jpg) with different image. Insertion fails with some error like "image already exists".

After I understood the purpose of GUID, I want to use these for my work.

Is it possible to do so and if yes, can someone help me?

Here is my full code-behind file:

protected void btnsub_Click(object sender, EventArgs e)
        {
            SqlConnection con = Connection.DBconnection();
            if (Textid.Text.Trim().Length > 0)
            {
                SqlCommand com = new SqlCommand("StoredProcedure3", con);
                com.CommandType = CommandType.StoredProcedure;
                com.Parameters.AddWithValue("@id", Textid.Text.Trim());
                com.Parameters.AddWithValue("@Name", Textusername.Text.Trim());
                com.Parameters.AddWithValue("@Class", Textclass.Text.Trim());
                com.Parameters.AddWithValue("@Section", Textsection.Text.Trim());
                com.Parameters.AddWithValue("@Address", Textaddress.Text.Trim());
                try
                {
                    string filename = Image1.ImageUrl.Substring(Image1.ImageUrl.IndexOf('/')+1);

                    if (fileupload.PostedFile.FileName.Length > 0)
                    {      
                        filename = Path.GetFileName(fileupload.PostedFile.FileName);                        
                        fileupload.SaveAs(Server.MapPath("~/Images/" + filename));
                    }                  
                    com.Parameters.AddWithValue("@Image",(filename.Length>0)? "Images/" + filename:string.Empty);
                    com.ExecuteNonQuery();                    
                }
                catch (Exception ex)
                {
                    btnsub.Text = ex.Message;
                }
                    Response.Redirect("studententry.aspx");
            }
            else
            {
                SqlCommand com = new SqlCommand("StoredProcedure1", con);
                com.CommandType = CommandType.StoredProcedure;
                com.Parameters.AddWithValue("@Name", Textusername.Text.Trim());
                com.Parameters.AddWithValue("@Class", Textclass.Text.Trim());
                com.Parameters.AddWithValue("@Section", Textsection.Text.Trim());
                com.Parameters.AddWithValue("@Address", Textaddress.Text.Trim());
                try
                {
                    string filename = string.Empty;
                    if (fileupload.PostedFile.FileName.Length > 0)
                    {
                        filename = Path.GetFileName(fileupload.PostedFile.FileName);
                        if (File.Exists(Server.MapPath("~/Images/" + filename)))
                        {
                            Label6.Visible = true;
                            return;
                        }

                        fileupload.SaveAs(Server.MapPath("~/Images/" + filename));
                    }
                        com.Parameters.AddWithValue("@Image",(filename.Length>0)? "Images/" + filename:string.Empty);
                        com.ExecuteNonQuery();                    
                }
                catch (Exception ex)
                {
                    btnsub.Text = ex.Message;
                }
                    Response.Redirect("studententry.aspx");
            }
        }           

Thank you.

Upvotes: 1

Views: 882

Answers (3)

Ved Prakash Tiwari
Ved Prakash Tiwari

Reputation: 267

If i understood your problem:

These changes are enough with your original code for use of GUID.

  1. make change in db table "Student" for column Id from "int" to "NVARCHAR(36)"

  2. Form Code behind Pass "Id" parameter values as

    string ID = Guid.NewGuid().ToString();

    com.Parameters.AddWithValue("@id", ID);

  3. you can keep image name as original name.

OR------

U can directly genarat GUID in DataBase also as follows

ALTER PROCEDURE StoredProcedure3
(    
   @Name Varchar (100),
   @Class varchar (50),
   @Section Varchar (50),
   @Address Varchar (50),
   @Image Varchar (50)
)
AS
begin

   DECLARE  @id NVARCHAR(36);
   SET @id = NEWID();

   Update Student set Name = @Name, Class= @Class, Section= @Section,  Address = @Address, Image = @Image where id=@id
End

Upvotes: 1

CloudyOne
CloudyOne

Reputation: 161

Assuming that Id is the primary key on your table, then just replace

com.Parameters.AddWithValue("@id", Textid.Text.Trim());

with

com.Parameters.AddWithValue("@id", System.Guid.NewGuid().ToString());

If this doesn't resolve your issue, I could assist further if you provided the structure of your table, or the code in your stored procedure.

--EDIT-- With your edits, my answer no longer makes sense as we now know that varchar isn't acceptable as id and the error is being thrown at the point of the fileupload.SaveAs().

Suprabhat Biswal is on the right track as you should be using GUID to be changing your file name.

Here's some updated code, NOTE that i changed the id back to the Textid.Text.Trim().

protected void btnsub_Click(object sender, EventArgs e)
{
    SqlConnection con = Connection.DBconnection();
    if (Textid.Text.Trim().Length > 0)
    {
        SqlCommand com = new SqlCommand("StoredProcedure3", con);
        com.CommandType = CommandType.StoredProcedure;
        com.Parameters.AddWithValue("@id", Textid.Text.Trim());
        com.Parameters.AddWithValue("@Name", Textusername.Text.Trim());
        com.Parameters.AddWithValue("@Class", Textclass.Text.Trim());
        com.Parameters.AddWithValue("@Section", Textsection.Text.Trim());
        com.Parameters.AddWithValue("@Address", Textaddress.Text.Trim());
        try
        {

            var filename = string.Format("{0}.{1}", Guid.NewGuid().ToString(), Path.GetExtension(fileupload.PostedFile.FileName).ToLower());
            var full_path = Server.MapPath("~/Images/", filename);
            if (fileupload.PostedFile.FileName.Length > 0)
            {                        ;
                fileupload.SaveAs(full_path);
            }
            com.Parameters.AddWithValue("@Image", (filename.Length > 0) ? "Images/" + filename : string.Empty);
            com.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            btnsub.Text = ex.Message;
        }
        Response.Redirect("studententry.aspx");
    }
    else
    {
        SqlCommand com = new SqlCommand("StoredProcedure1", con);
        com.CommandType = CommandType.StoredProcedure;
        com.Parameters.AddWithValue("@Name", Textusername.Text.Trim());
        com.Parameters.AddWithValue("@Class", Textclass.Text.Trim());
        com.Parameters.AddWithValue("@Section", Textsection.Text.Trim());
        com.Parameters.AddWithValue("@Address", Textaddress.Text.Trim());

        try
        {
            string filename = string.Empty;
            if (fileupload.PostedFile.FileName.Length > 0)
            {
                var filename = string.Format("{0}.{1}", Guid.NewGuid().ToString(), Path.GetExtension(fileupload.PostedFile.FileName).ToLower());
                var full_path = Server.MapPath("~/Images/", filename);                        
                // This IF statement should never be hit since we're using GUID for the file name.
                if (File.Exists(full_path))
                {
                    Label6.Visible = true;                            
                    return;
                }
                fileupload.SaveAs(full_path);
            }
            com.Parameters.AddWithValue("@Image", (filename.Length > 0) ? "Images/" + filename : string.Empty);
            com.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            btnsub.Text = ex.Message;
        }
        Response.Redirect("studententry.aspx");
    }
}

Upvotes: 3

Suprabhat Biswal
Suprabhat Biswal

Reputation: 3216

Namespace: using System.IO;

For StoredProdure3:

string filename = Image1.ImageUrl.Substring(Image1.ImageUrl.IndexOf('/')+1);
if (fileupload.PostedFile.FileName.Length > 0)
{      
    filename = Path.GetFileName(fileupload.PostedFile.FileName); 
    string fileExtension = Path.GetExtension(filename).ToLower();  // this will give you file extension.
    string uniqueFileName = Guid.NewGuid().ToString() + fileExtension;   // this will give you unique filename.
    fileupload.SaveAs(Server.MapPath("~/Images/" + uniqueFileName)); // save the image with guid name.
    com.Parameters.AddWithValue("@Image",(filename.Length > 0) ? "Images/" + uniqueFileName : string.Empty); // now you can save the new filename in database for associated record.
} 

For StoredProdure1:

string filename = string.Empty;
if (fileupload.PostedFile.FileName.Length > 0)
{
    filename = Path.GetFileName(fileupload.PostedFile.FileName);
    if (File.Exists(Server.MapPath("~/Images/" + filename)))
    {
        Label6.Visible = true;
        return;
    }
    string fileExtension = Path.GetExtension(filename).ToLower();  // this will give you file extension.
    string uniqueFileName = Guid.NewGuid().ToString() + fileExtension;   // this will give you unique filename.
    fileupload.SaveAs(Server.MapPath("~/Images/" + uniqueFileName)); // save the image with guid name.
}
com.Parameters.AddWithValue("@Image",(filename.Length > 0)? "Images/" + uniqueFileName : string.Empty);
com.ExecuteNonQuery();

Now all uploaded images that will be saved to drive will have unique name even if original filename is same but images are different.

Upvotes: 4

Related Questions