protected void Button1_Click(object sender, EventArgs e) { //check validate if (string.IsNullOrEmpty(FileUpload1.FileName)) { lbNoti.Text = "Please upload image!"; return; } if (txtName.Text.Trim() == "" || txtDescription.Text == "" || dpCategory.SelectedIndex == 0) { lbNoti.Text = "Please input full information!"; return; } try{ Double.Parse(txtPrice.Text); } catch { lbNoti.Text = "Price must be a float number!"; return; } //do if (sqlUtil.connect(lbNoti)) { //get id nexrow var sqlcom = sqlUtil.sqlcom; String sql = "select dbo.f_NextID()"; //funtion created in database SqlDataReader reader = sqlUtil.execReader(sql, null); //alway have result reader.Read(); int x = reader.GetInt32(0); reader.Close(); lbNoti.Text = x.ToString(); //save img to directory string path = "img/" + x.ToString() + FileUpload1.FileName; FileUpload1.SaveAs(Request.PhysicalApplicationPath + "/" + path); //save to db sqlUtil.disconnect(); sqlUtil.connect(lbNoti); String sqlInsert = "Insert into products values(@name,@price,@description,@img,@cate_id)"; List <SqlParameter> parameters = new List <SqlParameter>(); parameters.Add(new SqlParameter("name", System.Data.SqlDbType.NVarChar)); parameters.Add(new SqlParameter("price", System.Data.SqlDbType.Money)); parameters.Add(new SqlParameter("description", System.Data.SqlDbType.NVarChar)); parameters.Add(new SqlParameter("img", System.Data.SqlDbType.NVarChar)); parameters.Add(new SqlParameter("cate_id", System.Data.SqlDbType.VarChar)); parameters[0].Value = txtName.Text; parameters[1].Value = txtPrice.Text; parameters[2].Value = txtDescription.Text; parameters[3].Value = path; parameters[4].Value = dpCategory.SelectedValue; try { if (sqlUtil.execInsUpdDel(sqlInsert, parameters) == 1) { lbNoti.Text = "Insert successfully!"; } } catch (Exception ex) { lbNoti.Text = ex.ToString(); } } sqlUtil.disconnect(); }
protected void Button1_Click(object sender, EventArgs e) { SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=E:\PlacementMGT\placement_management.mdf;Integrated Security=True;Connect Timeout=300"); con.Open(); string checkuser = "******" + txtemail.Text + "' AND sig_mobile = '" + txtmob.Text + "' AND sig_id_no = '" + txtid.Text + "' "; //SqlCommand cmd1 = new SqlCommand(checkuser, con); //int temp = Convert.ToInt32(cmd1.ExecuteScalar()); SqlDataAdapter sda1 = new SqlDataAdapter(checkuser, con); DataTable dt1 = new DataTable(); sda1.Fill(dt1); int temp = dt1.Rows.Count; if (temp > 0) { Response.Write("<script>alert('Data already exist');</script>"); con.Close(); } else { try { string insertQuery = "insert into signup (sig_name,sig_id_no,sig_email,sig_mobile,br_id,sig_sem,imagename,imagepath) values (@sig_name,@sig_id_no,@sig_email,@sig_mobile,@br_id,@sig_sem,@imagename, @imagepath)"; SqlCommand cmd = new SqlCommand(insertQuery, con); string filename = Path.GetFileName(FileUpload1.FileName); if (filename != null) { try { FileUpload1.SaveAs(Server.MapPath("~/profile/" + filename)); } catch (Exception e2) { } } else { filename = ""; } cmd.Parameters.AddWithValue("@sig_name", txtname.Text); cmd.Parameters.AddWithValue("@sig_id_no", txtid.Text); cmd.Parameters.AddWithValue("@sig_email", txtemail.Text); cmd.Parameters.AddWithValue("@sig_mobile", txtmob.Text); cmd.Parameters.AddWithValue("@br_id", ddlbranch.Text); cmd.Parameters.AddWithValue("@sig_sem", ddlsem.SelectedValue); cmd.Parameters.AddWithValue("@imagename", filename); cmd.Parameters.AddWithValue("@imagepath", "profile/" + filename); cmd.ExecuteNonQuery(); Response.Write("<script>alert('Data Successfully Added');</script>"); con.Close(); } catch (Exception ex) { Response.Write("error:" + ex.ToString()); } } }
protected void Button1_Click(object sender, EventArgs e) { if (FileUpload1.HasFile) { String photo = Path.GetFileName(FileUpload1.FileName); FileUpload1.SaveAs(Server.MapPath("~/Teacher/pic/" + photo)); string conn = ConfigurationManager.ConnectionStrings["totalschoolConnectionString"].ConnectionString; SqlConnection objcon = new SqlConnection(conn); objcon.Open(); SqlCommand objcmd = new SqlCommand("spgal", objcon); objcmd.CommandType = CommandType.StoredProcedure; SqlParameter p2 = new SqlParameter(); p2.ParameterName = "@pic"; p2.SqlDbType = SqlDbType.NVarChar; p2.Value = FileUpload1.FileName; objcmd.Parameters.Add(p2); SqlParameter p3 = new SqlParameter(); p3.ParameterName = "@id"; p3.SqlDbType = SqlDbType.NVarChar; p3.Value = lblid.Text; objcmd.Parameters.Add(p3); SqlParameter p1 = new SqlParameter(); p1.ParameterName = "@school"; p1.SqlDbType = SqlDbType.NVarChar; p1.Value = lblsch.Text; objcmd.Parameters.Add(p1); //Class1.WebMsgBox.Show("1 Added successfully"); objcmd.ExecuteNonQuery(); // Response.Write("Created Successfully"); objcon.Close(); } if (FileUpload2.HasFile) { String photo1 = Path.GetFileName(FileUpload2.FileName); FileUpload2.SaveAs(Server.MapPath("~/Teacher/pic/" + photo1)); string conn1 = ConfigurationManager.ConnectionStrings["totalschoolConnectionString"].ConnectionString; SqlConnection objcon1 = new SqlConnection(conn1); objcon1.Open(); SqlCommand objcmd1 = new SqlCommand("spgal", objcon1); objcmd1.CommandType = CommandType.StoredProcedure; SqlParameter p21 = new SqlParameter(); p21.ParameterName = "@pic"; p21.SqlDbType = SqlDbType.NVarChar; p21.Value = FileUpload2.FileName; objcmd1.Parameters.Add(p21); SqlParameter p31 = new SqlParameter(); p31.ParameterName = "@id"; p31.SqlDbType = SqlDbType.NVarChar; p31.Value = lblid.Text; objcmd1.Parameters.Add(p31); SqlParameter p1 = new SqlParameter(); p1.ParameterName = "@school"; p1.SqlDbType = SqlDbType.NVarChar; p1.Value = lblsch.Text; objcmd1.Parameters.Add(p1); //Class1.WebMsgBox.Show("2 Added successfully"); objcmd1.ExecuteNonQuery(); // Response.Write("Created Successfully"); objcon1.Close(); } if (FileUpload3.HasFile) { String photo2 = Path.GetFileName(FileUpload3.FileName); FileUpload3.SaveAs(Server.MapPath("~/Teacher/pic/" + photo2)); string conn2 = ConfigurationManager.ConnectionStrings["totalschoolConnectionString"].ConnectionString; SqlConnection objcon2 = new SqlConnection(conn2); objcon2.Open(); SqlCommand objcmd2 = new SqlCommand("spgal", objcon2); objcmd2.CommandType = CommandType.StoredProcedure; SqlParameter p22 = new SqlParameter(); p22.ParameterName = "@pic"; p22.SqlDbType = SqlDbType.NVarChar; p22.Value = FileUpload3.FileName; objcmd2.Parameters.Add(p22); SqlParameter p32 = new SqlParameter(); p32.ParameterName = "@id"; p32.SqlDbType = SqlDbType.NVarChar; p32.Value = lblid.Text; objcmd2.Parameters.Add(p32); SqlParameter p1 = new SqlParameter(); p1.ParameterName = "@school"; p1.SqlDbType = SqlDbType.NVarChar; p1.Value = lblsch.Text; objcmd2.Parameters.Add(p1); //Class1.WebMsgBox.Show("3 Added successfully"); objcmd2.ExecuteNonQuery(); // Response.Write("Created Successfully"); objcon2.Close(); } if (FileUpload4.HasFile) { String photo3 = Path.GetFileName(FileUpload4.FileName); FileUpload4.SaveAs(Server.MapPath("~/Teacher/pic/" + photo3)); string conn3 = ConfigurationManager.ConnectionStrings["totalschoolConnectionString"].ConnectionString; SqlConnection objcon3 = new SqlConnection(conn3); objcon3.Open(); SqlCommand objcmd3 = new SqlCommand("spgal", objcon3); objcmd3.CommandType = CommandType.StoredProcedure; SqlParameter p23 = new SqlParameter(); p23.ParameterName = "@pic"; p23.SqlDbType = SqlDbType.NVarChar; p23.Value = FileUpload4.FileName; objcmd3.Parameters.Add(p23); SqlParameter p33 = new SqlParameter(); p33.ParameterName = "@id"; p33.SqlDbType = SqlDbType.NVarChar; p33.Value = lblid.Text; objcmd3.Parameters.Add(p33); SqlParameter p1 = new SqlParameter(); p1.ParameterName = "@school"; p1.SqlDbType = SqlDbType.NVarChar; p1.Value = lblsch.Text; objcmd3.Parameters.Add(p1); // Class1.WebMsgBox.Show("4 Added successfully"); objcmd3.ExecuteNonQuery(); // Response.Write("Created Successfully"); objcon3.Close(); } if (FileUpload5.HasFile) { String photo4 = Path.GetFileName(FileUpload5.FileName); FileUpload5.SaveAs(Server.MapPath("~/Teacher/pic/" + photo4)); string conn4 = ConfigurationManager.ConnectionStrings["totalschoolConnectionString"].ConnectionString; SqlConnection objcon4 = new SqlConnection(conn4); objcon4.Open(); SqlCommand objcmd4 = new SqlCommand("spgal", objcon4); objcmd4.CommandType = CommandType.StoredProcedure; SqlParameter p24 = new SqlParameter(); p24.ParameterName = "@pic"; p24.SqlDbType = SqlDbType.NVarChar; p24.Value = FileUpload5.FileName; objcmd4.Parameters.Add(p24); SqlParameter p34 = new SqlParameter(); p34.ParameterName = "@id"; p34.SqlDbType = SqlDbType.NVarChar; p34.Value = lblid.Text; objcmd4.Parameters.Add(p34); SqlParameter p1 = new SqlParameter(); p1.ParameterName = "@school"; p1.SqlDbType = SqlDbType.NVarChar; p1.Value = lblsch.Text; objcmd4.Parameters.Add(p1); //Class1.WebMsgBox.Show("5 Added successfully"); objcmd4.ExecuteNonQuery(); // Response.Write("Created Successfully"); objcon4.Close(); } Class1.WebMsgBox.Show("Pics Added to Gallery Successfully"); }
protected void Button1_Click(object sender, EventArgs e) { string connString = ""; FileUpload1.SaveAs(Server.MapPath("~/Upload/" + FileUpload1.FileName)); //for uploading files string strFileType = Path.GetExtension(FileUpload1.FileName).ToLower(); //getting path string path1 = FileUpload1.PostedFile.FileName; string path = System.IO.Path.GetFullPath(Server.MapPath("~/Upload/" + FileUpload1.FileName)); //for storing files in .net folder if (strFileType.Trim() == ".xls") { connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("~/Upload/" + FileUpload1.FileName) + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";//for xls } else if (strFileType.Trim() == ".xlsx") { connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Server.MapPath("~/Upload/" + FileUpload1.FileName) + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\""; //for xlsx } string query = "select * FROM [IF1G$]"; //for fetching data from excel sheet(sheet1) OleDbConnection conn = new OleDbConnection(connString); ArrayList list1 = new ArrayList();//to get the values in array list from excel list list1.Clear(); ArrayList list2 = new ArrayList(); list2.Clear(); ArrayList list3 = new ArrayList(); list3.Clear(); ArrayList list4 = new ArrayList(); list4.Clear(); ArrayList list5 = new ArrayList(); list5.Clear(); ArrayList list6 = new ArrayList(); list6.Clear(); ArrayList list7 = new ArrayList(); list7.Clear(); ArrayList list8 = new ArrayList(); list8.Clear(); ArrayList list9 = new ArrayList(); list9.Clear(); ArrayList list10 = new ArrayList(); list10.Clear(); ArrayList list11 = new ArrayList(); list11.Clear(); ArrayList list12 = new ArrayList(); list12.Clear(); ArrayList list13 = new ArrayList(); list13.Clear(); ArrayList list14 = new ArrayList(); list14.Clear(); ArrayList list15 = new ArrayList(); list15.Clear(); ArrayList list16 = new ArrayList(); list16.Clear(); ArrayList list17 = new ArrayList(); list17.Clear(); ArrayList list18 = new ArrayList(); list18.Clear(); ArrayList list19 = new ArrayList(); list19.Clear(); //string count=""; conn.Open(); OleDbCommand cmd = new OleDbCommand();//oledbconnection for reading data from excela OleDbDataReader rs1; cmd.Connection = conn; cmd.CommandText = "select * FROM [IF1G$]"; rs1 = cmd.ExecuteReader(); while (rs1.Read()) { if (rs1.GetValue(0).ToString() != "") //if not blank then enter { list1.Add(rs1.GetValue(0).ToString()); // for fetching data from excel list2.Add(rs1.GetValue(1).ToString()); list3.Add(rs1.GetValue(2).ToString()); list4.Add(rs1.GetValue(3).ToString()); list5.Add(rs1.GetValue(4).ToString()); list6.Add(rs1.GetValue(5).ToString()); list7.Add(rs1.GetValue(6).ToString()); list8.Add(rs1.GetValue(7).ToString()); list9.Add(rs1.GetValue(8).ToString()); list10.Add(rs1.GetValue(9).ToString()); list11.Add(rs1.GetValue(10).ToString()); list12.Add(rs1.GetValue(11).ToString()); list13.Add(rs1.GetValue(12).ToString()); list14.Add(rs1.GetValue(13).ToString()); list15.Add(rs1.GetValue(14).ToString()); list16.Add(rs1.GetValue(15).ToString()); list17.Add(rs1.GetValue(16).ToString()); list18.Add(rs1.GetValue(17).ToString()); list19.Add(rs1.GetValue(18).ToString()); } } rs1.Close(); cmd.Dispose(); conn.Close(); conn.Dispose(); int i = 0; for (i = 0; i < list1.Count; i++)//for entering into the excel sheet { int count1 = 0; cn.Open();// connection for inserting data in database cmd1.Connection = cn; cmd1.CommandText = "select count(*) from Semester1 where Enroll_No='" + list1[i].ToString() + "'"; rs = cmd1.ExecuteReader(); while (rs.Read()) { count1 = int.Parse(rs.GetValue(0).ToString()); } rs.Close(); cmd1.Dispose(); cn.Close(); string qry = ""; if (count1 == 0) { Auto_Gen();//for inserting values into database qry = "insert into Semester1 (ID,Enroll_No,Surname,Firstname,Middlename,Seatnumber,Eng_TH,Eng_TW ,Bsi_TH,Bsi_PR,Bms_TH,Egg_PR,Egg_TW ,Cmf_PR,Cmf_TW,Wcc_TW ,Sw ,Total,Percentage,Remarks)values('" + auto + "','" + list1[i].ToString() + "','" + list2[i].ToString() + "','" + list3[i].ToString() + "','" + list4[i].ToString() + "','" + list5[i].ToString() + "','" + list6[i].ToString() + "','" + list7[i].ToString() + "','" + list8[i].ToString() + "','" + list9[i].ToString() + "','" + list10[i].ToString() + "','" + list11[i].ToString() + "','" + list12[i].ToString() + "','" + list13[i].ToString() + "','" + list14[i].ToString() + "','" + list15[i].ToString() + "','" + list16[i].ToString() + "','" + list17[i].ToString() + "','" + list18[i].ToString() + "','" + list19[i].ToString() + "')"; } else {//for updating database qry = "update Semester1 set Surname='" + list2[i].ToString() + "',Firstname='" + list3[i].ToString() + "',Middlename='" + list4[i].ToString() + "',Seatnumber='" + list5[i].ToString() + "',Eng_TH='" + list6[i].ToString() + "',Eng_TW='" + list7[i].ToString() + "',Bsi_TH='" + list8[i].ToString() + "',Bsi_PR='" + list9[i].ToString() + "',Bms_TH='" + list10[i].ToString() + "',Egg_PR='" + list11[i].ToString() + "',Egg_TW='" + list12[i].ToString() + "',Cmf_PR='" + list13[i].ToString() + "',Cmf_TW='" + list14[i].ToString() + "',Wcc_TW='" + list15[i].ToString() + "',Sw ='" + list16[i].ToString() + "',Total='" + list17[i].ToString() + "',Percentage='" + list18[i].ToString() + "',Remarks='" + list19[i].ToString() + "' where Enroll_No='" + list1[i].ToString() + "' "; } cn.Open(); cmd1.Connection = cn; cmd1.CommandText = qry; cmd1.ExecuteNonQuery(); cmd1.Dispose(); cn.Close(); Label1.Text = "Successfully Uploaded"; } }
protected void Button1_Click(object sender, EventArgs e) { try { if (FileUpload1.PostedFile != null && FileUpload1.HasFile) { if (emp_id == null && upd_id == null) { ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Please Select Employee First ')", true); } else { if (emp_id != null && upd_id == null) { string imgFile2 = Path.GetFileName(FileUpload1.PostedFile.FileName); FileUpload1.SaveAs(Server.MapPath("Images/" + imgFile2)); string con1 = System.Configuration.ConfigurationManager.ConnectionStrings["DBMS"].ConnectionString; SqlConnection conn = new SqlConnection(con1); SqlCommand cmd1 = new SqlCommand("update Employee set Img = @img where emp_id = @id", conn); cmd1.Parameters.AddWithValue("@img", "Images/" + imgFile2.ToString()); cmd1.Parameters.AddWithValue("@id", emp_id); conn.Open(); cmd1.ExecuteNonQuery(); conn.Close(); conn.Dispose(); emp_id = null; ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Save Employee Data')", true); } else if (upd_id != null && emp_id == null) { string imgFile2 = Path.GetFileName(FileUpload1.PostedFile.FileName); FileUpload1.SaveAs(Server.MapPath("Images/" + imgFile2)); string con1 = System.Configuration.ConfigurationManager.ConnectionStrings["DBMS"].ConnectionString; SqlConnection conn = new SqlConnection(con1); SqlCommand cmd1 = new SqlCommand("update Employee set Img = @img where emp_id = @id", conn); cmd1.Parameters.AddWithValue("@img", "Images/" + imgFile2.ToString()); cmd1.Parameters.AddWithValue("@id", upd_id); conn.Open(); cmd1.ExecuteNonQuery(); conn.Close(); conn.Dispose(); upd_id = null; ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Save Employee Data')", true); } } } else { ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Please Select Image First ')", true); } } catch (SqlException ex) { ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Error : '+'" + ex.Message + "')", true); } }
protected void Button1_Click(object sender, EventArgs e) { if (teacherId != 0) { teacher = DataRepository.TeacherProvider.GetByTeacherId(teacherId); } else { teacher = DataRepository.TeacherProvider.GetByAspnetMembershipUserId(new Guid(Membership.GetUser().ProviderUserKey.ToString()))[0]; } // teacher = DataRepository.TeacherProvider.GetByAspnetMembershipUserId(new Guid(Membership.GetUser().ProviderUserKey.ToString()))[0]; bool boolCommit = false; bool ImageUploaded = false; if (FileUpload1.HasFile) { if (FileUpload1.FileName.ToLower().EndsWith(".jpg") || FileUpload1.FileName.ToLower().EndsWith(".png")) { try { FileUpload1.SaveAs(Server.MapPath("~/TeacherPics/" + FileUpload1.FileName)); teacher.PicturePath = "/TeacherPics/" + FileUpload1.FileName; boolCommit = true; ImageUploaded = true; } catch (Exception ex) { boolCommit = false; ImageUploaded = false; } } else { boolCommit = false; ImageUploaded = false; } } else { //No image to upload boolCommit = true; ImageUploaded = false; } if (boolCommit) { if (!FreeTextBox1.Text.Equals("") && !FreeTextBox1.Text.Equals(null) && !FreeTextBox2.Text.Equals("") && !FreeTextBox2.Text.Equals(null)) { teacher.WelcomeText = FreeTextBox1.Text; teacher.BioText = FreeTextBox2.Text; try { DataRepository.TeacherProvider.Update(teacher); if (ImageUploaded) { Label4.Text = "Your details were successfully saved to the database. Visit the My Teacher page to review."; Label4.Visible = true; Image1.ImageUrl = "~" + teacher.PicturePath; } else { Label4.Text = "Your details were successfully saved to the database. No image was uploaded, though. Visit the My Teacher page to review."; Label4.Visible = true; } } catch (Exception ex) { Label4.Text = "Your data was not successfully submitted. There was an error updating the database."; Label4.Visible = true; } } else { Label4.Text = "Your data was not successfully submitted. Please insure that the Welcome Text box and Bio Text box are not empty."; Label4.Visible = true; } } else { Label4.Text = "Your data was not successfully submitted. There was an error uploading the image."; Label4.Visible = true; } }
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(); } } }
protected void Button1_Click(object sender, EventArgs e) { string UpPath = Server.MapPath("~/creator"); Random r = new Random(); int rInt = r.Next(0, 10000); if (!Directory.Exists(UpPath)) { Directory.CreateDirectory(UpPath); info.Text = UpPath + " folder does not exist"; } else { int imgSize = FileUpload1.PostedFile.ContentLength; string imgName = FileUpload1.FileName; string imgPath = "uploaded/" + rInt + imgName; if (FileUpload1.PostedFile.ContentLength > 1000000) { Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Alert", "alert('File is too big.')", true); } else { //then save it to the folder FileUpload1.SaveAs(Server.MapPath(imgPath)); } } string connectionString = WebConfigurationManager.ConnectionStrings["photocatconnection"].ConnectionString; SqlConnection myConnection = new SqlConnection(connectionString); //myConnection.ConnectionString is now set to connectionString. myConnection.Open(); string img = "creator/uploaded/" + rInt + FileUpload1.FileName; DateTime dateNow = DateTime.Now; string locat = locationtext.Text; string pub = PublishList.SelectedValue; string desc = desctext.Text; int cat = CatList.SelectedIndex; if (CatList.SelectedIndex == 0) { UploadPanel.Visible = true; Preview.Visible = true; ScriptManager.RegisterStartupScript(this, GetType(), "catconfirm", "catconfirm();", true); } else { int id = (int)Session["id"]; string query = "INSERT INTO Photos (ImagePath, Location, Published, Description, Likes, UserId, CatId) VALUES ('" + img + "', '" + locat + "', '" + pub + "', '" + desc + "', '0', '" + id + "', '" + cat + "')"; SqlCommand myCommand = new SqlCommand(query, myConnection); myCommand.ExecuteNonQuery(); } //info.Text = "connection to db made"; myConnection.Close(); }
protected void Button1_Click(object sender, EventArgs e) { if (FileUpload1.HasFile) { try { string fileName = FileUpload1.FileName; string extension = System.IO.Path.GetExtension(fileName).ToLower(); string allowExtension = ConfigurationManager.AppSettings["PhotoExtension"].ToString(); if (allowExtension.Contains(extension)) { //文件名 string filename1 = fileName.Substring(fileName.LastIndexOf("\\") + 1); //取得后缀名 string suffix = filename1.Substring(filename1.LastIndexOf(".")); //定义上传路径(在当前目录下的uploadfile文件下) string uploadpath = this.Server.MapPath("upload/Focus"); System.IO.Stream oStream = this.FileUpload1.PostedFile.InputStream; System.Drawing.Image oImage = System.Drawing.Image.FromStream(oStream); int oWidth = oImage.Width; //原图宽度 int oHeight = oImage.Height; //原图高度 int tWidth = 600; //设置缩略图初始宽度 int tHeight = 180; //设置缩略图初始高度 //按比例计算出缩略图的宽度和高度 if (oWidth >= oHeight) { tHeight = (int)Math.Floor(Convert.ToDouble(oHeight) * (Convert.ToDouble(tWidth) / Convert.ToDouble(oWidth))); } else { tWidth = (int)Math.Floor(Convert.ToDouble(oWidth) * (Convert.ToDouble(tHeight) / Convert.ToDouble(oHeight))); } //生成缩略原图 Bitmap tImage = new Bitmap(600, tHeight); Graphics g = Graphics.FromImage(tImage); g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; //设置高质量插值法 g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //设置高质量,低速度呈现平滑程度 g.Clear(Color.Transparent); //清空画布并以透明背景色填充 g.DrawImage(oImage, new Rectangle(0, 0, tWidth, tHeight), new Rectangle(0, 0, oWidth, oHeight), GraphicsUnit.Pixel); //创建一个图像对象取得上传图片对象 //缩略图的保存路径 string fileXltPath = uploadpath + "\\" + filename1.Replace(suffix, "x" + suffix); string fileXltPath2 = "upload/Focus/" + filename1.Replace(suffix, "x" + suffix); //保存缩略图 tImage.Save(fileXltPath, System.Drawing.Imaging.ImageFormat.Jpeg); string now = DateTime.Now.ToString("yyyyMMdd_HHmmss"); string number = String.Format("{0:0000}", new Random().Next(1000));//生产****四位数的字符串 string physicalName = "upload/Focus/" + Session["UserID"].ToString() + "_" + now + "_" + number + extension; //int fileSize = FileUpload1.PostedFile.ContentLength / 1024 ; //if (fileSize == 0) fileSize = 1; FileUpload1.SaveAs(Server.MapPath(physicalName)); using (SqlConnection conn = new DB().GetConnection()) { SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "insert into Focuses( PhotoSrc,UserID,UserName,Thumbnail ) values( @PhotoSrc,@UserID,@UserName,@Thumbnail )"; cmd.Parameters.AddWithValue("@PhotoSrc", physicalName); cmd.Parameters.AddWithValue("@UserID", Session["UserID"].ToString()); cmd.Parameters.AddWithValue("@UserName", Session["UserName"].ToString()); cmd.Parameters.AddWithValue("@Thumbnail", fileXltPath2); conn.Open(); cmd.ExecuteNonQuery(); } Response.Redirect(Server.HtmlEncode("Focus_Man.aspx")); } else { ResultLabel.Text = "上传图片格式错误!"; ResultLabel.Visible = true; } } catch (Exception exc) { ResultLabel.Text = "上传图片失败。请重试!或者与管理员联系!<br>" + exc.ToString(); ResultLabel.Visible = true; } } else { ResultLabel.Text = "所选图片格式不符合要求"; ResultLabel.Visible = true; } }
protected void Button1_Click(object sender, EventArgs e) { //將附件上傳 String fileNameraw = "0"; if (FileUpload1.HasFile) { String fileName = FileUpload1.FileName; fileNameraw = "~/files/signup/" + FileUpload1.FileName; String savePath = Server.MapPath("~/files/signup/"); String saveResult = savePath + fileName; //-- 重點!!必須包含 Server端的「目錄」與「檔名」,才能使用 .SaveAs()方法! FileUpload1.SaveAs(saveResult); //若要更改檔名在此更改 //if (TextBox1.Text != "") //{ // fileName = TextBox1.Text; //} } int check1 = 0; int check2 = 0; //int check3 = 0; //此次新增投票是否開放修改參加者,多人參加和葷食素食選擇 if (CheckBoxList1.Items[0].Selected) { check1 = 1; } if (CheckBoxList1.Items[1].Selected) { check2 = 1; } //if (CheckBoxList1.Items[2].Selected) //{ // check3 = 0; //} //額外要求資訊清單 string list = ""; if (CheckBoxList1.Items[1].Selected) { list += " 需求資料:"; } if (CheckBoxList2.Items[0].Selected) { list += " 身分證 "; } if (CheckBoxList2.Items[1].Selected) { list += " 出生年月日 "; } if (CheckBoxList2.Items[2].Selected) { list += " 飲食狀況 "; } if (CheckBoxList2.Items[3].Selected) { list += " 是否搭乘包車 "; } string name = ""; DAL.JuicDao dao = new DAL.JuicDao("MENU"); var getuser = dao.GetUsername(User.Identity.Name.ToString());//待新增 if (getuser.Rows.Count != 0) { name = getuser.Rows[0]["username"].ToString(); } string strConn = ConfigurationManager.ConnectionStrings["MENU"].ConnectionString; using (SqlConnection conn = new SqlConnection(strConn)) { string strCmd = "Insert into TB_SignupList(Title,Type,Content,Startdate,Enddate,Activedate,Addons1,Addons2,Addons3,FileURL,emp_no,emp_cne)values(@Title,@Type,@Content,@Startdate,@Enddate,@Activedate,@Addons1,@Addons2,@Addons3,@FileURL,@emp_no,@emp_cne)"; using (SqlCommand cmd = new SqlCommand(strCmd, conn)) { cmd.Parameters.AddWithValue("@Title", title.Text); cmd.Parameters.AddWithValue("@Type", DropDownList1.SelectedItem.Text); cmd.Parameters.AddWithValue("@Content", content.Text); cmd.Parameters.AddWithValue("@Startdate", DateTime.Parse(datestart.Text)); cmd.Parameters.AddWithValue("@Enddate", DateTime.Parse(dateend.Text)); cmd.Parameters.AddWithValue("@Activedate", DateTime.Parse(TextBox3.Text)); cmd.Parameters.AddWithValue("@Addons1", check1); cmd.Parameters.AddWithValue("@Addons2", check2); cmd.Parameters.AddWithValue("@Addons3", list); cmd.Parameters.AddWithValue("@FileURL", fileNameraw); cmd.Parameters.AddWithValue("@emp_no", User.Identity.Name.ToString()); cmd.Parameters.AddWithValue("@emp_cne", name); string message = ""; try { conn.Open(); cmd.ExecuteNonQuery(); message = "新增成功"; } catch (Exception ex) { message = ex.Message; } finally { conn.Close(); string strJS = "alert('" + message + "');location.href = ('Join.aspx');"; Page.ClientScript.RegisterStartupScript(this.GetType(), "", strJS, true); } } } }
protected void bt1_Click(object sender, EventArgs e) { try { //validar nome(100) string nome = tbNome.Text.Trim(); if (nome == String.Empty || nome.Length < 2 || nome.Length > 100) { throw new Exception("O nome deve ter pelo menos 2 letras e no máximo 100."); } //validar o ano int iano = 0; if (int.TryParse(tbAno.Text, out iano) == false) { throw new Exception("O ano indicado não é valido.Deve ser um valor numérico."); } if (iano <= 0 || iano > DateTime.Now.Year) { throw new Exception("O ano de edição do livro tem de ser superior a 0 e inferior ou igual ao ano atual."); } //validar a data_aquisicao DateTime dataAquisicao = DateTime.Parse(tbData.Text); if (dataAquisicao > DateTime.Now) { throw new Exception("A data não é válida. Tem de ser inferior ou igual à data atual"); } //validar preco (4,2) Decimal preco = 0; if (Decimal.TryParse(tbPreco.Text, out preco) == false) { throw new Exception("O preço indicado não é válido. Deve ser um valor numérico."); } if (preco < 0 || preco >= 100) { throw new Exception("O preço não é válido. Tem de estar entre 0 e 99,99"); } //validar o autor (100) string autor = tbAutor.Text.Trim(); if (autor == String.Empty || autor.Length < 2 || autor.Length > 100) { throw new Exception("O autor deve ter pelo menos 2 letras e no máximo 100."); } //validar o tipo (50) string tipo = tbTipo.Text.Trim(); if (tipo == String.Empty || tipo.Length > 50) { throw new Exception("O tipo deve ter entre 2 e 50 letras."); } //capa if (FileUpload1.HasFile == false) { throw new Exception("Tem de indicar o ficheiro da capa"); } if (FileUpload1.PostedFile.ContentType != "image/jpeg" && FileUpload1.PostedFile.ContentType != "image/jpg" && FileUpload1.PostedFile.ContentType != "image/png") { throw new Exception("O formato do ficheiro da capa não é suportado."); } if (FileUpload1.PostedFile.ContentLength == 0 || FileUpload1.PostedFile.ContentLength > 5000000) { throw new Exception("O tamanho do ficheiro não é válido."); } //criar objeto livro Livro livro = new Livro(); //preencher propriedades livro.ano = int.Parse(tbAno.Text); livro.autor = tbAutor.Text; livro.data_aquisicao = dataAquisicao; livro.estado = 1; livro.nome = tbNome.Text; livro.preco = decimal.Parse(tbPreco.Text); livro.tipo = tbTipo.Text; //guardar int idlivro = livro.Adicionar(); //copiar o ficheiro string ficheiro = Server.MapPath(@"~\Public\Images\"); ficheiro += idlivro + ".jpg"; FileUpload1.SaveAs(ficheiro); } catch (Exception erro) { lbErro.Text = "Ocorreu o seguinte erro: " + erro.Message; lbErro.CssClass = "alert"; return; } //limpar tbAno.Text = ""; tbAutor.Text = ""; tbNome.Text = ""; tbPreco.Text = ""; tbTipo.Text = ""; lbErro.Text = ""; AtualizarGrid(); }
protected void Button1_Click(object sender, EventArgs e) { string path = Server.MapPath("/Files/" + Session.SessionID + getString() + "." + Path.GetExtension(FileUpload1.PostedFile.FileName)); FileUpload1.SaveAs(path); }
protected void Button1_Click(object sender, EventArgs e) { errorlbl.Text = string.Empty; if (Path.GetExtension(FileUpload1.FileName) != ".txt") { errorlbl.Text = "הקובץ לא מסוג txt"; return; } else if (string.IsNullOrEmpty(TextBox2.Text)) { errorlbl.Text = "לא הוזן מספר מילים"; return; } //the file name var userInput = "userinput" + new Random().Next(0, 999).ToString() + Path.GetExtension(FileUpload1.FileName); //the file full path (directory + filename) var filePath = Path.Combine(Server.MapPath("~"), "Assets", userInput); FileUpload1.SaveAs(filePath); int TotalWords = int.Parse(TextBox2.Text); var filelines = File.ReadAllText(filePath); var results = SearchInBibleText(filelines, TotalWords); //check if was did merging // int flag = 0; if (results.Count() > 1) { for (int j = 0; j < results.Count - 1; j++) { if (results[j].pos + results[j].lenght > results[j + 1].pos) { bool success; var s = results[j].text; var s1 = results[j + 1].text; string merging = Helper.merging(s, s1, out success); if (success) { results[j].text = merging; results[j].lenght = merging.Length; results.RemoveAt(j + 1); } // var checkLocal = Helper.checkLocal(s, s1, TotalWords); // results[j].local = checkLocal; } } } for (int i = 0; i < results.Count; i++) { var check = results[i].text.Split(' '); int count = check.Count(); if (count == 2) { //PlaceHolderResultsPositions.Controls.Add(new Literal() { Text = string.Format("<div data-id='{0}' class='col-md-1 index'>{1}{2}", i, results[i].pos, "</div>") }); filelines = filelines.Replace(results[i].text, string.Format("<a id='{0}' class='marked2 match' data-reference='{3}'>{1}{2}", i, results[i].text, "</a>", PrintRefernces(results[i].references))); continue; } if (count == 3) { filelines = filelines.Replace(results[i].text, string.Format("<a id='{0}' class='marked3 match' data-reference='{3}'>{1}{2}", i, results[i].text, "</a>", PrintRefernces(results[i].references))); continue; } if (count >= 4) { filelines = filelines.Replace(results[i].text, string.Format("<a id='{0}' class='marked4 match' data-reference='{3}'>{1}{2}", i, results[i].text, "</a>", PrintRefernces(results[i].references))); continue; } } filelines = filelines.Replace(Environment.NewLine, "<br />"); PlaceHolderTextResults.Controls.Add(new Literal() { Text = filelines }); }
void updateBookByID() { if (checkIfBookExists()) { try { int actual_stock = Convert.ToInt32(TextBox4.Text.Trim()); int current_stock = Convert.ToInt32(TextBox5.Text.Trim()); if (global_actual_stock == actual_stock) { } else { if (actual_stock < global_issued_books) { Response.Write("<script>alert('Actual Stock value cannot be less than the Issued books');</script>"); return; } else { current_stock = actual_stock - global_issued_books; TextBox5.Text = "" + current_stock; } } string genres = ""; foreach (int i in ListBox1.GetSelectedIndices()) { genres = genres + ListBox1.Items[i] + ","; } genres = genres.Remove(genres.Length - 1); string filepath = "~/book_inventory/books1"; string filename = Path.GetFileName(FileUpload1.PostedFile.FileName); if (filename == "" || filename == null) { filepath = global_filepath; } else { FileUpload1.SaveAs(Server.MapPath("book_inventory/" + filename)); filepath = "~/book_inventory/" + filename; } SqlConnection con = new SqlConnection(strcon); if (con.State == ConnectionState.Closed) { con.Open(); } SqlCommand cmd = new SqlCommand("UPDATE book_master_tbl SET book_name=@book_name, genre=@genre, author_name=@author_name, publisher_name=@publisher_name, publish_date=@publish_date, language=@language, edition=@edition, book_cost=@book_cost, no_of_pages=@no_of_pages, book_description=@book_description, actual_stock=@actual_stock, current_stock=@current_stock, book_img_link=@book_img_link WHERE book_id='" + TextBox1.Text.Trim() + "'", con); cmd.Parameters.AddWithValue("@book_name", TextBox2.Text.Trim()); cmd.Parameters.AddWithValue("@genre", genres); cmd.Parameters.AddWithValue("@author_name", DropDownList3.SelectedItem.Value); cmd.Parameters.AddWithValue("@publisher_name", DropDownList2.SelectedItem.Value); cmd.Parameters.AddWithValue("@publish_date", TextBox3.Text.Trim()); cmd.Parameters.AddWithValue("@language", DropDownList1.SelectedItem.Value); cmd.Parameters.AddWithValue("@edition", TextBox9.Text.Trim()); cmd.Parameters.AddWithValue("@book_cost", TextBox10.Text.Trim()); cmd.Parameters.AddWithValue("@no_of_pages", TextBox11.Text.Trim()); cmd.Parameters.AddWithValue("@book_description", TextBox6.Text.Trim()); cmd.Parameters.AddWithValue("@actual_stock", actual_stock.ToString()); cmd.Parameters.AddWithValue("@current_stock", current_stock.ToString()); cmd.Parameters.AddWithValue("@book_img_link", filepath); cmd.ExecuteNonQuery(); con.Close(); Response.Write("<script>alert('Book Updated Successfully');</script>"); GridView1.DataBind(); } catch (Exception ex) { Response.Write("<script>alert('" + ex.Message + "');</script>"); } } else { Response.Write("<script>alert('Invalid Book ID');</script>"); } }
protected void Button1_Click(object sender, EventArgs e) { //上传 string savePath = null; bool fileflag = false; string filepath = "Files/"; //存储路径 string filename = Server.HtmlEncode(FileUpload1.FileName); //名字 string extension = System.IO.Path.GetExtension(filename); //扩展名字 if (FileUpload1.HasFile) //如果有选择文件 { if (extension == ".xlsx" || extension == ".xls") { savePath = filepath + filename; //存储相对路径 FileUpload1.SaveAs(Server.MapPath(savePath)); //存到服务器 //ClientScript.RegisterStartupScript(GetType(), "message", "<script>alert('上传成功.');</script>"); fileflag = true; } else { //ClientScript.RegisterStartupScript(GetType(), "message", "<script>alert('Wrong file ,please select the right file.');</script>"); errorcode = 1;//文件格式错误 } } else { errorcode = 5; } if (fileflag) { //格式检查 readconfig();//获得配置文件 //DataSet ds = LoadDataFromExcel(Server.MapPath(savePath), extension, excelsheetname.ToString());//存储数据 //DataSet ds1 = ToDataTable(Server.MapPath(savePath)); DataSet ds = new DataSet(); //读取文件 DataTable dt = ImpExcel(Server.MapPath(savePath)); ds.Tables.Add(dt); if (errorcode != 2) { for (int i = 0; i < 16; i++) { string columnname = null; try { columnname = ds.Tables[excelsheetname.ToString()].Columns[i].ColumnName; } catch (Exception ex) { errorcode = 4;//表格格式错误 } if (stringBuilders[i].ToString() != columnname) { errorcode = 4; } } if (errorcode != 3 && errorcode != 4) { //转换 DataSet dstemp = LoadTemplateFromExcel(Server.MapPath("Template/Template.xls"), extension, excelsheetname.ToString()); //存储数据 newexcel(ds, dstemp); addavg(dstemp); //添加 AVG //保存 saveExcel(Server.MapPath("Template/" + excelfilename.ToString() + ".xls"), dstemp); File.Delete(Server.MapPath(savePath)); //killexcel //KillProcess(); //下载 FileTo(); } } //ClientScript.RegisterStartupScript(GetType(), "message", "<script>alert('删除成功.');</script>"); } //删除上传文件 if (errorcode != 1 && errorcode != 0) { File.Delete(Server.MapPath(savePath)); } //错误提示 string errorstring = null; switch (errorcode) { case 0: errorstring = "Convert successful"; break; case 1: errorstring = "Wrong Format ,please select the correct excel file"; break; case 2: errorstring = "Wrong sheet ,please select the correct file"; break; case 3: errorstring = "Can not find the Template file ,please contact administrator"; break; case 4: errorstring = "Wrong file ,please select the correct file"; break; case 5: errorstring = "No file ,please select file"; break; default: //errorstring = "Convert successful"; break; } ClientScript.RegisterStartupScript(GetType(), "message", "<script>alert('" + errorstring + "');</script>"); }
protected void btnUpload_Click(object sender, EventArgs e) { if (FileUpload1.HasFile) { try { if (FileUpload1.PostedFile.ContentLength > 204800) { lblImageUploadMessage.Text = "File size must be less than 200KB."; Page.RegisterStartupScript("Validation", "<script language=\"javascript\">window.alert(\"File size must be less than 200KB.\");</script>"); btnUpload.Enabled = true; return; } string strExtension = ""; String UploadedFile = FileUpload1.PostedFile.FileName; if (UploadedFile.Trim() == "") { btnUpload.Enabled = true; return; } int ExtractPos = UploadedFile.LastIndexOf("."); strExtension = UploadedFile.Substring(ExtractPos, UploadedFile.Length - ExtractPos); if ((strExtension.ToUpper() == ".BMP")) { Page.RegisterStartupScript("Validation", "<script language=\"javascript\">window.alert(\"Bmp format is not allowed. Please choose any other format.\");</script>"); btnUpload.Enabled = true; return; } // code start for "do not upload .txt, .doc file " if ((strExtension.ToUpper() == ".TXT")) { Page.RegisterStartupScript("Validation", "<script language=\"javascript\">window.alert(\"Txt file is not allowed. Please choose any other format.\");</script>"); btnUpload.Enabled = true; return; } // code end for "do not upload .txt file " string strFileName = DateTime.Now.ToString("hh.mm.ss"); strFileName += "_" + DateTime.Today.Day.ToString(); strFileName += "." + DateTime.Today.Month.ToString(); strFileName += "." + DateTime.Now.Year.ToString(); string fileName = Path.GetFileName(FileUpload1.FileName); FileUpload1.SaveAs(Server.MapPath(@"../Images/UserUploadedCoupon" + "/" + strFileName + "_CorporateDiscountCoupon_" + strExtension)); ImagePath = @"Images/UserUploadedCoupon" + "/" + strFileName + "_CorporateDiscountCoupon_" + strExtension; Page.RegisterStartupScript("Validation", "<script language=\"javascript\">window.alert(\"Image uploaded.\");</script>"); lblImageUploadMessage.Text = "Image uploaded."; } catch (Exception ex) { lblSystemMessage.Text = "Error occured while uploading the image." + ex.Message; } } else { lblImageUploadMessage.Text = "Please browse an image."; } }
protected void Button1_Click(object sender, EventArgs e) { if ((FileUpload1.PostedFile != null) && (FileUpload1.PostedFile.ContentLength > 0)) { //try //{ string path = string.Concat(Server.MapPath("~/UploadFile/" + FileUpload1.FileName)); FileUpload1.SaveAs(path); // Connection String to Excel Workbook string excelCS = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0", path); using (OleDbConnection con = new OleDbConnection(excelCS)) { OleDbCommand cmd = new OleDbCommand("select * from [Sheet1$]", con); con.Open(); // Create DbDataReader to Data Worksheet // SQL Server Connection String string CS = "Data Source=LAPTOP-EGV5R1IK\\SQLEXPRESS;Initial Catalog=libbook;Integrated Security=true;"; DbDataReader dr = cmd.ExecuteReader(); using (SqlBulkCopy bulkInsert = new SqlBulkCopy(CS)) { // bulkInsert.Columns["status"].DefaultValue = "active"; bulkInsert.DestinationTableName = "addbooks"; bulkInsert.ColumnMappings.Add("[BookNo]", "BookNo"); bulkInsert.ColumnMappings.Add("[TITLE]", "TITLE"); bulkInsert.ColumnMappings.Add("[AUTHOR]", "AUTHOR"); bulkInsert.ColumnMappings.Add("[YEAR]", "YEAR"); bulkInsert.ColumnMappings.Add("[EDITION]", "EDITION"); bulkInsert.ColumnMappings.Add("[PUBLISHER]", "PUBLISHER"); // bulkInsert.ColumnMappings.Add("[status]"); // bulkInsert.ColumnMappings.Insert("[degree]", "status"); //bulkInsert.ColumnMappings.Add("[status]", "status"); // try //{ bulkInsert.WriteToServer(dr); //Response.Write("hai"); //lblMessage.Visible = true; //lblMessage.Text = "Your file uploaded successfully"; //lblMessage.ForeColor = System.Drawing.Color.Green; //entrydata(); ClientScript.RegisterStartupScript(this.GetType(), "ele", "<script>alert('Your file uploaded successfully');</script>"); //} //catch (Exception ex) //{ //lblMessage.Visible = true; //lblMessage.Text = "Wrong File!.Pls Check Your Xl File"; //lblMessage.ForeColor = System.Drawing.Color.Red; ClientScript.RegisterStartupScript(this.GetType(), "ele", "<script>alert('Wrong File!.Pls Check Your Xl File');</script>"); // } //finally //{ dr.Close(); //} } } } else { //lblMessage.Visible = true; //lblMessage.Text = "* File Required to process upload"; //lblMessage.ForeColor = System.Drawing.Color.Red; ClientScript.RegisterStartupScript(this.GetType(), "ele", "<script>alert('File Required to process upload');</script>"); } }
protected void btnSave_Click(object sender, EventArgs e) { if (txtTitle.Text != "") { string imageone = string.Empty; string Pic1url = ""; if (FileUpload1.HasFile) { string Fname; Fname = Path.GetFileName(FileUpload1.FileName); string ex = Path.GetExtension(Fname); ex = ex.ToLower(); if (ex == ".jpg" || ex == ".bmp" || ex == ".png" || ex == ".jpeg") { try { string STR = Fname; string[] STR1 = STR.Split('.'); string fileName = ""; string extention = ""; string datetime = DateTime.Now.ToString(); datetime = datetime.Replace(' ', '_'); datetime = datetime.Replace(':', '_'); datetime = datetime.Replace('-', '_'); datetime = datetime.Replace('/', '_'); datetime = datetime.Replace('\\', '_'); fileName = STR1[0]; extention = STR1[1]; //Random rnd = new Random(); //string random = rnd.Next(LowerBoundary, UpperBoundary).ToString(); // imageone = "inv/" + fileName + datetime + '.' + extention; imageone = "images/" + fileName + datetime + '.' + extention; //uploadProductPic = "admin/ProjectsPic/" + fileName + datetime + '.' + extention; // Pic1url = "../Cruise/Booking/inv/" + fileName + datetime + "." + extention; Pic1url = "../Cruise/Booking/images/" + fileName + datetime + "." + extention; FileUpload1.SaveAs(Server.MapPath(Pic1url)); //createimage } catch { } } else { ScriptManager.RegisterStartupScript(Page, Page.GetType(), "ss", "<script>alert('Invalid image format!')</script>", false); return; } } else { { ScriptManager.RegisterStartupScript(Page, Page.GetType(), "ss", "<script>alert('Browse an image first!')</script>", false); return; } } int n = dalagent.savebanner(imageone, txtTitle.Text); if (n == 1) { lblMsg.Text = "Save Successfully"; lblMsg.ForeColor = System.Drawing.Color.Red; txtTitle.Text = ""; selectall(); } } else { ScriptManager.RegisterStartupScript(Page, Page.GetType(), "ss", "<script>alert('Please Enter Title!')</script>", false); return; } }
protected void btnok_Click(object sender, EventArgs e) { try { if (FileUpload1.FileName != "") { if (FileUpload1.HasFile) { FileUpload1.SaveAs(Server.MapPath("~/FILES/kutipan/" + FileUpload1.FileName)); string path = Server.MapPath("~/FILES/kutipan/" + FileUpload1.FileName).ToString(); DataTable table = new DataTable(); table.Columns.Add("no_rujukan"); table.Columns.Add("nama_p"); table.Columns.Add("kod_t"); table.Columns.Add("rujukan_t"); table.Columns.Add("tarikh_b"); table.Columns.Add("amaun"); // CONVERT(datetime,LEFT(DTTRX,8) + ' ' + SUBSTRING(DTTRX,9,2) +':'+SUBSTRING(DTTRX,11,2) +':' + RIGHT(DTTRX,2)) as DTTRX using (StreamReader sr = new StreamReader(path)) { while (!sr.EndOfStream) { string myString1 = string.Empty; string[] parts = sr.ReadLine().Split('|'); String dateString = parts[1]; String format = "ddMMyyyy"; DateTime result = DateTime.ParseExact(dateString, format, CultureInfo.InvariantCulture); string d1 = result.ToString("dd/MM/yyyy"); myString1 = parts[2]; List <string> strList = myString1.Split(' ').ToList(); string s1 = strList.First(); string s2 = strList.Last(); DataTable ddicno = new DataTable(); ddicno = Dblog.Ora_Execute_table("select app_applcn_no,app_new_icno,app_name from jpa_application JA where JA.app_new_icno = '" + parts[4] + "'"); string aname = string.Empty; if (ddicno.Rows.Count != 0) { aname = ddicno.Rows[0]["app_name"].ToString(); } else { aname = ""; } table.Rows.Add(parts[0], aname, s1, s2, d1, parts[3]); } } shw_htxt.Visible = true; GridView1.DataSource = table; GridView1.DataBind(); } } else { ScriptManager.RegisterStartupScript(this, GetType(), "alertMessage", "$.Zebra_Dialog('Sila Pilih Fail',{'type': 'warning','title': 'Warning','auto_close': 2000});", true); } } catch (Exception ex) { Page.ClientScript.RegisterStartupScript(typeof(Page), "", "<script>alert('" + ex.Message + "');</script>"); } }
protected void Button1_Click(object sender, EventArgs e) { try { if (FileUpload1.HasFile || FileUpload2.HasFile || FileUpload3.HasFile) { string fileextention = System.IO.Path.GetExtension(FileUpload1.FileName); string fileextention2 = System.IO.Path.GetExtension(FileUpload2.FileName); string fileextention3 = System.IO.Path.GetExtension(FileUpload3.FileName); if (fileextention.ToLower() != ".jpg" && fileextention.ToLower() != ".jpeg" && fileextention2.ToLower() != ".jpg" && fileextention2.ToLower() != ".jpeg" && fileextention3.ToLower() != ".jpg" && fileextention3.ToLower() != ".jpeg") { Label4.Text = "Please select jpeg"; Label4.ForeColor = System.Drawing.Color.Red; } else { int filesize = FileUpload1.PostedFile.ContentLength; int filesize2 = FileUpload2.PostedFile.ContentLength; int filesize3 = FileUpload3.PostedFile.ContentLength; if (filesize > 2097152 && filesize2 > 2097152 && filesize3 > 2097152) { Label4.Text = "select file size with 2 mb"; Label4.ForeColor = System.Drawing.Color.Red; } else { SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString); FileUpload1.SaveAs(Server.MapPath("~/Uploads/States/") + Path.GetFileName(FileUpload1.FileName)); FileUpload2.SaveAs(Server.MapPath("~/Uploads/States/") + Path.GetFileName(FileUpload2.FileName)); FileUpload3.SaveAs(Server.MapPath("~/Uploads/States/") + Path.GetFileName(FileUpload3.FileName)); String link = "Uploads/States/" + Path.GetFileName(FileUpload1.FileName); String link1 = "Uploads/States/" + Path.GetFileName(FileUpload2.FileName); String link2 = "Uploads/States/" + Path.GetFileName(FileUpload3.FileName); string query = "insert into StateData (SName,SImage,SDescription,SImage1,SImage2) values (@state, @image, @description, @image1, @image2)"; SqlCommand cmd = new SqlCommand(query, conn); cmd.Parameters.AddWithValue("@state", TextBox1.Text); cmd.Parameters.AddWithValue("@image", link); cmd.Parameters.AddWithValue("@description", TextBox2.Text); cmd.Parameters.AddWithValue("@image1", link1); cmd.Parameters.AddWithValue("@image2", link2); conn.Open(); cmd.ExecuteNonQuery(); conn.Close(); /*FileUpload1.SaveAs(Server.MapPath("~/Uploads/" +FileUpload1.FileName)); * Label8.Text = "file uploaded"; * Label8.ForeColor = System.Drawing.Color.Green;*/ //SqlCommand cmd = new SqlCommand(query, conn); //com.Parameters.AddWithValue("@ID", newGUID.ToString()); //cmd.Parameters.AddWithValue("@city", TextBoxCT.Text); //cmd.Parameters.AddWithValue("@package1", TextBoxP1.Text); //cmd.Parameters.AddWithValue("@package2", TextBoxP2.Text); // cmd.Parameters.AddWithValue("@package3", TextBoxP3.Text); //Label2.Text = "Video Data Has Been Uploaded and Saved Successfully"; //TextBox1.Text = ""; //TextBox2.Text = ""; /*string content = " window.onload=function(){ alert('"; * content += ");"; * content += "window.location='"; * content += Request.Url.AbsoluteUri; * content += "';}"; * ClientScript.RegisterStartupScript(this.GetType(), "SuccessMessage", content, true); */ } } } else { Label4.Text = "Please select file to upload"; Label4.ForeColor = System.Drawing.Color.Red; } } catch (Exception ex) { Response.Write("Error:" + ex.ToString()); } }
protected void Unnamed_ServerClick(object sender, EventArgs e) { if (tbxMessageText.Value.Length == 0) { return; } string ext = Path.GetExtension(FileUpload1.FileName).ToLower(); if (ext != ".zip" && ext != "" && ext != null) { lblWarning.Text = "فرمت فایل مجاز نیست"; lblWarning.ForeColor = System.Drawing.Color.Red; return; } if (FileUpload1.FileBytes.Length > 1024 * 1024) { lblWarning.Text = "حجم فایل بارگذاری شده بیشتر از 1 مگابایت است"; lblWarning.ForeColor = System.Drawing.Color.Red; return; } // int id = Session["userid"].ToString().ToInt(); string tbl = "adm"; string filename = Path.GetFileName(FileUpload1.FileName); string rand = DBManager.CurrentTimeWithoutColons() + DBManager.CurrentPersianDateWithoutSlash(); filename = rand + filename; string ps = Server.MapPath(@"~\img\") + filename; FileUpload1.SaveAs(ps); FileStream fStream = File.OpenRead(ps); byte[] contents = new byte[fStream.Length]; fStream.Read(contents, 0, (int)fStream.Length); fStream.Close(); FileInfo fi = new FileInfo(ps); fi.Delete(); try { Message msg = new Message(); msg.MessageText = tbxMessageText.Value; msg.MessageDate = DBManager.CurrentPersianDate(); msg.MessageTime = DBManager.CurrentTime(); msg.SenderTable = tbl; msg.SenderID = Session["adminid"].ToString().ToInt(); msg.ChatID = chatid; msg.hasSeen = true; if (contents.Length == 0) { msg.MessageFile = null; } else { msg.MessageFile = contents; } MessageRepository mr = new MessageRepository(); mr.SaveMessages(msg); tbxMessageText.InnerText = ""; lblWarning.Text = ""; } catch { lblWarning.Text = "در ارسال پیام مشکلی بوجود آمد.لطفا مجددا سعی کنید"; lblWarning.ForeColor = System.Drawing.Color.Red; } }
protected void Button4_Click(object sender, EventArgs e) { cid = Request.QueryString["id"].ToString(); string sql = ""; { sql = @"update [dbo].[Results] set voidku='" + Common.strFilter(voidku.Text) + "' where id='" + cid + "'"; } int count = DBqiye.getRowsCount(sql); if (count > 0) { Label7.Text = "保存成功"; } else { Label7.Text = "保存失败" + sql; } typeid = 7; //Label7.Text = ""; if (!FileUpload1.HasFile) { Label6.Text = "请选择文件后上传"; return; } if (FileUpload1.FileBytes.Length > 1024 * 1024 * 50) { Label7.Text = "文件不能大于50M"; return; } string ext = FileUpload1.FileName.Substring(FileUpload1.FileName.Length - 3).ToLower(); if (ext != "mp4" && ext != "rmvb" && ext != "avi" && ext != "rm" && ext != "wmv" && ext != "3gp") { Label7.Text = "文件格式只能是 rm、rmvb、wmv、avi、mp4、3gp"; return; } string file = DateTime.Now.ToString("yyyMMddHHmmss.ss"); string filename = Server.MapPath("~/upload/") + file + "." + ext; FileUpload1.SaveAs(filename); voidfile.Text = "/upload/" + file + "." + ext; //imgh.ImageUrl = "/upload/" + file + "." + ext; //DBC.getRowsCount("update users set headimg='" + headimg.Text + "' where id=" + Session["userid"].ToString()); //imgh.ImageUrl = imgh.ImageUrl; //Session["headimg"] = imgh.ImageUrl; //Global.ROOM.updateheadIMG(ulong.Parse(Session["userid"].ToString()), imgh.ImageUrl); Label7.Text = "上传成功"; cid = Request.QueryString["id"].ToString(); sql = ""; { sql = @"update [dbo].[Results] set voidfile='" + Common.strFilter(voidfile.Text) + "',voidtext='" + Common.strFilter(voidtext.Text) + "',voidku='" + Common.strFilter(voidku.Text) + "' where id='" + cid + "'"; } count = DBqiye.getRowsCount(sql); if (count > 0) { Label7.Text = "保存成功"; } else { Label7.Text = "保存失败" + sql; } Bindpic(cid); }
protected void btnSubmit_Click(object sender, EventArgs e) { Boolean isValid = true; StatusEnum status = (StatusEnum)Enum.Parse(typeof(StatusEnum), this.jobSample.job_status.ToString(), true); switch (status) { case StatusEnum.CHEMIST_TESTING: if (FileUpload2.HasFile) // && (Path.GetExtension(FileUpload2.FileName).Equals(".doc") || Path.GetExtension(FileUpload2.FileName).Equals(".docx"))) { string yyyy = DateTime.Now.ToString("yyyy"); string MM = DateTime.Now.ToString("MM"); string dd = DateTime.Now.ToString("dd"); String source_file = String.Format(Configurations.PATH_SOURCE, yyyy, MM, dd, this.jobSample.job_number, Path.GetFileName(FileUpload2.FileName)); String source_file_url = String.Format(Configurations.PATH_URL, yyyy, MM, dd, this.jobSample.job_number, Path.GetFileName(FileUpload2.FileName)); if (!Directory.Exists(Path.GetDirectoryName(source_file))) { Directory.CreateDirectory(Path.GetDirectoryName(source_file)); } FileUpload2.SaveAs(source_file); this.jobSample.ad_hoc_tempalte_path = source_file_url; } this.jobSample.job_status = Convert.ToInt32(StatusEnum.SR_CHEMIST_CHECKING); this.jobSample.step2owner = userLogin.id; this.jobSample.date_chemist_complete = DateTime.Now; break; case StatusEnum.SR_CHEMIST_CHECKING: StatusEnum srChemistApproveStatus = (StatusEnum)Enum.Parse(typeof(StatusEnum), ddlStatus.SelectedValue, true); switch (srChemistApproveStatus) { case StatusEnum.SR_CHEMIST_APPROVE: this.jobSample.job_status = Convert.ToInt32(StatusEnum.ADMIN_CONVERT_WORD); #region ":: STAMP COMPLETE DATE" this.jobSample.date_srchemist_complate = DateTime.Now; #endregion break; case StatusEnum.SR_CHEMIST_DISAPPROVE: this.jobSample.job_status = Convert.ToInt32(StatusEnum.CHEMIST_TESTING); #region "LOG" job_sample_logs jobSampleLog = new job_sample_logs { ID = 0, job_sample_id = this.jobSample.ID, log_title = String.Format("Sr.Chemist DisApprove"), job_remark = txtRemark.Text, is_active = "0", date = DateTime.Now }; jobSampleLog.Insert(); #endregion break; } this.jobSample.step4owner = userLogin.id; break; case StatusEnum.LABMANAGER_CHECKING: StatusEnum labApproveStatus = (StatusEnum)Enum.Parse(typeof(StatusEnum), ddlStatus.SelectedValue, true); switch (labApproveStatus) { case StatusEnum.LABMANAGER_APPROVE: this.jobSample.job_status = Convert.ToInt32(StatusEnum.ADMIN_CONVERT_PDF); this.jobSample.date_labman_complete = DateTime.Now; break; case StatusEnum.LABMANAGER_DISAPPROVE: this.jobSample.job_status = Convert.ToInt32(ddlAssignTo.SelectedValue); #region "LOG" job_sample_logs jobSampleLog = new job_sample_logs { ID = 0, job_sample_id = this.jobSample.ID, log_title = String.Format("Lab Manager DisApprove"), job_remark = txtRemark.Text, is_active = "0", date = DateTime.Now }; jobSampleLog.Insert(); #endregion break; } this.jobSample.step5owner = userLogin.id; break; case StatusEnum.ADMIN_CONVERT_WORD: if (FileUpload1.HasFile) // && (Path.GetExtension(FileUpload1.FileName).Equals(".doc") || Path.GetExtension(FileUpload1.FileName).Equals(".docx"))) { string yyyy = DateTime.Now.ToString("yyyy"); string MM = DateTime.Now.ToString("MM"); string dd = DateTime.Now.ToString("dd"); String source_file = String.Format(Configurations.PATH_SOURCE, yyyy, MM, dd, this.jobSample.job_number, Path.GetFileName(FileUpload1.FileName)); String source_file_url = String.Format(Configurations.PATH_URL, yyyy, MM, dd, this.jobSample.job_number, Path.GetFileName(FileUpload1.FileName)); if (!Directory.Exists(Path.GetDirectoryName(source_file))) { Directory.CreateDirectory(Path.GetDirectoryName(source_file)); } FileUpload1.SaveAs(source_file); this.jobSample.path_word = source_file_url; this.jobSample.job_status = Convert.ToInt32(StatusEnum.LABMANAGER_CHECKING); } else { errors.Add("Invalid File. Please upload a File with extension .doc|.docx"); } this.jobSample.step6owner = userLogin.id; break; case StatusEnum.ADMIN_CONVERT_PDF: if (FileUpload1.HasFile) // && (Path.GetExtension(FileUpload1.FileName).Equals(".pdf"))) { string yyyy = DateTime.Now.ToString("yyyy"); string MM = DateTime.Now.ToString("MM"); string dd = DateTime.Now.ToString("dd"); String source_file = String.Format(Configurations.PATH_SOURCE, yyyy, MM, dd, this.jobSample.job_number, Path.GetFileName(FileUpload1.FileName)); String source_file_url = String.Format(Configurations.PATH_URL, yyyy, MM, dd, this.jobSample.job_number, Path.GetFileName(FileUpload1.FileName)); if (!Directory.Exists(Path.GetDirectoryName(source_file))) { Directory.CreateDirectory(Path.GetDirectoryName(source_file)); } FileUpload1.SaveAs(source_file); this.jobSample.path_pdf = source_file_url; this.jobSample.job_status = Convert.ToInt32(StatusEnum.JOB_COMPLETE); this.jobSample.step7owner = userLogin.id; //lbMessage.Text = string.Empty; } else { errors.Add("Invalid File. Please upload a File with extension .pdf"); //lbMessage.Attributes["class"] = "alert alert-error"; //isValid = false; } break; } if (errors.Count > 0) { litErrorMessage.Text = MessageBox.GenWarnning(errors); modalErrorList.Show(); } else { litErrorMessage.Text = String.Empty; //######## this.jobSample.Update(); //Commit GeneralManager.Commit(); removeSession(); MessageBox.Show(this.Page, Resources.MSG_SAVE_SUCCESS, PreviousPath); } }
protected void ImageButtonSalvar_Click(object sender, ImageClickEventArgs e) { if (FileUpload1.HasFile) { string id = ""; string nameFile = ""; try { id = obterIdCadastrado(); } catch (Exception ex) { LabelErro.Text = ex.Message; ImageAttention.Visible = true; } if (Session["abaAtiva"].ToString().Equals((string)"TabPanelPessoais")) { nameFile = "docsPessoais"; } else if (Session["abaAtiva"].ToString().Equals((string)"TabPanelTitulacao")) { nameFile = "titulacoes"; } else if (Session["abaAtiva"].ToString().Equals((string)"TabPanelPortaria")) { nameFile = "portarias"; } else if (Session["abaAtiva"].ToString().Equals((string)"TabPanelCI")) { nameFile = "cis"; } else if (Session["abaAtiva"].ToString().Equals((string)"TabPanelAviso")) { nameFile = "avisoFerias"; } else if (Session["abaAtiva"].ToString().Equals((string)"TabPanelRequerimento")) { nameFile = "requerimentos"; } else if (Session["abaAtiva"].ToString().Equals((string)"TabPanelOutros")) { nameFile = "outros"; } string nomeArquivo = montarFormatoGD(id, nameFile + ext); if (Session["postou_" + nameFile].ToString().Equals((string)"sim")) { // Create a merge document and set it's properties MergeDocument document = MergeDocument.Merge(pathDir + nomeArquivo, FileUpload1.PostedFile.FileName); // Outputs the merged document document.Draw(nomeArquivo); System.IO.File.Delete(pathDir + nomeArquivo); System.IO.File.Move(nomeArquivo, pathDir + nomeArquivo); } //se ainda nao postou o documento nao precisa fazer um merge else { try { FileUpload1.SaveAs(pathDir + nomeArquivo); Session.Add("fileName", nomeArquivo); } catch (Exception ex) { LabelErro.Text = ex.Message; ImageAttention.Visible = true; } } TableArquivo.Visible = true; LabelArquivo.Text = nomeArquivo; ImageButtonVer.Visible = true; ImageButtonDelete.Visible = true; //levantar flag dizendo que o arquivo foi postado Session.Add("postou_" + nameFile, "sim"); Arquivo arq = new Arquivo(); arq.nome_Arquivo = nomeArquivo; arq.tipo_Arquivo = nameFile; List <Arquivo> lista = new List <Arquivo>(); lista = (List <Arquivo>)Session["arquivos"]; if (lista == null) { lista = new List <Arquivo>(); } lista.Add(arq); Session["arquivos"] = lista; } else { //Mostra o Erro quando não tem arquivo selecionado LabelErro.Text = "Selecione o arquivo"; ImageAttention.Visible = true; } }
protected void submit_Click(object sender, EventArgs e) { string fileName = string.Empty; if (FileUpload1.HasFile) { fileName = FileUpload1.FileName.ToString(); string uploadFolderPath = "~/UserImages/"; string filePath = HttpContext.Current.Server.MapPath(uploadFolderPath); FileUpload1.SaveAs(filePath + "\\" + fileName); } else { fileName = "user.jpg"; } string Usertype = string.Empty; string UserMerchant = "TravelRezOnline"; if (LoginType.Text == "Agents") { Usertype = "A"; } else if (LoginType.Text == "Distributer") { Usertype = "D"; } else if (LoginType.Text == "Agent Staff") { Usertype = "AU"; } else if (LoginType.Text == "Staff") { Usertype = "S"; } string sid = string.Empty; string sql2 = "Select top 1 sid from tblAgentdetails ORDER BY sid DESC;"; SqlDataReader sdr1 = DB.CommonDatabase.DataReader(sql2); try { if (sdr1.Read()) { sid = sdr1["sid"].ToString(); sid = (Convert.ToInt32(sid) + 1).ToString(); } else { } } catch (Exception) { } string supp = ""; string comm = ""; string sSql = "select * from Markup"; SqlDataReader sdr = DB.CommonDatabase.DataReader(sSql); try { while (sdr.Read()) { supp = sdr["hotelmarkup"].ToString() + ","; comm = sdr["hotelcomm"].ToString() + ","; } } catch (Exception) { } finally { sdr.Close(); } string refuserid = Session["loginVal"].ToString(); string loginid = "select * from Adminlogin where username='******'"; SqlDataReader sdrs = DB.CommonDatabase.DataReader(loginid); if (sdrs.Read()) { Label1.ForeColor = Color.Red; Label1.Text = "UserID already Exists!"; UserId.Focus(); } else { string SQL = "Insert into tblAgentdetails(userid,password,AgentCode,Usertype,ValidationCode,loginType,agencylogo,agencyName,address,PhoneNo,Contact,Emailid,UserMerchant,FirstName,LastName,Currency,City,State,PinCode,Remarks,hotelmarkup,hotelcomm,Country,RefAgency) values("; SQL += "'" + UserId.Text + "',"; SQL += "'" + Password.Text + "','TRAVREZ" + sid + "',"; SQL += "'" + Usertype + "','" + Usertype + "',"; SQL += "'" + LoginType.Text + "',"; SQL += "'" + fileName + "',"; SQL += "'" + AgencyName.Text + "',"; SQL += "'" + Address.Text + "',"; SQL += "'" + Phone.Text + "',"; SQL += "'" + Mobile.Text + "',"; SQL += "'" + UserId.Text + "',"; SQL += "'" + UserMerchant + "',"; SQL += "'" + FirstName.Text + "',"; SQL += "'" + LastName.Text + "',"; SQL += "'" + Currency.Text + "',"; SQL += "'" + City.Text + "',"; SQL += "'" + State.Text + "',"; SQL += "'" + PinCode.Text + "',"; SQL += "'" + Remarks.Text + "','" + supp + "','" + comm + "','" + Country.SelectedValue + "','" + refuserid + "')"; try { DB.CommonDatabase.RunQuery(SQL); } catch (Exception) { } string dcarduser = GenrateRandomNumber(); string sql1 = "Insert into Adminlogin(username,Password,Agencyid,AgencyName,ValidationCode,usertype,type,ContactPerson,designation,Phone,Mobile,Email,Address,city,state,LoginFlag,PanNo,ServiceTaxNo,DCarduser,country,JoingDate,image,refagency) values("; sql1 += "'" + UserId.Text + "',"; sql1 += "'" + Password.Text + "','TRAVREZ" + sid + "',"; sql1 += "'" + AgencyName.Text + "',"; sql1 += "'" + Usertype + "',"; sql1 += "'" + LoginType.Text + "',"; sql1 += "'" + Usertype + "',"; sql1 += "'" + FirstName.Text + " " + LastName.Text + "',"; sql1 += "'" + Designation.Text + "',"; sql1 += "'" + Phone.Text + "',"; sql1 += "'" + Mobile.Text + "',"; sql1 += "'" + UserId.Text + "',"; sql1 += "'" + Address.Text + "',"; sql1 += "'" + City.Text + "',"; sql1 += "'" + State.Text + "',"; sql1 += "'0',"; sql1 += "'" + TextBox1.Text + "',"; sql1 += "'" + TextBox2.Text + "',"; sql1 += "'" + fileName + "',"; sql1 += "'" + dcarduser + "','" + Country.SelectedValue + "','" + DateTime.Now.ToShortDateString() + "','" + refuserid + "')"; try { DB.CommonDatabase.RunQuery(sql1); Label1.ForeColor = System.Drawing.Color.DarkGreen; Label1.Text = "Agent Id Registered Successfully, Contact Admin for activation"; } catch (Exception) { } //try //{ // string xml = string.Empty; // xml += "<?xml version='1.0' encoding='utf-8'?>"; // xml += "<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>"; // xml += "<soap:Body>"; // xml += "<AddNewAgent xmlns='http://tempuri.org/'>"; // xml += "<EmailID>" + UserId.Text + "</EmailID>"; // xml += "<Password>" + Password.Text + "</Password>"; // xml += "</AddNewAgent>"; // xml += "</soap:Body>"; // xml += "</soap:Envelope>"; // string url = "http://bookingapi.theholidaykingdom.com/ApiList.asmx"; // cls.CommonClass obj = new cls.CommonClass(); // string responsedata = obj.PostXml4Min(url, xml); //} //catch (Exception) { } try { MailMessage mm = new MailMessage("" + ConfigurationManager.AppSettings["UserName"] + "", UserId.Text); mm.Subject = "Your Account is Created"; // mm.Body = string.Format("Dear " + FirstName.Text + " " + LastName.Text + " ,<br /><br /> Your ID and password are given below.<br />UserId: " + UserId.Text + "<br />Password: "******"<br>* Request you to please send us your GST Number.<br /><br />For your account activation please contact to Admin."); mm.Body = string.Format("Dear " + FirstName.Text + " " + LastName.Text + " ,<br /><br /> Your ID and password are given below.<br />UserId: " + UserId.Text + "<br />Password: "******"<br>* Request you to please send us your GST Number. <br /><br />For your account activation please contact to Admin."); mm.IsBodyHtml = true; SmtpClient smtp = new SmtpClient(); smtp.Host = ConfigurationManager.AppSettings["Host"]; smtp.EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSsl"]); //smtpClient.EnableSsl = true; ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return(true); }; NetworkCredential NetworkCred = new NetworkCredential(); NetworkCred.UserName = ConfigurationManager.AppSettings["UserName"]; NetworkCred.Password = ConfigurationManager.AppSettings["Password"]; smtp.UseDefaultCredentials = true; smtp.Credentials = NetworkCred; smtp.Port = int.Parse(ConfigurationManager.AppSettings["Port"]); smtp.Send(mm); } catch (Exception ex) { } } }
protected void Upload(object sender, EventArgs e) { if (FileUpload1.PostedFile.FileName.Length > 0) { //Upload and save the file string csvPath = Server.MapPath("~/Files/") + Path.GetFileName(FileUpload1.PostedFile.FileName); FileUpload1.SaveAs(csvPath); DataTable dt = new DataTable(); dt.Columns.AddRange(new DataColumn[9] { new DataColumn("MarketCode", typeof(string)), new DataColumn("StockCode", typeof(string)), new DataColumn("SockName", typeof(string)), new DataColumn("PriceOpen", typeof(string)), new DataColumn("PriceHigh", typeof(string)), new DataColumn("PriceLow", typeof(string)), new DataColumn("PriceClose", typeof(string)), new DataColumn("Volume", typeof(string)), new DataColumn("PriceDate", typeof(string)) }); string csvData = File.ReadAllText(csvPath); if (myDateField.Value.Length > 0) { if (ValidateCsv(csvData)) { var rows = csvData.Split('\n'); var rowLength = rows.Length; for (int j = 3; j < rowLength; j++) { if (!string.IsNullOrEmpty(rows[j])) { dt.Rows.Add(); //int i = 0; var cells = rows[j].Split(','); cells[8] = myDateField.Value; var cellLength = cells.Length - 1; for (int i = 0; i < cellLength; i++) { if (!String.IsNullOrEmpty(cells[i])) { dt.Rows[dt.Rows.Count - 1][i] = cells[i]; } } } } MySql.Data.MySqlClient.MySqlConnection conn = new MySqlConnection(GetConnectionString()); MySqlCommand cmd = null; conn.Open(); foreach (DataRow row in dt.Rows) { try { //Console.WriteLine("Connecting to MySQL..."); cmd = new MySqlCommand(); cmd.Connection = conn; cmd.CommandText = "SPInsertStockTransaction"; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("i_MarketCode", row[0]); cmd.Parameters["i_MarketCode"].Direction = ParameterDirection.Input; cmd.Parameters["i_MarketCode"].MySqlDbType = MySqlDbType.VarChar; cmd.Parameters.AddWithValue("i_StockCode", row[1]); cmd.Parameters["i_StockCode"].MySqlDbType = MySqlDbType.VarChar; cmd.Parameters["i_StockCode"].Direction = ParameterDirection.Input; cmd.Parameters.AddWithValue("i_PriceDate", DateTime.Parse(row[8].ToString()).ToString("yyyy-MM-dd")); cmd.Parameters["i_PriceDate"].MySqlDbType = MySqlDbType.Date; cmd.Parameters["i_PriceDate"].Direction = ParameterDirection.Input; cmd.Parameters.AddWithValue("i_PriceOpen", (row[3])); cmd.Parameters["i_PriceOpen"].MySqlDbType = MySqlDbType.Decimal; cmd.Parameters["i_PriceOpen"].Direction = ParameterDirection.Input; cmd.Parameters.AddWithValue("i_PriceHigh", (row[4])); cmd.Parameters["i_PriceHigh"].MySqlDbType = MySqlDbType.Decimal; cmd.Parameters["i_PriceHigh"].Direction = ParameterDirection.Input; cmd.Parameters.AddWithValue("i_PriceLow", (row[5])); cmd.Parameters["i_PriceLow"].MySqlDbType = MySqlDbType.Decimal; cmd.Parameters["i_PriceLow"].Direction = ParameterDirection.Input; cmd.Parameters.AddWithValue("i_PriceClose", (row[6])); cmd.Parameters["i_PriceClose"].MySqlDbType = MySqlDbType.Decimal; cmd.Parameters["i_PriceClose"].Direction = ParameterDirection.Input; cmd.Parameters.AddWithValue("i_PriceVolumn", (row[7])); cmd.Parameters["i_PriceVolumn"].MySqlDbType = MySqlDbType.Decimal; cmd.Parameters["i_PriceVolumn"].Direction = ParameterDirection.Input; //Add the output parameter to the command object cmd.Parameters.Add(new MySqlParameter("o_Flag", MySqlDbType.String)); cmd.Parameters["o_Flag"].Direction = ParameterDirection.Output; cmd.Parameters.Add(new MySqlParameter("o_ErrorCode", MySqlDbType.String)); cmd.Parameters["o_ErrorCode"].Direction = ParameterDirection.Output; cmd.Parameters.Add(new MySqlParameter("o_ErrorDescription", MySqlDbType.String)); cmd.Parameters["o_ErrorDescription"].Direction = ParameterDirection.Output; cmd.ExecuteNonQuery(); } catch (MySql.Data.MySqlClient.MySqlException ex) { errorMsg.InnerText = ex.Message; conn.Close(); break; } errorMsg.InnerText = "ファイルアップロードを成功しました。"; } //cmd.Dispose(); conn.Close(); } else { errorMsg.InnerText = "ファイルフォーマットは無効です。"; } } else { errorMsg.InnerText = "正しい日付を指定してください。"; } } else { errorMsg.InnerText = "ファイルを指定してください。"; } }
public void btnUpload_Click(object sender, EventArgs e) { const int sizeLimit = 5242880; if (FileUpload1.HasFile) { if (FileUpload1.PostedFile.ContentLength <= sizeLimit) { string path = @"C:\Users\Bateman\Documents\Visual Studio 2015\WebSites\TuteMCAQ\AdminTuteMCAQ\XmlFiles\" + FileUpload1.FileName; FileUpload1.SaveAs(path); lblMessage.ForeColor = System.Drawing.Color.Green; lblMessage.Text = "File Uploaded to " + path; try { string CS = ConfigurationManager.ConnectionStrings["TuteDB"].ConnectionString; using (SqlConnection con = new SqlConnection(CS)) { DataSet ds = new DataSet(); //ds.ReadXml(Server.MapPath("~/MyXMLdata.xml")); ds.ReadXml(path); DataTable dtQues = ds.Tables["Question"]; con.Open(); using (SqlBulkCopy bc = new SqlBulkCopy(con)) { bc.DestinationTableName = "Question"; //bc.ColumnMappings.Add("QuestionID", "QuestionID"); bc.ColumnMappings.Add("QuestText", "QuestText"); bc.ColumnMappings.Add("TypeOfQ", "TypeOfQ"); bc.ColumnMappings.Add("Option1", "Option1"); bc.ColumnMappings.Add("Option2", "Option2"); bc.ColumnMappings.Add("Option3", "Option3"); bc.ColumnMappings.Add("Option4", "Option4"); bc.ColumnMappings.Add("CorrectOption", "CorrectOption"); bc.WriteToServer(dtQues); } if ((System.IO.File.Exists(path))) { System.IO.File.Delete(path); lblMessage.ForeColor = System.Drawing.Color.Green; lblMessage.Text = "Insertion Successful and File Deleted!"; } } } catch (Exception ex) { lblMessage.ForeColor = System.Drawing.Color.Red; lblMessage.Text = "File Uploaded but database exception occured - " + ex.Message; if ((System.IO.File.Exists(path))) { System.IO.File.Delete(path); } } } else { lblMessage.ForeColor = System.Drawing.Color.Red; lblMessage.Text = "File exceeds size limit"; } } else { lblMessage.ForeColor = System.Drawing.Color.Red; lblMessage.Text = "No file to upload. Choose a file first."; } }
protected void Button1_Click(object sender, EventArgs e) { if (FileUpload1.HasFile == false)//HasFile用来检查FileUpload是否有指定文件 { Response.Write("<script>alert('请您选择Excel文件')</script> "); return; //当无文件时,返回 } string IsXls = System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower(); //System.IO.Path.GetExtension获得文件的扩展名 if (IsXls != ".xls" && IsXls != ".xlsx") { Response.Write("<script>alert('只可以选择Excel文件')</script>"); return; //当选择的不是Excel文件时,返回 } string filename = DateTime.Now.ToString("yyyymmddhhMMss") + FileUpload1.FileName; //获取Execle文件名 DateTime日期函数 string savePath = Server.MapPath(("~\\upfiles\\") + filename); //Server.MapPath 获得虚拟服务器相对路径 FileUpload1.SaveAs(savePath); //SaveAs 将上传的文件内容保存在服务器上 DataSet ds = Util.ExecleDs(savePath, filename); //调用自定义方法 DataRow[] dr = ds.Tables[0].Select(); //定义一个DataRow数组 int rowsnum = ds.Tables[0].Rows.Count; DataTable dt = Util.GetTableSchema(); if (rowsnum == 0) { Response.Write("<script>alert('Excel表为空表,无数据!')</script>"); //当Excel表为空时,对用户进行提示 } else { using (SqlConnection conn = new DB().GetConnection()) { SqlBulkCopy bulkCopy = new SqlBulkCopy(conn); bulkCopy.DestinationTableName = "Students"; bulkCopy.BatchSize = dr.Length; conn.Open(); for (int i = 0; i < dr.Length; i++) { string psd = ""; foreach (string str in dr[i]["出生日期"].ToString().Split(' ')[0].ToString().Split('/')) { string time = str; Util.ShowMessage(str, ""); if (int.Parse(time) < 10) { time = "0" + Convert.ToString(time); } psd += time; } DataRow dr1 = dt.NewRow(); dr1[1] = Guid.NewGuid(); dr1[3] = dr[i]["年级"].ToString(); dr1[4] = dr[i]["年级"].ToString() + dr[i]["班级"].ToString(); dr1[6] = dr[i]["校内学号"].ToString(); dr1[7] = dr[i]["学生姓名"].ToString(); dr1[8] = dr[i]["性别"].ToString(); dr1[14] = Util.GetHash(psd); dr1[15] = Convert.ToDateTime(dr[i]["出生日期"].ToString()); dt.Rows.Add(dr1); } if (dt != null && dt.Rows.Count != 0) { bulkCopy.WriteToServer(dt); Response.Write("<script>alert('成功导入数据');location='User_Man.aspx'</script></script> "); } } } }
protected void SubmitSerial_Click(object sender, EventArgs e) { if (TypeList.SelectedValue == "現有船型") { Label2.Visible = true; Label2.Text = "未選擇船型"; } else { TypeSerial(); if (string.IsNullOrEmpty(SerialEdit.Text)) { Label2.Visible = true; Label2.Text = "請輸入型號"; } else if (HiddenField2.Value.IndexOf("," + SerialEdit.Text + ",", StringComparison.OrdinalIgnoreCase) > -1) { Label2.Visible = true; Label2.Text = "此船型已有相同型號"; } else if (RadioButtonList1.SelectedItem == null) { Label2.Text = "請選擇是否為最新型"; Label2.Visible = true; } else { if (FileUpload1.HasFile) { string fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower(); //取得副檔名並轉成小寫 string[] allowExtension = { ".gif", ".png", ".jpeg", ".jpg", ".bmp" }; //宣告一個陣列,內容為符合的副檔名 bool fileOk = false; for (int i = 0; i < allowExtension.Length; i++) //判斷檔案的副檔名 { if (fileExtension == allowExtension[i]) { fileOk = true; break; //有true就可以出來了 } } if (fileOk == true) { string filename = FileUpload1.FileName; filename = DateTime.Now.ToString("yyyyMMdd") + "_" + filename;//加上前墜時間 string Path = Server.MapPath(@"~\images\yachts\"); string save = Path + filename; //存進原圖 FileUpload1.SaveAs(save); //從路徑找剛剛存進的圖縮小後再存 GenerateThumbnailImage(filename, Path, Path, "s_", 63); gotoSQL(filename); } } else { Label2.Visible = true; Label2.Text = "缺少首頁圖片"; } } } }
protected void DoUpload(string userID) { if (FileUpload1.HasFile) { try { string fileName = FileUpload1.FileName; string extension = System.IO.Path.GetExtension(fileName).ToLower(); string allowExtension = ConfigurationManager.AppSettings["PhotoExtension"].ToString(); if (allowExtension.Contains(extension)) { string now = DateTime.Now.ToString("yyyyMMdd_HHmmss"); string number = String.Format("{0:0000}", new Random().Next(1000));//生产****四位数的字符串 string physicalName = "Users/" + userID + "/" + now + "_" + number + extension; //int fileSize = FileUpload1.PostedFile.ContentLength / 1024 ; //if (fileSize == 0) fileSize = 1; FileUpload1.SaveAs(Server.MapPath(physicalName)); using (SqlConnection conn = new DB().GetConnection()) { string profileID = ""; SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "select ID from Profiles where UserID = " + userID + " order by ID desc"; conn.Open(); SqlDataReader rd = cmd.ExecuteReader(); if (rd.Read()) { profileID = rd["ID"].ToString(); } rd.Close(); cmd = conn.CreateCommand(); if (String.IsNullOrEmpty(profileID)) { cmd.CommandText = "insert into Profiles( UserID,BigPhotoSrc) values( @UserID,@BigPhotoSrc )"; cmd.Parameters.AddWithValue("@UserID", userID); cmd.Parameters.AddWithValue("@BigPhotoSrc", physicalName); } else { cmd.CommandText = "update Profiles set BigPhotoSrc = @BigPhotoSrc where ID = @ID"; cmd.Parameters.AddWithValue("@BigPhotoSrc", physicalName); cmd.Parameters.AddWithValue("@ID", profileID); } cmd.ExecuteNonQuery(); conn.Close(); } BigImage.ImageUrl = physicalName; //MyDataBind(); } else { ResultLabel.Text = "上传图片格式错误!"; ResultLabel.Visible = true; } } catch (Exception exc) { ResultLabel.Text = "上传图片失败。请重试!或者与管理员联系!<br>" + exc.ToString(); ResultLabel.Visible = true; } } else { ResultLabel.Text = "所选图片格式不符合要求"; ResultLabel.Visible = true; } }