Wrox Programmer Forums
Go Back   Wrox Programmer Forums > ASP.NET and ASP > Other ASP.NET > ASP.NET 1.x and 2.0 Application Design
| Search | Today's Posts | Mark Forums Read
ASP.NET 1.x and 2.0 Application Design Application design with ASP.NET 1.0, 1.1, and 2.0.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the ASP.NET 1.x and 2.0 Application Design section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
 
Old September 11th, 2007, 11:23 PM
Authorized User
 
Join Date: Jun 2007
Location: hyderabad, AndhraPradesh, India.
Posts: 24
Thanks: 0
Thanked 0 Times in 0 Posts
Default Problem with random number while uploading images!

Hi friends,
i have written a code with sessions where i can upload an image using random number. When i click the upload button a popup will rise and i will upload the image. Its working fine for the first 3 to 4 times but when i click it 5th time its generating some default images which i have previously uploaded. So kindly check out this problem.Here is the code.Sorry for the long code. Plz help.



IMAGE UPLOAD CODE
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;

public partial class AImageUpload : System.Web.UI.Page
{
    DBSQLClass cld = new DBSQLClass();
    ThumbNail tn = new ThumbNail();
    DataSet ds;
    private Int16 myRowNo = 0;
    string strRandNo;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            Session["Image"] = 0;




            DateTime tmeNow = DateTime.Now;
            int mls = tmeNow.Millisecond;
            Random rndNumber = new Random(mls);
            strRandNo = rndNumber.Next().ToString();
            strRandNo += Session["adminId"].ToString();
            ViewState["strRandNo"] = strRandNo;

            HttpContext.Current.Session["strRandNo"] = ViewState["strRandNo"];
            Bindgridview();
        }
        //Response.Write(strRandNo + "kk" + ViewState["strRandNo"]);
    }
    private void Bindgridview()
    {
        try
        {
            grdImageDetails.Visible = true;
            string str = "select ImageId,ImageName,Image from ImageUpload where RndNo='" + ViewState["strRandNo"] + "'";
            // Response.Write(str);
            ds = new DataSet();
            ds = cld.ReturnDataset(str);
            if (ds.Tables[0].Rows.Count > 0)
            {
                grdImageDetails.DataSource = ds;
                grdImageDetails.DataBind();
            }
        }
        catch (Exception ex)
        {
            lblErrorMsg.Text = ex.Message;
        }

    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            string ImageTitle, ImageFileName, ImageFileNameFullPath;
            //string ImageFileName;
            try
            {
                ImageTitle = txtImageTitle.Text;
                ImageFileName = FileUpload1.FileName;
                //ImageFileName = "//img//" + ImageFileName;
                ImageFileNameFullPath = Server.MapPath(".") + "\\img\\" + ImageFileName;
                //ImageFileName += ImageFileName;
                if (FileUpload1.FileName.Length > 0)
                {
                    FileUpload1.PostedFile.SaveAs(ImageFileNameFullPat h);
                    //FileUpload1.ImageUrl = "Images/" + filename;

                    //Response.Write(strfilename);



                    tn.GenerateThumbNail(Server.MapPath("img"), ImageFileName, ImageFileName, System.Drawing.Imaging.ImageFormat.Gif);
                    //cld.ExecuteStatement("insert into ImageUpload(ImageName,Image,uid) values('" + ImageTitle + "','" + ImageFileName + "'," + Session["adminId"] + ")");


                    cld.ExecuteStatement("insert into ImageUpload(ImageName,Image,rndno) values('" + ImageTitle + "','" + ImageFileName + "','" + ViewState["strRandNo"] + "')");
                    //Response.Write("insert into ImageUpload(ImageName,Image,uid) values('" + ImageTitle + "','" + ImageFileName + "'," + Session["adminId"] + ")");

                    lblErrorMsg.Text = "Image added Successfully.";
                    Bindgridview();
                    txtImageTitle.Text = "";

                }
            }
            catch (Exception ex)
            {
                lblErrorMsg.Text = ex.Message;
            }
        }



    }
    protected void grdImageDetails_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        try
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {

                myRowNo = Convert.ToInt16((grdImageDetails.PageSize * grdImageDetails.PageIndex) + (e.Row.RowIndex));

                e.Row.Cells[2].Text = "<a href='img/" + ds.Tables[0].Rows[myRowNo]["Image"].ToString().Trim() + "' target='_blank'><img border=0 src='img/tn_" + ds.Tables[0].Rows[myRowNo]["Image"].ToString().Trim() + "'></a>";

                ImageButton imgbtn = e.Row.FindControl("imgDel") as ImageButton;
                imgbtn.Attributes.Add("onClick", "javascript:return confirm('do you want to delete this record.');");
                imgbtn.CommandArgument = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "ImageId"));


                Session["Image"] = Session["Image"] + "," + Convert.ToString(DataBinder.Eval(e.Row.DataItem, "ImageId"));
            }
        }
        catch (Exception ex)
        {
            lblErrorMsg.Text = ex.Message;

        }
    }

    protected void grdImageDetails_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        try
        {
            if (e.CommandName == "imgDel")
            {
                deleteRecords(Convert.ToString(e.CommandArgument)) ;
            }
        }
        catch (Exception ex)
        {
            lblErrorMsg.Text = ex.Message;
        }

    }
    private void deleteRecords(string ids)
    {

        try
        {
            string str = "delete from ImageUpload where ImageId in(" + ids + ")";
            Int16 outV = cld.ExecuteStatement(str);
            if (outV >= 1)
            {

                lblErrorMsg.Text = "Record(s) deleted successfully";
                Bindgridview();
            }
            else
            {
                lblErrorMsg.Text = "Deletion Un-successfull.";
            }
        }
        catch (Exception ex)
        {
            cld.ShowMessage(lblErrorMsg, ex.Message);
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {

    }
}

TO UPDATE THE IMAGE

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;

public partial class Admin_NewTask : System.Web.UI.Page
{
     DBSQLClass cld=new DBSQLClass();
    protected void Page_Load(object sender, EventArgs e)
    {
        SCheck SC = new SCheck();

        SC.checkAdminLogin();
        if (!Page.IsPostBack)
        {
            Session["Image"] = "0";

            {
                if (Session["current_editing_row_ID"] != null)
                {
                    btnSubmit.Visible = false;

                    ViewState["id"] = Convert.ToInt16(Session["current_editing_row_ID"]);
                    DataSet ds = new DataSet();
                    string str = "select TaskID,TaskName,TaskDescription,convert(varchar,Pl annedStartDate,103) as PlannedStartDate,convert(varchar,PlannedEndDate,10 3) as PlannedEndDate,PlannedWork,convert(varchar,ActualS tartDate,103) as ActualStartDate,convert(varchar,ActualEndDate,103) as ActualEndDate,ActualWork,Status,ProjectID,Employee ID,TaskType,ModuleID,TaskCreatedDate,LastModifiedD ate,LastModifiedBy,IsAdmin,tPriority,[Date] from Tasks where TaskID=" + Convert.ToInt16(ViewState["id"]);

                    ds = cld.ReturnDataset(str);
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        EmpProjModule1.SetProjSelectedValue = ds.Tables[0].Rows[0]["projectid"].ToString();
                        txtTaskName.Text = ds.Tables[0].Rows[0]["Taskname"].ToString();
                        txtDesc.Text = ds.Tables[0].Rows[0]["Taskdescription"].ToString();

                        txtPlnStDate.Text = ds.Tables[0].Rows[0]["PlannedStartDate"].ToString();
                        txtPlnEdDate.Text = ds.Tables[0].Rows[0]["PlannedEndDate"].ToString();

                        txtPlannedWork.Text = ds.Tables[0].Rows[0]["PlannedWork"].ToString();
                        txtActStDate.Text = ds.Tables[0].Rows[0]["ActualStartDate"].ToString();
                        txtActEdDate.Text = ds.Tables[0].Rows[0]["ActualEndDate"].ToString();
                        txtStatus.Text = ds.Tables[0].Rows[0]["Status"].ToString();
                        txtActualWork.Text = ds.Tables[0].Rows[0]["ActualWork"].ToString();
                        modID.Value = ds.Tables[0].Rows[0]["ModuleID"].ToString();
                        empID.Value = ds.Tables[0].Rows[0]["employeeid"].ToString();
                        ddlTaskPriority.SelectedValue = ds.Tables[0].Rows[0]["tpriority"].ToString();
                        ddlType.SelectedValue = ds.Tables[0].Rows[0]["TaskType"].ToString();

                    }
                    btnUpdate.Visible = true;

                    Session["current_editing_row_ID"] = null;

                }

            }
        }
    }
    public DataSet dsGetSpParam(string sp_Name, int tbl_int, int tbl_Passvalue)
    {
        System.Data.SqlClient.SqlCommand cmd;
        System.Data.SqlClient.SqlDataAdapter da;

        DBConnClass objdbcon = new DBConnClass();
        objdbcon.conString = System.Configuration.ConfigurationManager.Connecti onStrings["conStringSQL"].ToString();
        try
        {
            objdbcon.dbConOpen();
            cmd = new System.Data.SqlClient.SqlCommand(sp_Name, objdbcon.dbCon);
            cmd.CommandType = CommandType.StoredProcedure;
            System.Data.SqlClient.SqlParameter[] myParams = new System.Data.SqlClient.SqlParameter[2];
            myParams[0] = cmd.Parameters.Add("@_MasterTypeInt", System.Data.SqlDbType.Int);
            myParams[0].Value = tbl_int;
            myParams[1] = cmd.Parameters.Add("@_MasterParticularId", System.Data.SqlDbType.Int);
            myParams[1].Value = tbl_Passvalue;

            System.Data.DataSet ds = new System.Data.DataSet();
            da = new System.Data.SqlClient.SqlDataAdapter(cmd);
            da.Fill(ds);
            da.Dispose();
            return ds;
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            objdbcon.dbConClose();
        }
    }
protected void btnSubmit_Click(object sender, EventArgs e)
{
    dealwithclientdetails("flag", 0);
}
    private void dealwithclientdetails(string flag, Int32 id)
    {
        try
        {


            if (EmpProjModule1.ProjValue.ToString() == "0")
            {
                lblErrorMsg.Text = "Please select a project";
                return;
            }
            if (EmpProjModule1.ModuleValue.ToString() == "0")
            {
                lblErrorMsg.Text = "Please select a Module";
                return;
            }
            if (EmpProjModule1.EmpValue.ToString() == "0")
            {
                lblErrorMsg.Text = "Please select a Employee";
                return;
            }


            System.Data.SqlClient.SqlParameter[] sqlparm = new System.Data.SqlClient.SqlParameter[21];
            if (flag == "Update")
            {
                sqlparm[0] = new System.Data.SqlClient.SqlParameter("@flag", "U");
                sqlparm[17] = new System.Data.SqlClient.SqlParameter("@IsAdmin", 1);
                sqlparm[18] = new System.Data.SqlClient.SqlParameter("@LastModifiedB y", Convert.ToInt16(Session["adminId"]));
            }
            else
            {
                sqlparm[0] = new System.Data.SqlClient.SqlParameter("@flag", "I");
                sqlparm[17] = new System.Data.SqlClient.SqlParameter("@IsAdmin", 0);
                sqlparm[18] = new System.Data.SqlClient.SqlParameter("@LastModifiedB y", 0);
            }

            sqlparm[1] = new System.Data.SqlClient.SqlParameter("@TaskName", Convert.ToString(txtTaskName.Text.Trim()));
            sqlparm[2] = new System.Data.SqlClient.SqlParameter("@TaskDescripti on", Convert.ToString(txtDesc.Text.Trim()));
            sqlparm[19] = new System.Data.SqlClient.SqlParameter("@tPriority", Convert.ToInt16(ddlTaskPriority.SelectedValue.ToSt ring().Trim()));
            sqlparm[20] = new System.Data.SqlClient.SqlParameter("@ImageUpload", Session["Image"].ToString());


            String dtD = null;
            string sd = txtPlnStDate.Text.Trim();
            if (sd.Length > 0)
            {
                String[] str = sd.Split('/');
                dtD = str[1].ToString() + "/" + str[0].ToString() + "/" + str[2].ToString();
            }
            else
            {
                dtD = null;
            }
            sqlparm[3] = new System.Data.SqlClient.SqlParameter("@PlannedStartD ate", dtD);

            dtD = null;
            sd = txtPlnEdDate.Text.Trim();
            if (sd.Length > 0)
            {
                String[] str = sd.Split('/');
                dtD = str[1].ToString() + "/" + str[0].ToString() + "/" + str[2].ToString();
            }
            else
            {
                dtD = null;
            }
            sqlparm[4] = new System.Data.SqlClient.SqlParameter("@PlannedEndDat e", dtD);




            dtD = null;
            sd = txtActStDate.Text.Trim();
            if (sd.Length > 0)
            {
                String[] str = sd.Split('/');
                dtD = str[1].ToString() + "/" + str[0].ToString() + "/" + str[2].ToString();
            }
            else
            {
                dtD = null;
            }
            sqlparm[5] = new System.Data.SqlClient.SqlParameter("@ActualStartDa te", dtD);


            dtD = null;
            sd = txtActEdDate.Text.Trim();
            if (sd.Length > 0)
            {
                String[] str = sd.Split('/');
                dtD = str[1].ToString() + "/" + str[0].ToString() + "/" + str[2].ToString();
            }
            else
            {
                dtD = null;
            }
            sqlparm[6] = new System.Data.SqlClient.SqlParameter("@ActualEndDate ", dtD);



            sqlparm[7] = new System.Data.SqlClient.SqlParameter("@ActualWork", Convert.ToString(txtActualWork.Text.Trim()));
            sqlparm = new System.Data.SqlClient.SqlParameter("@PlannedWork", Convert.ToString(txtPlannedWork.Text.Trim()));
            sqlparm[9] = new System.Data.SqlClient.SqlParameter("@Status", Convert.ToString(txtStatus.Text.Trim()));
            sqlparm[10] = new System.Data.SqlClient.SqlParameter("@ProjectID", Convert.ToInt16(EmpProjModule1.ProjValue));

            sqlparm[11] = new System.Data.SqlClient.SqlParameter("@EmployeeID", Convert.ToString(EmpProjModule1.EmpValue));
            sqlparm[12] = new System.Data.SqlClient.SqlParameter("@ModuleID", Convert.ToString(EmpProjModule1.ModuleValue));
            sqlparm[13] = new System.Data.SqlClient.SqlParameter("@TaskType", Convert.ToString(ddlType.SelectedValue.ToString(). Trim()));
            sqlparm[14] = new System.Data.SqlClient.SqlParameter("@Out", SqlDbType.Int);
            sqlparm[14].Direction = ParameterDirection.Output;
            sqlparm[15] = new System.Data.SqlClient.SqlParameter("@ReturnValue", SqlDbType.Int);
            sqlparm[15].Direction = ParameterDirection.Output;
            sqlparm[16] = new System.Data.SqlClient.SqlParameter("@TaskID", Convert.ToInt16(id));



            Int16 outval, retval;
            outval = Convert.ToInt16(cld.ExecuteStatement("Create_Taskn ameProcedure", sqlparm));
            retval = Convert.ToInt16(sqlparm[15].Value);

            if (outval == 0 && retval >= 0)
            {
                cld.ShowMessage(lblErrorMsg, "Task Saved Successfully");


                if (Session["strRandNo"] != null)
                {
                    if (Session["strRandNo"].ToString().Trim().Length > 0)
                    {
                        cld.ExecuteStatement("update ImageUpload set taskid=" + retval + " where rndno='" + Session["strRandNo"].ToString() + "'");
                    }
                }


            }
            else if (outval == 0 && retval == -1)
            {
                cld.ShowMessage(lblErrorMsg, "Task Name already exists.");
                txtTaskName.Text = "";
                txtDesc.Text = "";
                txtActualWork.Text = "";
                txtActStDate.Text = "";
                txtActEdDate.Text = "";
                txtPlannedWork.Text = "";
                txtPlnEdDate.Text = "";
                txtPlnStDate.Text = "";
                txtStatus.Text = "";
                ddlTaskPriority.SelectedValue = "0";
                EmpProjModule1.SetModuleSelectedValue = "0";
                EmpProjModule1.SetProjSelectedValue = "0";
                EmpProjModule1.SetEmpSelectedValue = "0";

            }

            else
            {
                cld.ShowMessage(lblErrorMsg, "Error Occured");

          }
        }
        catch (Exception ex)
        {
            cld.ShowMessage(lblErrorMsg, ex.Message);
        }
    }
protected void btnUpdate_Click(object sender, EventArgs e)
{

}
}
cheers
Ossy!
__________________
Surya!
 
Old September 12th, 2007, 01:43 AM
Friend of Wrox
 
Join Date: Oct 2004
Location: delhi, delhi, India.
Posts: 553
Thanks: 0
Thanked 1 Time in 1 Post
Send a message via MSN to vinod_yadav1919 Send a message via Yahoo to vinod_yadav1919
Default

Hi Ossy!!
Tip-1>u r using random number.
 When i click the upload button a popup will rise and i will upload the image. Its working fine for the first 3 to 4 times but when

 2>i click it 5th time its generating some default images which i have previously uploaded.


** Why it's showing the image that u have already uploaded, just because of the random nummber (this time) is generated the same number which is already generated in the previous upload.:)

So always take care about when you want to play with random number,it can make a infinite loop.

Solution-I have solution ,but think about it how you do made a logic "so that every time new random number is generated",Offcourse u will do this



Cheers :)

vinod
 
Old September 16th, 2007, 11:45 PM
Authorized User
 
Join Date: Jun 2007
Location: hyderabad, AndhraPradesh, India.
Posts: 24
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Hey vinod,
            I tried to generate a unique value for the random number but the problem is not bein solved yet.So plz help me.

Cheers,
Ossy!
 
Old September 30th, 2007, 05:24 AM
Authorized User
 
Join Date: Jul 2007
Location: , , India.
Posts: 27
Thanks: 0
Thanked 0 Times in 0 Posts
Default

I think here is the problem

 int mls = tmeNow.Millisecond;

you are using the variable 'mls' as to get a seed for the random number to be generated. There is, even though low, a possibility of getting same value. Do you really need a seed value? Try getting the random number without passing any parameter. Yes you can also do it that way. See if it can solve ur problem

 
Old September 30th, 2007, 05:33 AM
Imar's Avatar
Wrox Author
Points: 70,322, Level: 100
Points: 70,322, Level: 100 Points: 70,322, Level: 100 Points: 70,322, Level: 100
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Jun 2003
Location: Utrecht, Netherlands.
Posts: 17,089
Thanks: 80
Thanked 1,576 Times in 1,552 Posts
Default

I never understood why you need a random number in the first place. But, if you really do, why not use a GUID?

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

Wouldn't that be a much better solution?

Imar

---------------------------------------
Imar Spaanjaars
http://Imar.Spaanjaars.Com
Everyone is unique, except for me.
Author of ASP.NET 2.0 Instant Results and Beginning Dreamweaver MX / MX 2004




Similar Threads
Thread Thread Starter Forum Replies Last Post
Random Number Generation i_shahid C# 2005 2 March 31st, 2008 10:50 PM
Random Number Creation welshboy2005 C# 2 June 21st, 2005 12:54 PM
random number rajuru Beginning PHP 7 December 7th, 2004 10:52 AM
random number isheikh PHP How-To 1 October 25th, 2004 08:43 PM
Random Number Blaise Access 5 August 23rd, 2003 06:48 AM





Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.