Ejemplo n.º 1
0
    protected void Button4_Click(object sender, EventArgs e)
    {
        string saveDir = @"Uploads\";
        //因為反斜線會被解析,使用@方便閱讀
        //還是可寫成String saveDir= "\\FileUpload\\";
        //string saveDir = "\\FileUpload\\";
        string appPath = Request.PhysicalApplicationPath;//取得目錄完整位址
        string err     = "";

        if (FileUpload1.HasFile)
        {
            string savePath = appPath + saveDir +
                              Server.HtmlEncode(FileUpload1.FileName);
            FileUpload1.SaveAs(savePath);
            FileUpload1.Dispose();
            bool lockexcel = Class1.LockExcelInterop(savePath, 1, "1111", out err);
            if (lockexcel == true && err == "")
            {
                Label1.Text = "lockexcel ok!";
            }
            else
            {
                Label1.Text = "lockexcel fail!";
                return;
            }
            Label1.Text += "Your file was uploaded successfully.";
        }
        else
        {
            Label1.Text = "You did not specify a file to upload.";
        }
    }
Ejemplo n.º 2
0
        protected void Button2_Click(object sender, EventArgs e)
        {
            bool fileOK = false;

            //判断upload是否有文件
            if (FileUpload1.HasFile)
            {
                String   fileExtension     = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();
                String[] allowedExtensions = { ".gif", ".png", ".jpeg", ".jpg" }; //防止垃圾上传
                for (int i = 0; i < allowedExtensions.Length; i++)
                {
                    if (fileExtension == allowedExtensions[i])
                    {
                        fileOK = true;
                    }
                }
            }
            else if (FileUpload1.HasFile == false)
            {//upload有文件但是垃圾文件不是图片
                ScriptManager.RegisterStartupScript(this, this.GetType(), "msg", "<script>alert('请选择要上传的文件! ')</script>", false);
            }
            if (fileOK)
            { //有文件且是图片
                string path        = Server.MapPath("~/images/");
                string postaddpath = DateTime.Now.ToString("yyyyMMddhhmmss");
                FileUpload1.PostedFile.SaveAs(path + postaddpath + ".jpg");
                //FileUpload1.SaveAs(path);
                FileUpload1.Dispose();
                ScriptManager.RegisterStartupScript(this, this.GetType(), "msg", "<script>alert('上传成功! ')</script>", false);
                //allpath = "image/BBspost/" + postaddpath + ".jpg";
                //write();
            }
        }
Ejemplo n.º 3
0
    protected void EntryMode(bool IsUpdate)
    {
        if (IsUpdate == true)
        {
            btnSave.Text      = "Update";
            hfIsUpadate.Value = "Y";
            txtEmpID.ReadOnly = false;
        }
        else
        {
            btnSave.Text      = "Save";
            hfIsUpadate.Value = "N";
            txtEmpID.ReadOnly = false;
            imgEmp.ImageUrl   = ConfigurationManager.AppSettings["EmpImagePath"].Trim() + "/NoImage.jpg";
            hfEmpImage.Value  = "";
            ImgSign.ImageUrl  = ConfigurationManager.AppSettings["EmpSignPath"].Trim() + "/NoImage.jpg";

            FileUpload1.Dispose();
            FileUpload2.Dispose();
            imgByte                = null;
            imgSignByte            = null;
            Session["imgByte"]     = "";
            Session["imgSignByte"] = "";
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)                                                                                                                                                            //Upload file here
        {
            string fileExt = System.IO.Path.GetExtension(FileUpload1.FileName);                                                                                                             //Get extension
            if (fileExt == ".csv")                                                                                                                                                          //check to see if its a .csv file
            {
                FileUpload1.SaveAs("C:\\FolderName\\" + FileUpload1.FileName);                                                                                                              //save file to the specified folder
                OleDbConnection oconn = new     OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\AudioPRFiles\\; Extended     Properties='text; HDR=Yes; FMT=Delimited'"); //string connection for .CSV     OR Text file
                try
                {
                    OleDbCommand ocmd = new OleDbCommand("SELECT * FROM [" + FileUpload1.FileName + "]", oconn);            //Select statement, if your using .CSV...put the name of the file NOT the excel tab

                    oconn.Open();
                    OleDbDataReader odr      = ocmd.ExecuteReader();
                    string          Device   = "";
                    string          Source   = "";
                    string          Reviewer = "";
                    string          Datetime = "";
                    string          Links    = "";
                    string          Content  = "";
                    string          Subject  = "";
                    while (odr.Read())
                    {
                        Device   = valid(odr, 0);   //Call the valid method...see below
                        Source   = valid(odr, 1);
                        Reviewer = valid(odr, 2);
                        Datetime = valid(odr, 3);
                        Links    = valid(odr, 4);
                        Content  = valid(odr, 5);
                        Subject  = valid(odr, 6);
                        InsertDataIntoSql(Device, Source, Reviewer, Datetime, Links, Content, Subject); //Call the InsertDataIntoSql method...see below
                        FileUpload1.Dispose();                                                          //Dispose the file
                    }
                    oconn.Close();                                                                      //Close connection
                }
                catch (Exception ee)
                {
                    Label1.Text      = ee.Message;
                    Label1.ForeColor = System.Drawing.Color.Red;
                }
                finally
                {
                    Label1.Text      = "Data Inserted Successfully";
                    Label1.ForeColor = System.Drawing.Color.Green;
                }
            }
            else
            {
                Label1.Text = "Only .csv files allowed!";
            }
        }
        else
        {
            Label1.Text = "You have not specified a file!";
        }
    }
Ejemplo n.º 5
0
 protected void btnReset_Click(object sender, EventArgs e)
 {
     txtsubject.Text           = "";
     txtTextArea.Value         = "";
     ddlPriority.SelectedIndex = 0;
     ddlCategory.SelectedValue = "1";
     //CheckBox1.Checked = false;
     FileUpload1.Dispose();
 }
Ejemplo n.º 6
0
 protected void btnClear_Click(object sender, EventArgs e)
 {
     name.Text    = "";
     surname.Text = "";
     about.Text   = "";
     phone.Text   = "";
     email.Text   = "";
     FileUpload1.Dispose();
 }
Ejemplo n.º 7
0
        protected void btnScan_Click(object sender, EventArgs e)
        {
            listBox1.Items.Clear();

            if (FileUpload1.HasFile)
            {
                try
                {
                    StatusLabel.Text = "";
                    int    cnt_virus = 0;
                    string message   = "Virus not found!";
                    foreach (HttpPostedFile uploadedFile in FileUpload1.PostedFiles)
                    {
                        string filename   = Path.GetFileName(uploadedFile.FileName);
                        string path       = Server.MapPath("~/" + uploadedFile.FileName);
                        string saveaspath = System.IO.Path.Combine(Server.MapPath("~/"), uploadedFile.FileName);
                        uploadedFile.SaveAs(saveaspath);
                        StreamReader  stream = new StreamReader(path);
                        string        read   = stream.ReadToEnd();
                        List <string> virus  = new List <string>();
                        virus = getData();

                        foreach (string vrs in virus)
                        {
                            if (Regex.IsMatch(read, vrs))
                            {
                                cnt_virus += 1;
                                listBox1.Items.Add(filename + " (" + vrs + ")");
                                message = string.Format("{0} Virus detected!", cnt_virus);
                            }
                        }
                        stream.DiscardBufferedData();
                        stream.Dispose();
                        if (File.Exists(path))
                        {
                            System.IO.File.Delete(path);
                        }
                    }
                    StatusLabel.Text = message;
                }
                catch (Exception ex)
                {
                    lbl_Error.Visible = true;
                    lbl_Error.Text    = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
                }
                finally
                {
                    FileUpload1.Dispose();
                }
            }
            else
            {
                lbl_Error.Visible = true;
                lbl_Error.Text    = "Please upload the file!";
            }
        }
Ejemplo n.º 8
0
 protected void clearControls()
 {
     ddlSupplierList.ClearSelection();
     ddlSupplierList.SelectedIndex = 0;
     ddlEntityList.ClearSelection();
     ddlEntityList.SelectedIndex = 0;
     FileUpload1.Dispose();
     gvFileUploadSearchForNew.DataSource = null;
     gvFileUploadSearchForNew.DataBind();
 }
        void Clear()
        {
            _dittnamn.Value
                    = _Gatunamn.Value
                    = _Stad.Value
                    = Phonenr.Value = null;

            _Postnummer.Value = null;
            FileUpload1.Dispose();
        }
Ejemplo n.º 10
0
    private void Cancel()
    {
        GridView1.SelectedIndex = -1;
        TextTitle.Text          = "";
        TextBox1.Text           = "";
        FileUpload1.Dispose();

        TextTitle.Focus();
        LblHidden.ToolTip = "";
        Button1.Text      = "ثبت";
    }
Ejemplo n.º 11
0
 public void ClearPage()
 {
     txtDesc.Text              = "";
     txtName.Text              = "";
     txtPrice.Text             = "";
     txtSellingPrice.Text      = "";
     ddlBrands.SelectedIndex   = 0;
     ddlCategory.SelectedIndex = 0;
     ddlColor.SelectedIndex    = 0;
     FileUpload1.Dispose();
 }
Ejemplo n.º 12
0
        void Clear()
        {
            _skolnamn.Value
                      = _dittnamn.Value
                      = _Gatunamn.Value
                      = _Stad.Value
                      = _Email.Value = "";

            _Postnummer.Value = null;
            FileUpload1.Dispose();
        }
Ejemplo n.º 13
0
        private string UpLoadFile(string pName)
        {
            string _fileName = "";
            string _name     = "";

            try
            {
                if (FileUpload1.HasFile)
                {
                    _fileName = (Server.MapPath("/Upload/"));
                    if (pName == "")
                    {
                        _name = DateTime.Now.ToString("yyyyMMddHHmmss") + FileUpload1.FileName.Substring(FileUpload1.FileName.LastIndexOf('.'));
                    }
                    else
                    {
                        _name = pName;
                    }
                    _fileName += _name;
                    FileUpload1.SaveAs(_fileName);
                    FileUpload1.Dispose();

                    // _fileName =imghandle.MakeThumbPic(_fileName, _fileName, 150, 150, "Cut");

                    new ImageThumbnail(_fileName).ReducedImage(0.9, _fileName);

                    //ServiceReference1.ImgServiceSoapClient uf = new ServiceReference1.ImgServiceSoapClient();
                    //FileInfo imgFile = new FileInfo(@_fileName);
                    //byte[] imgByte = new byte[imgFile.Length];//1.初始化用于存放图片的字节数组
                    //System.IO.FileStream imgStream = imgFile.OpenRead();//2.初始化读取图片内容的文件流
                    //imgStream.Read(imgByte, 0, Convert.ToInt32(imgFile.Length));//3.将图片内容通过文件流读取到字节数组
                    //string str = uf.UploadFileImg(imgByte, _name);//4.发送到服务器

                    return(_name);
                    //if (str.Equals("上传成功"))
                    //{
                    //    return _name;
                    //}
                    //else
                    //{

                    //    return "1";
                    //}
                }
                return(_name);
            }
            catch (Exception ex)
            {
                return("0");
            }
        }
Ejemplo n.º 14
0
    protected void cleaneow()
    {
        mainqtb.Text = "";
        FileUpload1.Dispose();
        ImageforUpload1.ImageUrl = "/Images/ImagePlaceholder.png";

        for (int l = 1; l <= 7; l++)
        {
            string d  = Convert.ToString(l);
            string dd = Convert.ToString(l + 1);
            ((TextBox)FindControl("ATextBox" + d)).Text      = "";
            ((TextBox)FindControl("ATextBox" + d)).Enabled   = true;
            ((CheckBox)FindControl("ACheckBox" + d)).Checked = false;
            ((FileUpload)FindControl("FileUpload" + dd)).Dispose();
            ((ImageButton)FindControl("ImageforUpload" + dd)).ImageUrl = "/Images/ImagePlaceholder.png";
            ((ImageButton)FindControl("ImageforUpload" + dd)).Style.Add("opacity", "1");
        }
    }
Ejemplo n.º 15
0
 protected void btn_reset_Click(object sender, EventArgs e)
 {
     TextBox1.Text        = "";
     txt_Money.Text       = "";
     txt_Description.Text = "";
     txt_Comment.Text     = "";
     FileUpload1.Dispose();
     vat_fileupload.Dispose();
     Image1.ImageUrl  = "";
     txt_Amount.Text  = "";
     Img_Vat.ImageUrl = "";
     Vatmyframe.Src   = "";
     Img_Vat.Attributes.Add("width", "0px");
     Img_Vat.Attributes.Add("height", "0px");
     Vatmyframe.Attributes.Add("style", "height:0px;width:0px;");
     Image1.Attributes.Add("width", "0px");
     Image1.Attributes.Add("height", "0px");
 }
Ejemplo n.º 16
0
        protected void btnChange_Click(object sender, EventArgs e)
        {
            try
            {
                _showPage_info = string.Empty;

                string root      = Server.MapPath("/temp/");
                string excelPath = root + "test.xlsx";
                if (FileUpload1.HasFile)
                {
                    //上传word文件, 由于只是做示例,在这里不多做文件类型、大小、格式以及是否存在的判断
                    FileUpload1.SaveAs(excelPath);
                    FileUpload1.Dispose();

                    //从Excel中读取客户和联系人
                    List <DataTable> dtList = ExcelHelper.readExcel(excelPath);
                    if (dtList.Count > 0)
                    {
                        //数据转译
                        List <Dictionary <string, object> > dic_data = DataTableToList(dtList[0]);
                        //当前负责人名称
                        string userName = this.TextBox1.Text.Trim();

                        //开始进行更改
                        begin_cust_linkman(dic_data, userName);
                    }
                }
                else
                {
                    //请选择文件
                    Label1.Text = "请选择文件";
                }
            }
            catch (Exception ex)
            {
                Label1.Text = "出现异常,请联系管理员";
                LogHelper.Error(ex);
            }
            finally
            {
                //TextBox2.Text = _showPage_info;
            }
        }
Ejemplo n.º 17
0
        protected void FileUpload1_Click(object sender, ImageClickEventArgs e)
        {
            if (FileUpload1.HasFile)
            {
                if (FileUpload1.PostedFile.FileName != null)
                {
                    g.fileName = FileUpload1.PostedFile.FileName;
                    string[] matchextension = { ".JPG", ".JPEG", ".PNG", ".pdf", ".docx", ".doc" };

                    string fileExtension = System.IO.Path.GetExtension(g.fileName);

                    if ((matchextension.Contains(fileExtension)))
                    {
                        int fileLengthInKB = FileUpload1.PostedFile.ContentLength / 2048;

                        if (fileLengthInKB <= 2048)
                        {
                            FileUpload1.SaveAs(Server.MapPath(@"~/" + g.fileName));

                            //g.path = Server.MapPath(@"c:/badari/reqapp/images/" + g.fileName);

                            Response.Write("<script>alert(' File Saved Successfully');</script>");
                            FileUpload1.Dispose();
                        }
                        else
                        {
                            ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "myscript", "alert(' Please select file attachment less than 2MB')", true);
                        }
                    }
                    else
                    {
                        ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "myscript", "alert('Please select file attachment of type .Pdf .Jpg .Jpeg .png .doc .docx')", true);
                    }
                }
                else
                {
                    ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "myscript", "alert('Please select file attachment')", true);
                }
            }
        }
Ejemplo n.º 18
0
        protected void Button3_Click(object sender, EventArgs e)
        {
            string pSavePath = Server.MapPath("~/XLS/");

            if (!FileUpload1.HasFile)
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "msg", "<script>alert('请选择要上传的文件! ')</script>", false);
                return;
            }
            string pFileName = FileUpload1.FileName;

            pSavePath += pFileName;
            FileUpload1.SaveAs(pSavePath);
            FileUpload1.Dispose();
            int i = pFileName.Length - 4;

            if (pFileName.Substring(i) == ".zip")
            {
                CompresssFiles.UnZip(pSavePath, Server.MapPath("~/XLS/"));
            }
            ScriptManager.RegisterStartupScript(this, this.GetType(), "msg", "<script>alert('上传成功! 文件名为:" + FileUpload1.FileName + "  文件类型为:" + FileUpload1.PostedFile.ContentType + "  文件大小为:" + FileUpload1.PostedFile.ContentLength + "')</script>", false);
        }
Ejemplo n.º 19
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        string newfilename = "blablabla.jpg";

        //check if file is inside fileupload

        //check file size



        //check file type

        //save file to server



        FileUpload1.SaveAs(imagedir + newfilename);

        //save newfilename to db


        //dispose
        FileUpload1.Dispose();
    }
Ejemplo n.º 20
0
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Button3_Click(object sender, EventArgs e)
        {
            string pSavePath = Server.MapPath("~/XLS/");

            if (!FileUpload1.HasFile)
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "msg", "<script>alert('请选择要上传的文件! ')</script>", false);
                return;
            }
            string pFileName = FileUpload1.FileName;

            Session["mingcheng"] = pFileName.ToString();
            pSavePath           += pFileName;
            FileUpload1.SaveAs(pSavePath);
            FileUpload1.Dispose();
            int i = pFileName.Length - 4;

            if (pFileName.Substring(i) == ".zip")
            {
                CompresssFiles.UnZip(pSavePath, Server.MapPath("~/XLS/"));
            }
            //Session.Clear();

            string a = Session["mingcheng"].ToString();

            ScriptManager.RegisterStartupScript(this, this.GetType(), "msg", "<script>alert('上传成功! 文件名为:" + FileUpload1.FileName + "  文件类型为:" + FileUpload1.PostedFile.ContentType + "  文件大小为:" + FileUpload1.PostedFile.ContentLength + "')</script>", false);


            //    string name = GetFiles.FileName;//获取已上传文件的名字
            //string size = GetFiles.PostedFile.ContentLength.ToString();//获取已上传文件的大小
            //string type = GetFiles.PostedFile.ContentType;//获取已上传文件的MIME
            //string postfix = name.Substring(name.LastIndexOf(".") + 1);//获取已上传文件的后缀
            //string ipath = Server.MapPath("upimg") +"\\"+ name;//获取文件的实际路径
            //string fpath = Server.MapPath("upfile") + "\\" + name;
            //string dpath = "upimg\\" + name;//判断写入数据库的虚拟路径

            //ShowPic.Visible = true;//激活
            //ShowText.Visible = true;//激活

            ////判断文件格式
            //if (name == "") {
            //  Response.Write("<script>alert('上传文件不能为空')</script>");
            //}

            //else{

            //    if (postfix == "jpg" || postfix == "gif" || postfix == "bmp" || postfix == "png")
            //    {
            //        GetFiles.SaveAs(ipath);
            //        ShowPic.ImageUrl = dpath;
            //        ShowText.Text = "你上传的图片名称是:" + name + "<br>" + "文件大小:" + size + "KB" + "<br>" + "文件类型:" + type + "<br>" + "存放的实际路径为:" + ipath;

            //    }

            //    else
            //    {
            //        ShowPic.Visible = false;//隐藏图片
            //        GetFiles.SaveAs(fpath);//由于不是图片文件,因此转存在upfile这个文件夹
            //        ShowText.Text = "你上传的文件名称是:" + name + "<br>" + "文件大小:" + size + "KB" + "<br>" + "文件类型:" + type + "<br>" + "存放的实际路径为:" + fpath;

            //    }
        }
Ejemplo n.º 21
0
    public void fileupload1()
    {
        SqlConnection conn = new SqlConnection(constr);

        try
        {
            if (FileUpload1.HasFile)
            {
                FileUpload1.Dispose();

                string fileName = FileUpload1.ResolveClientUrl(FileUpload1.PostedFile.FileName);

                DataTable datatble = new DataTable();
                DataSet   ds       = new DataSet();

                //string SourceConstr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + fileName + "';Extended Properties= 'Excel 8.0;HDR=Yes;IMEX=1'";
                //OleDbConnection con = new OleDbConnection(SourceConstr);
                ////con.Open();
                //string query = "Select Process from [Process$]";

                string file       = FileUpload1.PostedFile.FileName;
                string serverpath = Server.MapPath("~/uploads/" + file);
                if (File.Exists(serverpath))
                {
                    File.Delete(serverpath);
                }
                FileUpload1.SaveAs(Server.MapPath("~/uploads/" + file));
                string filePath = Server.MapPath("~/uploads/" + file);

                bool   hasHeaders = false;
                string HDR        = hasHeaders ? "Yes" : "No";
                // string HDR = "Yes";
                string strConn;
                if (filePath.Substring(filePath.LastIndexOf('.')).ToLower() == ".xlsx")
                {
                    strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0;HDR=" + HDR + ";IMEX=0\"";
                }
                else
                {
                    strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=\"Excel 8.0;HDR=" + HDR + ";IMEX=0\"";
                }
                OleDbConnection con = new OleDbConnection(strConn);
                con.Open();
                DataTable schemaTable = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
                DataRow   schemaRow   = schemaTable.Rows[0];
                string    sheet       = schemaRow["TABLE_NAME"].ToString();
                if (!sheet.EndsWith("_"))
                {
                    string           query = "SELECT Process FROM [" + sheet + "]";
                    OleDbDataAdapter data  = new OleDbDataAdapter(query, con);
                    data.Fill(datatble);
                    DataTable filteredRows = datatble.Rows.Cast <DataRow>()
                                             .Where(row => !row.ItemArray.All(field => field is System.DBNull))
                                             .CopyToDataTable();
                    ds.Tables.Add(filteredRows);
                }
                SqlDataAdapter daa1 = new SqlDataAdapter("Select * from tbl_Process ", conn);
                DataSet        dss  = new DataSet();
                daa1.Fill(dss);

                if (dss.Tables[0].Rows.Count > 0)
                {
                    dss.Locale = System.Globalization.CultureInfo.InvariantCulture;
                    SqlCommand     cmd1 = new SqlCommand("Truncate table tbl_Process", conn);
                    SqlDataAdapter daa3 = new SqlDataAdapter(cmd1);
                    conn.Open();
                    cmd1.ExecuteNonQuery();
                    conn.Close();
                }
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    string Process = Convert.ToString(ds.Tables[0].Rows[i]["Process"].ToString());


                    ds.Locale = System.Globalization.CultureInfo.InvariantCulture;
                    SqlCommand     cmd = new SqlCommand("insert into tbl_Process(Process)values ('" + Process + "')", conn);
                    SqlDataAdapter daa = new SqlDataAdapter(cmd);
                    conn.Open();
                    cmd.ExecuteNonQuery();
                    conn.Close();
                }
                //objBL_Mac.Mode = "ExcelUpload1";

                //grdMac.DataSource = ds.Tables[0];
                //grdMac.DataBind();

                //DataSet SQlResult = objDL_Mac.BulkInsert1(objBL_Mac);

                //data.Dispose();
                //con.Close();
                //con.Dispose();

                objtbl_Process            = new Processtble_grid();
                objtbl_Process.FileUpload = "Process";
                objtbl_Process.UserName   = HttpContext.Current.Session["User_Name"].ToString();
                objtbl_Process.Time       = HttpContext.Current.Session["Logtime"].ToString();
                objtbl_Process.Date       = HttpContext.Current.Session["LogDate"].ToString();

                objQualitySheetdclassDataContext.Processtble_grids.InsertOnSubmit(objtbl_Process);
                objQualitySheetdclassDataContext.SubmitChanges();
                objQualitySheetdclassDataContext = null;
                con.Close();
                ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Process File Uploaded Successfully !');", true);
                Loadprocess();
            }
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Invalid file !');", true);
            Exception ex2          = ex;
            string    errorMessage = string.Empty;
            while (ex2 != null)
            {
                errorMessage += ex2.ToString();
                ex2           = ex2.InnerException;
            }
            HttpContext.Current.Response.Write(errorMessage);
        }
        finally
        {
            //conn.Close();
            FileUpload1.Dispose();
        }
    }
Ejemplo n.º 22
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (FileUpload1.PostedFile == null || String.IsNullOrEmpty(FileUpload1.PostedFile.FileName) || FileUpload1.PostedFile.InputStream == null)
        {
            Response.Write("<br />Error - unable to upload file. Please try again.<br />");
        }
        else
        {
            string filename = Path.GetFileName(FileUpload1.FileName);

            HttpPostedFile file        = FileUpload1.PostedFile;
            byte[]         buffer      = new byte[file.ContentLength];
            int            bytesReaded = file.InputStream.Read(buffer, 0, FileUpload1.PostedFile.ContentLength);

            SqlCommand cmd = new SqlCommand("insert into AddImage(Imgid,ImgName,ImgClr,ImgBhr,ImgBry,Image,count ) values('" + Label5.Text + "','" + TextBox1.Text + "','" + DropDownList1.SelectedItem.Text + "','" + TextBox2.Text + "',@file,@name,@c**t)", con);
            cmd.Parameters.AddWithValue("@file", buffer);
            cmd.Parameters.AddWithValue("@name", filename);
            cmd.Parameters.AddWithValue("@c**t", "0");


            con.Open();
            try
            {
                cmd.ExecuteNonQuery();
                con.Close();

                string pathToCreate1 = "~/Images/";
                if (Directory.Exists(Server.MapPath(pathToCreate1)))
                {
                    FileUpload1.SaveAs(Server.MapPath("~/Images/" + filename));
                    string     fname = Server.MapPath("~/Images/" + filename);
                    SqlCommand cmd1  = new SqlCommand("update AddImage set ImgPath='" + fname + "'where Imgid='" + Label5.Text + "'", con);
                    con.Open();
                    cmd1.ExecuteNonQuery();
                    con.Close();
                }
                else
                {
                    Directory.CreateDirectory(Server.MapPath(pathToCreate1));
                    FileUpload1.SaveAs(Server.MapPath("~/Images/" + filename));
                    string     fname = Server.MapPath("~/Images/" + filename);
                    SqlCommand cmd2  = new SqlCommand("update AddImage set ImgPath='" + fname + "'where Imgid='" + Label5.Text + "'", con);
                    con.Open();
                    cmd2.ExecuteNonQuery();
                    con.Close();
                }
                string pathToCreate = "~/" + TextBox2.Text + "/";
                if (Directory.Exists(Server.MapPath(pathToCreate)))
                {
                    FileUpload1.SaveAs(Server.MapPath("~/" + TextBox2.Text + "/" + filename));
                }
                else
                {
                    Directory.CreateDirectory(Server.MapPath(pathToCreate));
                    FileUpload1.SaveAs(Server.MapPath("~/" + TextBox2.Text + "/" + filename));
                }

                cmd.Dispose();


                FileUpload1.Dispose();
                Label7.Text = "Status: Uploaded Successfully";
            }
            catch (SqlException ex)
            {
                Label7.Text = "error" + ex.Message.ToString();
            }
        }
    }
Ejemplo n.º 23
0
        protected void btnCreate_Click(object sender, EventArgs e)
        {
            Page.Validate();
            if (Page.IsValid)
            {
                //upload pics
                if (FileUpload1.HasFile)
                {
                    string fileName    = FileUpload1.FileName;
                    Bitmap originalBMP = new Bitmap(FileUpload1.FileContent);

                    // Calculate the new image dimensions
                    decimal origWidth      = originalBMP.Width;
                    decimal origHeight     = originalBMP.Height;
                    decimal sngRatio       = origWidth / origHeight;
                    int     newWidth       = 200;
                    decimal newHeight_temp = newWidth / sngRatio;
                    int     newHeight      = Convert.ToInt32(newHeight_temp);

                    Bitmap   newBMP    = new Bitmap(originalBMP, newWidth, newHeight);
                    Graphics oGraphics = Graphics.FromImage(newBMP);

                    oGraphics.SmoothingMode     = SmoothingMode.AntiAlias;
                    oGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight);

                    newBMP.Save(Server.MapPath("~/ProfilePic/") + txtGuestId.Text + "_Profile.png");

                    originalBMP.Dispose();
                    newBMP.Dispose();
                    oGraphics.Dispose();

                    FileUpload1.FileContent.Dispose();
                    FileUpload1.Dispose();
                }

                if (FileUpload2.HasFile)
                {
                    string fileName    = FileUpload2.FileName;
                    Bitmap originalBMP = new Bitmap(FileUpload2.FileContent);

                    // Calculate the new image dimensions
                    decimal origWidth      = originalBMP.Width;
                    decimal origHeight     = originalBMP.Height;
                    decimal sngRatio       = origWidth / origHeight;
                    int     newWidth       = 200;
                    decimal newHeight_temp = newWidth / sngRatio;
                    int     newHeight      = Convert.ToInt32(newHeight_temp);

                    Bitmap   newBMP    = new Bitmap(originalBMP, newWidth, newHeight);
                    Graphics oGraphics = Graphics.FromImage(newBMP);

                    oGraphics.SmoothingMode     = SmoothingMode.AntiAlias;
                    oGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight);

                    newBMP.Save(Server.MapPath("~/IDPic/") + txtGuestId.Text + "_IDPic.png");

                    originalBMP.Dispose();
                    newBMP.Dispose();
                    oGraphics.Dispose();

                    FileUpload2.FileContent.Dispose();
                    FileUpload2.Dispose();
                }

                Guest g = new Guest();
                g.GuestId                 = txtGuestId.Text;
                g.FirstName               = txtFirstName.Text;
                g.MiddleName              = txtMiddleName.Text;
                g.LastName                = txtLastName.Text;
                g.CompanyId               = Convert.ToInt32(ddlCompanyName.SelectedValue);
                g.ContactNumber           = txtContactNo.Text;
                g.Email                   = txtEmail.Text;
                g.ValidIDNumber           = txtIdNumber.Text;
                g.PicFilePath             = txtGuestId.Text + "_Profile.png";
                g.IDFilePath              = txtGuestId.Text + "_IDPic.png";
                g.EmergencyContactPerson  = txtContactPerson.Text;
                g.EmergencyContactNumber  = txtContactPersonNumber.Text;
                g.EmergencyContactAddress = txtContactPersonAddress.Text;
                g.CreateDate              = DateTime.Now;
                g.CreatedBy               = User.Identity.Name;
                g.IsCompany               = false;

                db.Guests.InsertOnSubmit(g);
                db.SubmitChanges();

                //audit trail
                DBLogger.Log("Create", "Created Individual Guest", g.GuestId);

                Response.Redirect("~/guest/default.aspx");
                //pnlSuccess.Visible = true;
                //clearButtons();
            }
        }
Ejemplo n.º 24
0
        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            Page.Validate();
            if (Page.IsValid)
            {
                //upload pics
                if (FileUpload1.HasFile)
                {
                    string fileName    = FileUpload1.FileName;
                    Bitmap originalBMP = new Bitmap(FileUpload1.FileContent);

                    // Calculate the new image dimensions
                    decimal origWidth      = originalBMP.Width;
                    decimal origHeight     = originalBMP.Height;
                    decimal sngRatio       = origWidth / origHeight;
                    int     newWidth       = 200;
                    decimal newHeight_temp = newWidth / sngRatio;
                    int     newHeight      = Convert.ToInt32(newHeight_temp);

                    Bitmap   newBMP    = new Bitmap(originalBMP, newWidth, newHeight);
                    Graphics oGraphics = Graphics.FromImage(newBMP);

                    oGraphics.SmoothingMode     = SmoothingMode.AntiAlias;
                    oGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight);

                    newBMP.Save(Server.MapPath("~/ProfilePic/") + txtGuestId.Text + "_Profile.png");

                    originalBMP.Dispose();
                    newBMP.Dispose();
                    oGraphics.Dispose();

                    FileUpload1.FileContent.Dispose();
                    FileUpload1.Dispose();
                }

                if (FileUpload2.HasFile)
                {
                    string fileName    = FileUpload2.FileName;
                    Bitmap originalBMP = new Bitmap(FileUpload2.FileContent);

                    // Calculate the new image dimensions
                    decimal origWidth      = originalBMP.Width;
                    decimal origHeight     = originalBMP.Height;
                    decimal sngRatio       = origWidth / origHeight;
                    int     newWidth       = 200;
                    decimal newHeight_temp = newWidth / sngRatio;
                    int     newHeight      = Convert.ToInt32(newHeight_temp);

                    Bitmap   newBMP    = new Bitmap(originalBMP, newWidth, newHeight);
                    Graphics oGraphics = Graphics.FromImage(newBMP);

                    oGraphics.SmoothingMode     = SmoothingMode.AntiAlias;
                    oGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight);

                    newBMP.Save(Server.MapPath("~/IDPic/") + txtGuestId.Text + "_IDPic.png");

                    originalBMP.Dispose();
                    newBMP.Dispose();
                    oGraphics.Dispose();

                    FileUpload2.FileContent.Dispose();
                    FileUpload2.Dispose();
                }

                var g = (from gu in db.Guests
                         where gu.Id.Equals(Request.QueryString["guestid"])
                         select gu).FirstOrDefault();

                g.GuestId                 = txtGuestId.Text;
                g.FirstName               = txtFirstName.Text;
                g.MiddleName              = txtMiddleName.Text;
                g.LastName                = txtLastName.Text;
                g.CompanyId               = Convert.ToInt32(ddlCompanyName.SelectedValue);
                g.ContactNumber           = txtContactNo.Text;
                g.Email                   = txtEmail.Text;
                g.ValidIDNumber           = txtIdNumber.Text;
                g.PicFilePath             = txtGuestId.Text + "_Profile.png";
                g.IDFilePath              = txtGuestId.Text + "_IDPic.png";
                g.EmergencyContactPerson  = txtContactPerson.Text;
                g.EmergencyContactNumber  = txtContactPersonNumber.Text;
                g.EmergencyContactAddress = txtContactPersonAddress.Text;
                g.CreatedBy               = User.Identity.Name;

                db.SubmitChanges();

                //audit trail
                DBLogger.Log("Update", "Updated Individual Guest", g.GuestId);

                pnlSuccess.Visible = true;

                //load images
                if (!File.Exists(Server.MapPath("~/ProfilePic/") + g.GuestId + "_Profile.png"))
                {
                    imgProfile.ImageUrl = "~/ProfilePic/noImage.png";
                }
                else
                {
                    imgProfile.ImageUrl = "~/ProfilePic/" + g.GuestId + "_Profile.png?t=" + DateTime.Now.ToString();
                }

                if (!File.Exists(Server.MapPath("~/IDPic/") + g.GuestId + "_IDPic.png"))
                {
                    IDPic.ImageUrl = "~/IDPic/noImage.png";
                }
                else
                {
                    IDPic.ImageUrl = "~/IDPic/" + g.GuestId + "_IDPic.png?t=" + DateTime.Now.ToString();
                }
            }
        }
Ejemplo n.º 25
0
 protected void Button1_Click(object sender, EventArgs e)
 {
     FileUpload1.Dispose();
 }
        protected void ibtn_Upload_Click(object sender, ImageClickEventArgs e)
        {
            OracleConnection Oracleconn = new OracleConnection(WebConfigurationManager.ConnectionStrings["ORAWF"].ConnectionString);

            Oracleconn.Open();

            //janaka

            using (OracleBulkCopy bulkcopy = new OracleBulkCopy(Oracleconn))
            {
                if (FileUpload1.HasFile)
                {
                    String Date = DateTime.Now.ToShortDateString().Replace("/", "-");

                    string directoryPath = Server.MapPath("~/IBTManual_UploadFiles/" + Date + "/");
                    if (!Directory.Exists(directoryPath))
                    {
                        Directory.CreateDirectory(directoryPath);
                    }
                    string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
                    string savePath = Server.MapPath("~/IBTManual_UploadFiles/" + Date + "/") + fileName;


                    //Check Duplicate file
                    if (File.Exists(savePath))
                    {
                        call_error_msg(false);
                        lblResult.Text = "Duplicate file found, Please check the attached file.....!";
                        return;
                    }


                    FileUpload1.PostedFile.SaveAs(savePath);
                    DataTable EmployeeData = exceldataLife(savePath);



                    //---------------------------------------------
                    List <string> List = new List <string>();
                    foreach (DataRow row in EmployeeData.Rows)
                    {
                        string Serial = row["SERIAL"].ToString();
                        if (List.Contains(Serial))
                        {
                            call_error_msg(false);
                            lblResult.Text = "Please Check Serial Number Column.....!";
                            return;
                        }
                        List.Add(Serial);
                    }
                    //---------------------------------------------



                    //string filelocation = Convert.ToString(FileUpload1.PostedFile.FileName);
                    ////Save to path
                    //string filename = FileUpload1.FileName;
                    //string savePath = System.IO.Path.Combine(@"\\192.168.10.13\LifeClaims_WF\", filename);
                    //FileUpload1.PostedFile.SaveAs(savePath);
                    ////End Save to path

                    //DataTable EmployeeData = exceldataLife(savePath);

                    bulkcopy.ColumnMappings.Add(new OracleBulkCopyColumnMapping("SERIAL", "SERIAL"));
                    bulkcopy.ColumnMappings.Add(new OracleBulkCopyColumnMapping("TRANSACTION_CODE", "TRANSACTION_CODE"));
                    bulkcopy.ColumnMappings.Add(new OracleBulkCopyColumnMapping("VOUCHER_DATE", "VOUCHER_DATE"));
                    bulkcopy.ColumnMappings.Add(new OracleBulkCopyColumnMapping("PAYMENT_MODE", "PAYMENT_MODE"));
                    bulkcopy.ColumnMappings.Add(new OracleBulkCopyColumnMapping("NARRATION", "NARRATION"));
                    bulkcopy.ColumnMappings.Add(new OracleBulkCopyColumnMapping("POLICY_NUMBER", "POLICY_NUMBER"));
                    bulkcopy.ColumnMappings.Add(new OracleBulkCopyColumnMapping("AMOUNT", "AMOUNT"));
                    bulkcopy.ColumnMappings.Add(new OracleBulkCopyColumnMapping("POLICY_FEE", "POLICY_FEE"));
                    bulkcopy.ColumnMappings.Add(new OracleBulkCopyColumnMapping("CASH_ACCOUNT", "CASH_ACCOUNT"));
                    bulkcopy.ColumnMappings.Add(new OracleBulkCopyColumnMapping("POLICY_BRANCH", "POLICY_BRANCH"));
                    bulkcopy.ColumnMappings.Add(new OracleBulkCopyColumnMapping("PAYING_PARTY", "PAYING_PARTY"));
                    bulkcopy.ColumnMappings.Add(new OracleBulkCopyColumnMapping("INSTRUMENT_NUMBER", "INSTRUMENT_NUMBER"));
                    bulkcopy.ColumnMappings.Add(new OracleBulkCopyColumnMapping("INSTRUMENT_DATE", "INSTRUMENT_DATE"));
                    bulkcopy.ColumnMappings.Add(new OracleBulkCopyColumnMapping("STATUS", "STATUS"));
                    bulkcopy.ColumnMappings.Add(new OracleBulkCopyColumnMapping("CREATEDBY", "CREATEDBY"));
                    bulkcopy.ColumnMappings.Add(new OracleBulkCopyColumnMapping("CREATED_DATE", "CREATED_DATE"));
                    bulkcopy.ColumnMappings.Add(new OracleBulkCopyColumnMapping("BATCH_NO", "BATCH_NO"));
                    bulkcopy.ColumnMappings.Add(new OracleBulkCopyColumnMapping("BATCH_STATUS", "BATCH_STATUS"));
                    bulkcopy.ColumnMappings.Add(new OracleBulkCopyColumnMapping("BATCH_TYPE", "BATCH_TYPE"));

                    bulkcopy.DestinationTableName = "fas_ibt_temp_receipt_nt";

                    try
                    {
                        bulkcopy.WriteToServer(EmployeeData);
                        Oracleconn.Close();
                        Oracleconn.Dispose();
                        FileUpload1.Dispose();
                        //LblError.Visible = true;
                        //LblError.Text = "Upload Successful...";

                        call_error_msg(true);
                        lblResult.Text = "Upload Successful........!";
                    }
                    catch (Exception ex)
                    {
                        call_error_msg(false);
                        lblResult.Text = "Upload Fail........!";
                    }
                }
            }
        }
Ejemplo n.º 27
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                string institutename  = txtinstitutename.Text;
                string category       = Txtcategory.Text;
                string educationgroup = txteducationgroup.Text;
                string description    = txtinstdescp.Text;
                string address        = txtaddress.Text;
                string state          = ddlstate.SelectedItem.ToString();
                string city           = ddlcity.SelectedItem.ToString();
                string area           = txtarea.Text;
                string town           = txttown.Text;
                string country        = txtcountry.Text;
                long   zipcode        = long.Parse(txtzipcode.Text.ToString());
                string affiliatedto   = ddlaffiliatedto.SelectedItem.ToString();
                string board          = ddlboard.SelectedItem.ToString();
                string classfrom      = ddlclassfrom.SelectedItem.ToString();
                string medium         = ddlmedium.SelectedItem.ToString();
                string classto        = ddlclassto.SelectedItem.ToString();
                string schooltype     = ddlschooltype.SelectedItem.ToString();
                string classification = ddlclassification.SelectedItem.ToString();
                string admissionproc  = txtadmprocedure.Text;
                string docrequired    = txtdocsreq.Text;
                int    agecriteria    = int.Parse(txtagecriteria.Text.ToString());

                DateTime admstartdate = DateTime.Parse(txtadmstartdate.Text.ToString());
                //string admstdate = admstartdate.ToString("YYYY-MM-DD");

                DateTime admenddate = DateTime.Parse(txtadmenddate.Text.ToString());
                //string admedate = admenddate.ToString("YYYY-MM-DD");

                string contactname = txtyourname.Text;
                string email       = txtemail.Text;
                string phone       = txtphone.Text;
                string website     = txtwebsite.Text;
                string designation = txtdesignation.Text;
                string facebook    = txtfacebook.Text;
                string twitter     = txttwitter.Text;
                string linkedin    = txtlinkedin.Text;
                string skype       = txtskype.Text;
                string gmaps       = txtgmapslink.Text;
                con.Open();
                SqlCommand cmd0 = new SqlCommand(@"INSERT INTO Schoolmaster(Schoolname,Category,Educationgroup,Ins_description,Address,State,City,Area,Town,Country,Zipcode,Googlemaps,Affiliatedto,Board,Medium,Class_from,Class_to,School_type,Classification,Adm_procedure,Docs_required,Age_criteria,Admstartdate,Admenddate,Contact_name,Contact_email,Contact_Phone,Designation,Website,Facebook,Twitter,Linkedin,Skype,Listingpriority,Package) values('" + institutename + "','" + category + "','" + educationgroup + "','" + description + "','" + address + "','" + state + "','" + city + "','" + area + "','" + town + "','" + country + "','" + zipcode + "','" + gmaps + "','" + affiliatedto + "','" + board + "','" + medium + "','" + classfrom + "','" + classto + "','" + schooltype + "','" + classification + "','" + admissionproc + "','" + docrequired + "','" + agecriteria + "','" + admstartdate + "','" + admenddate + "','" + contactname + "','" + email + "','" + phone + "','" + designation + "','" + website + "','" + facebook + "','" + twitter + "','" + linkedin + "','" + skype + "','low','Free');", con);
                cmd0.ExecuteNonQuery();



                SqlCommand cmd1 = new SqlCommand("Select MAX(SchoolId) from Schoolmaster;", con);
                cmd1.ExecuteNonQuery();


                SqlDataReader dr0 = cmd1.ExecuteReader();
                while (dr0.Read())   // This is how record is read. Loop through the each record
                {
                    var schoolid = long.Parse(dr0[0].ToString());
                    lblclassid.Text = schoolid.ToString();
                }
                dr0.Close();


                int Class_id = int.Parse(lblclassid.Text.ToString());



                /////Loading CoachingFacilities

                for (int i = 0; i < cblfacilities.Items.Count; i++)
                {
                    if (cblfacilities.Items[i].Selected == true)
                    {
                        SqlCommand cmd2 = new SqlCommand("insert into Schoolfacilities values ('" + Class_id + "','" + cblfacilities.Items[i].ToString() + "')", con);
                        cmd2.ExecuteNonQuery();
                    }
                }

                ///////////Condition for checking values in fileupload box and then loading the table////////////
                if (FileUpload1.HasFile && FileUpload2.HasFile && FileUpload3.HasFile)
                {
                    FileInfo fi1    = new FileInfo(FileUpload1.FileName);
                    string   name1  = fi1.Name;
                    byte[]   image1 = FileUpload1.FileBytes;

                    FileInfo fi2    = new FileInfo(FileUpload2.FileName);
                    string   name2  = fi2.Name;
                    byte[]   image2 = FileUpload2.FileBytes;

                    FileInfo fi3    = new FileInfo(FileUpload3.FileName);
                    string   name3  = fi3.Name;
                    byte[]   image3 = FileUpload3.FileBytes;

                    SqlCommand com = new SqlCommand("Insert into Schoolimages (SchoolId,Schoollogo, School_Image1,School_Image2) values (@SchoolId,@Schoollogo, @School_Image1,@School_Image2)", con);
                    com.Parameters.AddWithValue("@SchoolId", SqlDbType.VarChar).Value        = lblclassid.Text;
                    com.Parameters.AddWithValue("@Schoollogo", SqlDbType.VarBinary).Value    = image1;
                    com.Parameters.AddWithValue("@School_Image1", SqlDbType.VarBinary).Value = image2;
                    com.Parameters.AddWithValue("@School_Image2", SqlDbType.VarBinary).Value = image3;
                    com.ExecuteNonQuery();
                }

                else if (FileUpload1.HasFile && !FileUpload2.HasFile && !FileUpload3.HasFile)
                {
                    FileInfo fi1    = new FileInfo(FileUpload1.FileName);
                    string   name1  = fi1.Name;
                    byte[]   image1 = FileUpload1.FileBytes;

                    //FileInfo fi2 = new FileInfo(FileUpload2.FileName);
                    //string name2 = fi2.Name;
                    //byte[] image2 = FileUpload2.FileBytes;

                    //FileInfo fi3 = new FileInfo(FileUpload3.FileName);
                    //string name3 = fi3.Name;
                    //byte[] image3 = FileUpload3.FileBytes;

                    SqlCommand com = new SqlCommand("Insert into Schoolimages (SchoolId,Schoollogo ) values (@SchoolId,@Schoollogo)", con);
                    com.Parameters.AddWithValue("@SchoolId", SqlDbType.VarChar).Value     = lblclassid.Text;
                    com.Parameters.AddWithValue("@Schoollogo", SqlDbType.VarBinary).Value = image1;
                    //com.Parameters.AddWithValue("@School_Image1", SqlDbType.VarBinary).Value = image2;
                    //com.Parameters.AddWithValue("@School_Image2", SqlDbType.VarBinary).Value = image3;
                    com.ExecuteNonQuery();
                }
                else if (!FileUpload1.HasFile && FileUpload2.HasFile && !FileUpload3.HasFile)
                {
                    FileInfo fi2    = new FileInfo(FileUpload2.FileName);
                    string   name2  = fi2.Name;
                    byte[]   image2 = FileUpload2.FileBytes;



                    SqlCommand com = new SqlCommand("Insert into Schoolimages (SchoolId, School_Image1) values (@SchoolId, @School_Image1)", con);
                    com.Parameters.AddWithValue("@SchoolId", SqlDbType.VarChar).Value = lblclassid.Text;

                    com.Parameters.AddWithValue("@School_Image1", SqlDbType.VarBinary).Value = image2;

                    com.ExecuteNonQuery();
                }
                else if (!FileUpload1.HasFile && !FileUpload2.HasFile && FileUpload3.HasFile)
                {
                    FileInfo fi3    = new FileInfo(FileUpload3.FileName);
                    string   name3  = fi3.Name;
                    byte[]   image3 = FileUpload3.FileBytes;

                    SqlCommand com = new SqlCommand("Insert into Schoolimages (SchoolId,School_Image2) values (@SchoolId,@School_Image2)", con);
                    com.Parameters.AddWithValue("@SchoolId", SqlDbType.VarChar).Value = lblclassid.Text;

                    com.Parameters.AddWithValue("@School_Image2", SqlDbType.VarBinary).Value = image3;
                    com.ExecuteNonQuery();
                }
                else if (FileUpload1.HasFile && !FileUpload2.HasFile && !FileUpload3.HasFile)
                {
                    FileInfo fi1    = new FileInfo(FileUpload1.FileName);
                    string   name1  = fi1.Name;
                    byte[]   image1 = FileUpload1.FileBytes;


                    SqlCommand com = new SqlCommand("Insert into Schoolimages (SchoolId,Schoollogo) values (@SchoolId,@Schoollogo)", con);
                    com.Parameters.AddWithValue("@SchoolId", SqlDbType.VarChar).Value     = lblclassid.Text;
                    com.Parameters.AddWithValue("@Schoollogo", SqlDbType.VarBinary).Value = image1;
                    com.ExecuteNonQuery();
                }


                con.Close();


                string display = "School Details Added Successfully!";
                ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + display + "');", true);


                txtinstitutename.Text           = "";
                Txtcategory.Text                = "";
                txteducationgroup.Text          = "";
                txtinstdescp.Text               = "";
                txtaddress.Text                 = "";
                ddlstate.SelectedIndex          = 0;
                ddlcity.SelectedIndex           = 0;
                txtarea.Text                    = "";
                txttown.Text                    = "";
                txtcountry.Text                 = "";
                txtzipcode.Text                 = "";
                ddlaffiliatedto.SelectedIndex   = 0;
                ddlboard.SelectedIndex          = 0;
                ddlclassfrom.SelectedIndex      = 0;
                ddlclassto.SelectedIndex        = 0;
                ddlschooltype.SelectedIndex     = 0;
                ddlclassification.SelectedIndex = 0;
                txtadmprocedure.Text            = "";
                txtdocsreq.Text                 = "";
                txtagecriteria.Text             = "";
                txtadmstartdate.Text            = "";
                txtadmenddate.Text              = "";

                txtyourname.Text    = "";
                txtemail.Text       = "";
                txtphone.Text       = "";
                txtwebsite.Text     = "";
                txtdesignation.Text = "";
                txtfacebook.Text    = "";
                txttwitter.Text     = "";
                txtlinkedin.Text    = "";
                txtskype.Text       = "";
                FileUpload1.Dispose();
                FileUpload2.Dispose();
                FileUpload3.Dispose();
            }
            catch (Exception ex)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + ex.Message + "');", true);
            }
        }
Ejemplo n.º 28
0
        protected void btnAddSI_Click(object sender, EventArgs e)
        {
            // declare variables
            string time        = rblTime.SelectedValue;
            string days        = rblDay.SelectedValue;
            string course      = drpCourse.SelectedValue;
            string image       = FileUpload1.ToString();
            string username    = txtUserName.Text;
            string password    = txtPassword.Text;
            string name        = txtName.Text;
            string surname     = txtSurname.Text;
            int    phonenumber = Int32.Parse(txtPhoneNum.Text);
            string email       = txtEmail.Text;
            string SI          = "SI";
            string message     = "Successfully added";
            string error       = "Username already exists";


            try
            {
                //open connection
                con.Open();

                //verify if entered username does not match any existing one
                SqlCommand command = new SqlCommand("select Username from SI where Username like @username", con);
                command.Parameters.AddWithValue("@username", "%" + username + "%");
                SqlDataReader dr = command.ExecuteReader();

                if (dr.HasRows)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + error + "');", true);
                    txtUserName.Text      = " ";
                    rblTime.SelectedIndex = -1;
                    rblDay.SelectedIndex  = -1;
                    txtEmail.Text         = " ";
                    txtName.Text          = " ";
                    txtPassword.Text      = " ";
                    txtPhoneNum.Text      = " ";
                    txtSurname.Text       = " ";
                    FileUpload1.Dispose();
                }

                else
                {
                    con.Close();
                    //get image filepath
                    string filepath = FileUpload1.PostedFile.FileName;
                    string filename = Path.GetFileName(filepath);
                    string ext      = Path.GetExtension(filename);

                    string contentType = String.Empty;

                    //read file extension to make sure its a picture
                    switch (ext)
                    {
                    case ".jpg":
                        contentType = "image/jpg";
                        break;

                    case ".png":
                        contentType = "image/png";
                        break;

                    case ".exif":
                        contentType = "image/exif";
                        break;

                    case ".tiff":
                        contentType = "image/tiff";
                        break;

                    case ".gif":
                        contentType = "image/gif";
                        break;

                    case ".bmp":
                        contentType = "image/bmp";
                        break;

                    case ".heif":
                        contentType = "image/heif";
                        break;

                    case ".bat":
                        contentType = "image/bat";
                        break;

                    default:
                        break;
                    }

                    //checks if the image was uploaded before saving information into the database
                    if (contentType != String.Empty)
                    {
                        Stream       fs    = FileUpload1.PostedFile.InputStream;
                        BinaryReader br    = new BinaryReader(fs);
                        Byte[]       bytes = br.ReadBytes((Int32)fs.Length);

                        //insert querry with parameters
                        string query = "INSERT into SI(Times,Days,CourseCode,Image,Username,Password,Name,Surname,PhoneNumber,Email)" + "VALUES(@Times,@Days,@CourseCode,@Image,@Username,@Password,@Name,@Surname,@PhoneNumber,@Email)";


                        //create command
                        using (SqlCommand cmd = new SqlCommand(query, con))
                        {
                            //add parameters into the database
                            cmd.Parameters.Add("@Times", SqlDbType.VarChar, 50).Value      = time;
                            cmd.Parameters.Add("@Days", SqlDbType.VarChar, 50).Value       = days;
                            cmd.Parameters.Add("@CourseCode", SqlDbType.VarChar, 50).Value = course;
                            cmd.Parameters.Add("@Image", SqlDbType.VarBinary, 8000).Value  = bytes;
                            cmd.Parameters.Add("@Username", SqlDbType.VarChar, 50).Value   = username;
                            cmd.Parameters.Add("@Password", SqlDbType.VarChar, 50).Value   = password;
                            cmd.Parameters.Add("@Name", SqlDbType.VarChar, 50).Value       = name;
                            cmd.Parameters.Add("@Surname", SqlDbType.VarChar, 50).Value    = surname;
                            cmd.Parameters.Add("@PhoneNumber", SqlDbType.Int).Value        = phonenumber;
                            cmd.Parameters.Add("@Email", SqlDbType.VarChar, 50).Value      = email;

                            con.Open();
                            cmd.ExecuteNonQuery();
                            con.Close();
                        }

                        Roles.AddUserToRole(username, SI);
                        ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + message + "');", true);
                        Response.Redirect("~/Default.aspx");
                    }
                    else
                    {
                        Response.Write("Error occured");
                    }
                }
            }


            catch
            {
                Response.Write("Error. Please try again");
            }
        }