protected void btnUpdate_Click(object sender, EventArgs e) { rc = new ReportController(); Report r = new Report(); r.ReportNo = tbxReportNo.Text; r.SubmitterName = tbxSubmitterName.Text; r.Date = Convert.ToDateTime(tbxDate.Text); r.Location = ddlLocation.Text; r.Classification = ddlClassification.Text; r.Description = tbxDescription.Text; r.Memo = tbxMemo.Text; string fileName = tbxReportNo.Text + Path.GetExtension(UploadPhoto.FileName); string photopath = Server.MapPath("~/Pictures/") + fileName; if (UploadPhoto.PostedFile.FileName == "" || UploadPhoto.PostedFile.FileName == null) { photopath = null; r.PhotoPath = null; } else { //string fileName = tbxReportNo.Text + Path.GetExtension(UploadPhoto.FileName); //string photopath = Server.MapPath("~/Pictures/") + fileName; UploadPhoto.SaveAs(photopath); r.PhotoPath = fileName; } rc.UpdateReport(r); Response.Redirect("~/Admin/ReportList.aspx"); }
public void Enter_Value_ListARentalPage() { // var SelectElement = new SelectElement(SelectProp); // SelectElement.SelectByIndex(1); Actions actions = new Actions(_driver); actions.MoveToElement(SelectProp); actions.Click(); actions.SendKeys("1222 High Street, Taita, Lower Hutt, 5011"); actions.Build().Perform(); System.Threading.Thread.Sleep(200); Title.SendKeys("TestTitleNewToRent"); Description.SendKeys("Description To Test"); MovingCost.SendKeys("2000"); TargetRent.SendKeys("200"); AvailableDate.Click(); AvailableDate.Clear(); AvailableDate.SendKeys("16/07/2019"); System.Threading.Thread.Sleep(250); OccupantsCount.SendKeys("2"); UploadPhoto.SendKeys(@"C:\Users\Mallik\Documents\Key-Project\property-connect-home.jpg"); System.Threading.Thread.Sleep(150); Save.Click(); _Wait.Until(condition: ExpectedConditions.ElementExists(By.Id("SearchBox"))); // IAlert alert = _driver.SwitchTo().Alert(); // alert.Accept(); // System.Threading.Thread.Sleep(50); }
public async Task postData(string username, string password, string documentid, StreamContent streamContent) { UploadPhoto details = new UploadPhoto(); try { System.Diagnostics.Debug.WriteLine("uplod done"); var clinet = new HttpClient(); var content = new MultipartFormDataContent(); content.Add(streamContent, "file", "test.jpeg"); System.Net.Http.HttpResponseMessage r = await clinet.PostAsync(YOUR_URL, content); string json = await r.Content.ReadAsStringAsync(); details = JsonConvert.DeserializeObject <UploadPhoto>(json); if (details.message == "Upload success") { success = 200; } success = 200; } catch (Exception e) { Debug.WriteLine(e.Message); success = 400; } }
protected void btnSubmit_Click(object sender, EventArgs e) { Observation obs = new Model.Observation(); //cardId = Convert.ToInt32(Session["CardId"]); //cardId = Convert.ToInt32(Request.QueryString["CardId"]); obs.CardId = cardId; //date = o.Date; obs.Date = context.Observations.Where(x => x.CardId == cardId).Select(x => x.Date).First(); obs.Location = ddlLocation.Text; obs.Others = tbxOthers.Text; obs.Classification = ddlClassification.Text; obs.Description = tbxDescription.Text; obs.ImmediateAction = tbxImmAction.Text; obs.FurtherAction = tbxFurtherAction.Text; obs.PositiveComment = tbxComment.Text; string fileName = DateTime.Now.ToString("ddMMyyyy-hhmmss") + Path.GetExtension(UploadPhoto.FileName); string photopath = Server.MapPath("~/Pictures/") + fileName; if (UploadPhoto.PostedFile.FileName != "") { UploadPhoto.SaveAs(photopath); obs.PhotoPath = fileName; } oc.UpdateObservation(obs); Response.Redirect("~/Users/ObservationList.aspx"); }
public async Task <IActionResult> UploadConfirmed([Bind("ProfileImage")] UploadPhoto upload) { if (ModelState.IsValid) { var user = await _userManager.GetUserAsync(User); //search for current user information var entity = _context.Users.FirstOrDefault(i => i.Id == user.Id); if (entity != null) { //add Profile Image string wwwRootPath = _hostEnvironment.WebRootPath; string fileName = Path.GetFileNameWithoutExtension(upload.ProfileImage.FileName); string extension = Path.GetExtension(upload.ProfileImage.FileName); upload.ProfileImageName = fileName = fileName + DateTime.Now.ToString("yymmssfff") + extension; string path = Path.Combine(wwwRootPath + "/image", fileName); using (var fileStream = new FileStream(path, FileMode.Create)) { await upload.ProfileImage.CopyToAsync(fileStream); } entity.ProfileImage = fileName; await _userManager.UpdateAsync(entity); _logger.LogInformation("User profile photo updated"); return(RedirectToAction("Index", "Profile")); } } return(View()); }
protected void btnSubmit_Click(object sned, EventArgs e) { Observation o = new Observation(); //Take submitter name from cookies o.Name = Session["username"].ToString(); o.Date = DateTime.Today.Date; o.Location = ddlLocation.Text; o.Classification = ddlClassification.Text; o.Description = tbxDescription.Text; string fileName = DateTime.Now.ToString("ddMMyyyy-hhmmss") + Path.GetExtension(UploadPhoto.FileName); string photopath = Server.MapPath("~/Pictures/") + fileName; if (UploadPhoto.PostedFile.FileName == "" || UploadPhoto.PostedFile.FileName == null) { photopath = null; o.PhotoPath = null; } else { //string fileName = tbxReportNo.Text + Path.GetExtension(UploadPhoto.FileName); //string photopath = Server.MapPath("~/Pictures/") + fileName; UploadPhoto.SaveAs(photopath); o.PhotoPath = fileName; } o.ImmediateAction = tbxImmAction.Text; o.FurtherAction = tbxFurtherAction.Text; o.PositiveComment = tbxComment.Text; context.Observations.Add(o); context.SaveChanges(); Response.Redirect("~/ObservationList.aspx"); }
public void Enter_Value_ListARentalPage() { // var SelectElement = new SelectElement(SelectProp); // SelectElement.SelectByIndex(1); Actions actions = new Actions(_driver); actions.MoveToElement(SelectProp); actions.Click(); actions.SendKeys("1222 High Street, Taita, Lower Hutt, 5011"); actions.Build().Perform(); System.Threading.Thread.Sleep(50); Title.SendKeys("TestTitleNewToRent"); Description.SendKeys("Description To Test"); MovingCost.SendKeys("2000"); TargetRent.SendKeys("200"); AvailableDate.SendKeys("10/05/2019"); System.Threading.Thread.Sleep(50); OccupantsCount.SendKeys("2"); UploadPhoto.SendKeys(@"C:\Users\Mallik\Desktop\Test.jpg"); System.Threading.Thread.Sleep(50); Save.Click(); // IAlert alert = _driver.SwitchTo().Alert(); // alert.Accept(); // System.Threading.Thread.Sleep(50); }
/// <summary> /// Desc : upload Profile Pic /// </summary> /// <param name="userName"></param> /// <param name="filePath"></param> public void Uploadphoto(string userName, string filePath) { try { Utils.driver.FindElement(By.LinkText("Home")).Click(); Utils.driver.FindElement(By.XPath("//div[text()='" + userName + "']")).Click(); Actions Action = new Actions(Utils.driver); if (UpdateProfilePic.Count > 0) { Action.MoveToElement(ProfilePicSelector).Click(UpdateProfilePic[0]).Build().Perform(); } else { Action.MoveToElement(ProfilePicSelector).Click(AddProfilePic[0]).Build().Perform(); } UploadPhoto.Click(); System.Threading.Thread.Sleep(3000); SendKeys.SendWait(filePath); SendKeys.SendWait("{Enter}"); ProfilePicSaveButton.Click(); System.Threading.Thread.Sleep(3000); } catch (Exception ex) { ex.ToString(); } }
public RegisterResult RegisterCoach(RegisterCoachViewModel model) { var result = new RegisterResult(); string Msg = string.Empty; bool check = true; Coach User = model.User; if (!ShareService.Instance.CheckFormat(User.Email, @"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$", 50, ref Msg)) { result.Message += $"帳號{Msg}\r"; check = false; } if (!ShareService.Instance.CheckFormat(User.Password, @"^(?=.*[A-Za-z])(?=.*\d)[\w]{4,12}$", 50, ref Msg)) { result.Message += $"密碼{Msg}\r"; check = false; } if (!ShareService.Instance.CheckFormat(User.Phone, @"^[\d]*$", 10, ref Msg)) { result.Message += $"手機{Msg}\r"; check = false; } if (check == false) { result.ReturnNo = -1; return(result); } User.Address = $"{model.addressCity}|{model.addressArea}|{User.Address}"; //註冊 string returnStr = ShareService.Instance.SendApi("Member/CoachRegister", JsonConvert.SerializeObject(User)); result = JsonConvert.DeserializeObject <RegisterResult>(returnStr); //註冊成功 上傳大頭照 if (result.ReturnNo == 1) { if (model.Image != null && model.Image.ContentLength > 0) { //存到資料夾 var FileName = result.MemberId + DateTime.Now.ToString("yyyyMMdd") + ".jpg";; var FilePath = Path.Combine(HttpContext.Current.Server.MapPath("~/CoachImage/"), FileName); model.Image.SaveAs(FilePath); var imagemodel = new UploadPhoto() { MemberId = result.MemberId, ImageName = FileName }; returnStr = ShareService.Instance.SendApi("Member/InsertCoachPhoto", JsonConvert.SerializeObject(imagemodel)); var imageResult = JsonConvert.DeserializeObject <Result>(returnStr); if (imageResult.ReturnNo != 1) { result.ReturnNo = -99; result.Message = "上傳圖片失敗" + imageResult.Message; } } } return(result); }
public async Task CreatePhoto(UploadPhoto photo) { using var image = Image.Load <Rgba32>(photo.Photo); var folder = Path.Combine(UploadImagesFullPath, photo.PhotoId); Directory.CreateDirectory(folder); var path = Path.ChangeExtension(Path.Combine(folder, photo.PhotoId), "png"); await Task.Run(() => image.Save(path)); }
public async Task <IActionResult> UploadPhoto(UploadPhoto photo) { photo.PhotoId = Guid.NewGuid().ToString(); photo.PhotoLocation = Path.Combine(_mediaService.UploadImagesPath, photo.PhotoId, $"{photo.PhotoId}.png"); await _mediaService.CreatePhoto(photo); //await _mediaService.CreateResizedPhoto(photo, 0.1f, "small"); //await _mediaService.CreateResizedPhoto(photo, 0.5f, "medium"); return(Ok(new { photo.PhotoLocation })); }
private bool ImageDataIsValid(UploadPhoto photoData) { if (photoData.Folder.Access >= photoData.Access) { return(true); } else { return(false); } }
public async Task CreateResizedPhoto(UploadPhoto photo, float percent, string addToName) { Directory.CreateDirectory(Path.Combine(UploadImagesFullPath, photo.PhotoId)); var folder = Path.Combine(UploadImagesFullPath, photo.PhotoId); using var image = Image.Load <Rgba32>(photo.Photo); var path = Path.ChangeExtension(Path.Combine(folder, $"{photo.PhotoId}_{addToName}"), "png"); await Task.Run(() => { image.Mutate(x => x.Resize((int)(image.Width * percent), (int)(image.Height * percent))); image.Save(path); }); }
public async Task <IActionResult> UploadPhoto() { if (ModelState.IsValid) { var user = await _userManager.GetUserAsync(User); var model = new UploadPhoto { ProfileImageName = user.ProfileImage }; return(View(model)); } return(View()); }
private void UploadImage(HttpContext context, UploadPhoto photoData, IFormFile uploadedImage) { Picture imageDataForDB = new Picture( photoData.Description, photoData.Access, uploadedImage.ContentType, userGet.GetUser(context), photoData.Folder); Picture savedImageData = pictureRepository.SavePicture(imageDataForDB); string filePath = CreateFilePath(savedImageData, uploadedImage); FileStream stream = new FileStream(filePath, FileMode.Create); uploadedImage.CopyTo(stream); stream.Close(); }
public CreateProfileViewModel() { Date = DateTime.Now; UpdateUser = new Command(async() => { IsBusy = true; var response = await HttpService.PutRequest <ResponseModel <UserModel>, UserModel>("user/update", User); if (response.Code != 200) { Device.BeginInvokeOnMainThread(async() => { await Application.Current.MainPage.DisplayAlert(response.Code.ToString(), ListStringifyer.StringifyList(response.Errors), "OK"); }); IsBusy = false; return; } if (Avatar != null) { UploadPhoto.Execute(null); } else { IsBusy = false; Navigate(); } }); UploadPhoto = new Command(async() => { var file = System.IO.File.ReadAllBytes(Avatar.AlbumPath); var response = await HttpService.UploadFile <ResponseModel <string> >("user/avatar", file); if (response.Code != 200) { Device.BeginInvokeOnMainThread(async() => { await Application.Current.MainPage.DisplayAlert(response.Code.ToString(), ListStringifyer.StringifyList(response.Errors), "OK"); IsBusy = false; return; }); } Navigate(); }); }
protected void btnSubmit_Click(object sned, EventArgs e) { Observation o = new Observation(); string username = context.Employees.Where(x => x.Name == ddlName.Text).Select(x => x.UserName).First(); string HRMS = context.Employees.Where(x => x.UserName == o.Name).Select(x => x.HRMS).First(); try { o.Name = username; o.HRMS = HRMS; o.Date = DateTime.Today.Date; o.Location = ddlLocation.Text; o.Classification = ddlClassification.Text; o.Description = tbxDescription.Text; string fileName = DateTime.Now.ToString("ddMMyyyy-hhmmss") + Path.GetExtension(UploadPhoto.FileName); string photopath = Server.MapPath("~/Pictures/") + fileName; if (UploadPhoto.PostedFile.FileName == "" || UploadPhoto.PostedFile.FileName == null) { photopath = null; o.PhotoPath = null; } else { //string fileName = tbxReportNo.Text + Path.GetExtension(UploadPhoto.FileName); //string photopath = Server.MapPath("~/Pictures/") + fileName; UploadPhoto.SaveAs(photopath); o.PhotoPath = fileName; } o.ImmediateAction = tbxImmAction.Text; o.FurtherAction = tbxFurtherAction.Text; o.PositiveComment = tbxComment.Text; context.Observations.Add(o); context.SaveChanges(); Response.Redirect("~/Admin/ObservationReport.aspx"); } catch (Exception ex) { Response.Write(ex); lblError.Text = "Error! Observation card hasn't been created."; } }
protected void btnSubmit_Click(object sender, EventArgs e) { try { IIdentity id = User.Identity; dynamic profile = ProfileBase.Create(id.Name); string username = id.Name; Report r = new Report(); r.ReportNo = tbxReportNo.Text; r.Date = Convert.ToDateTime(tbxDate.Text); r.Location = ddlLocation.Text; r.Classification = ddlClassification.Text; r.Description = tbxDescription.Text; r.Memo = tbxMemo.Text; //Submitter name value will be added from cookies later r.SubmitterName = username; string fileName = tbxReportNo.Text + Path.GetExtension(UploadPhoto.FileName); string photopath = Server.MapPath("~/Pictures/") + fileName; if (UploadPhoto.PostedFile.FileName == "" || UploadPhoto.PostedFile.FileName == null) { photopath = null; r.PhotoPath = null; } else { //string fileName = tbxReportNo.Text + Path.GetExtension(UploadPhoto.FileName); //string photopath = Server.MapPath("~/Pictures/") + fileName; UploadPhoto.SaveAs(photopath); r.PhotoPath = fileName; } context.Reports.Add(r); context.SaveChanges(); Response.Redirect("~/Admin/ReportList.aspx"); } catch (Exception ex) { Response.Write("Error:" + ex); } }
protected void btnSubmit_Click(object sned, EventArgs e) { IIdentity id = User.Identity; dynamic profile = ProfileBase.Create(id.Name); string username = id.Name; string HRMS = context.Employees.Where(x => x.UserName == username).Select(x => x.HRMS).First(); Observation o = new Observation(); //Take submitter name from cookies o.Name = username; o.HRMS = HRMS; o.Date = DateTime.Today.Date; o.Location = ddlLocation.Text; o.Others = tbxOthers.Text; o.Classification = ddlClassification.Text; o.Description = tbxDescription.Text; string fileName = DateTime.Now.ToString("ddMMyyyy-hhmmss") + Path.GetExtension(UploadPhoto.FileName); string photopath = Server.MapPath("~/Pictures/") + fileName; if (UploadPhoto.PostedFile.FileName == "" || UploadPhoto.PostedFile.FileName == null) { photopath = null; o.PhotoPath = null; } else { //string fileName = tbxReportNo.Text + Path.GetExtension(UploadPhoto.FileName); //string photopath = Server.MapPath("~/Pictures/") + fileName; UploadPhoto.SaveAs(photopath); o.PhotoPath = fileName; } o.ImmediateAction = tbxImmAction.Text; o.FurtherAction = tbxFurtherAction.Text; o.PositiveComment = tbxComment.Text; context.Observations.Add(o); context.SaveChanges(); Response.Redirect("~/Users/ObservationList.aspx"); }
public IActionResult UploadPicture() { IFormFile uploadedImage = HttpContext.Request.Form.Files[0]; Folder folder = folderRepository.GetFolder(userGet.GetUser(HttpContext), HttpContext.Request.Form["FolderName"].ToString()); if (folder == null) { return(BadRequest("Not existing folder!")); } UploadPhoto photoData = new UploadPhoto( HttpContext.Request.Form["Description"].ToString(), HttpContext.Request.Form["Access"].ToString(), folder); if (userGet.HaveUser(HttpContext) && ModelState.IsValid && uploadedImage != null && ImageTypeIsValid(uploadedImage) && ImageDataIsValid(photoData)) { UploadImage(HttpContext, photoData, uploadedImage); return(Ok()); } return(Unauthorized()); }
private void UploadToolStripMenuItem_Click(object sender, EventArgs e) { try { UploadPhoto up; this.openIcoFileDialog.Multiselect = true; this.openIcoFileDialog.Filter = "JPG文件(*.jpg)|*.jpg|JPEG文件(*.jpeg)|*.jpeg|PNG文件(*.png)|*.png|GIF文件(*.gif)|*.gif|BMP文件(*.bmp)|*.bmp|TIFF文件(*.tiff)|*.tiff"; if (this.openIcoFileDialog.ShowDialog() == DialogResult.OK) { string[] files; files = this.openIcoFileDialog.FileNames; up = new UploadPhoto(ds, files); Thread t = new Thread(new ThreadStart(up.uploadPhoto)); t.Start(); } } catch (System.Exception ex) { Console.WriteLine(ex.StackTrace); } }
public JsonResult UploadPhotoAdd(FormDataUpload form) { if (Response.IsClientConnected) { if (form.Photos == null || form.StringId == null) { return(Json(new { success = false })); } var dir = HostingEnvironment.MapPath("~/Photos/" + form.StringId.Substring(2, 4) + "/" + form.StringId.Substring(0, 4)); Directory.CreateDirectory(dir); List <UploadPhoto> phos = new List <UploadPhoto>(); int _curr = form.CurrentPhotoCount; int _max = form.MaxPhotoCount; for (int i = 0; i < form.Photos.Count && form.CurrentPhotoCount <= form.MaxPhotoCount && i < _max - _curr; i++, form.CurrentPhotoCount++) { HttpPostedFileBase photo = form.Photos.ElementAt(i); if (AllowedFileTypes.AllowedFileTypesValidation(photo, "CreateAd")) { var p = new UploadPhoto() { Original_FileName = photo.FileName }; // Compress image for ad list thumbnail PhotoEditing.CompressUploadPhoto(dir, true, false, photo, ref p); // Compress image for ad details thumbnail PhotoEditing.CompressUploadPhoto(dir, false, true, photo, ref p); // Compress imgae PhotoEditing.DefaultCompressionJpegUpload(dir, photo, ref p); // Set display src p.Src = "/Images/" + form.StringId.Substring(2, 4) + "/" + form.StringId.Substring(0, 4) + "/" + p.AdList_FileName; phos.Add(p); } } return(Json(new { success = true, photocount = new { current = form.CurrentPhotoCount }, photos = JsonConvert.SerializeObject(phos) })); } return(Json(new { success = false })); }
public async Task <IActionResult> UploadProfilePhoto(string id, UploadPhoto model) { ViewData["Id"] = id; AppUser user = await userManager.FindByIdAsync(id); if (user != null && model.ProfilePhoto != null) { //Create user directory string dirPath = Path.Combine(hostingEnvironment.WebRootPath, $@"UsersData\{user.Id}"); System.IO.Directory.CreateDirectory(dirPath); string fileName = "profilePhoto.jpeg"; string filePath = Path.Combine(dirPath, fileName); using (var stream = new FileStream(filePath, FileMode.Create)) { model.ProfilePhoto.CopyTo(stream); } //add photo path to AppUser/ProfilePhotoUrl string photoPath = user.Id + @"\profilePhoto.jpeg"; ViewData["msg"] = photoPath; user.UpdatedAt = DateTime.Now; user.ProfilePhotoUrl = photoPath; IdentityResult result = await userManager.UpdateAsync(user); return(RedirectToAction("UserProfile", "User", new { id = user.Id, userId = user.Id })); } else { ModelState.AddModelError("", "No photo"); } return(View(ModelState)); }
public static async Task <bool> MainAsync() { try { Console.WriteLine("Starting demo of InstaSharper project"); // create user session data and provide login details var userSession = new UserSessionData { UserName = "******", Password = "******" }; // create new InstaApi instance using Builder _instaApi = new InstaApiBuilder() .SetUser(userSession) .UseLogger(new DebugFileLogger()) // use logger for requests and debug messages .SetRequestDelay(TimeSpan.FromSeconds(1)) // set delay between requests .Build(); // login Console.WriteLine($"Logging in as {userSession.UserName}"); var logInResult = await _instaApi.LoginAsync(); if (!logInResult.Succeeded) { Console.WriteLine($"Unable to login: {logInResult.Info.Message}"); } else { Console.WriteLine("Press 1 to start basic demo samples"); Console.WriteLine("Press 2 to start upload photo demo sample"); Console.WriteLine("Press 3 to start comment media demo sample"); var key = Console.ReadKey(); Console.WriteLine(Environment.NewLine); switch (key.Key) { case ConsoleKey.D1: var basics = new Basics(_instaApi); await basics.DoShow(); break; case ConsoleKey.D2: var upload = new UploadPhoto(_instaApi); await upload.DoShow(); break; case ConsoleKey.D3: var comment = new CommentMedia(_instaApi); await comment.DoShow(); break; default: break; } Console.WriteLine("Done. Press esc key to exit..."); key = Console.ReadKey(); return(key.Key == ConsoleKey.Escape); } } catch (Exception ex) { Console.WriteLine(ex); } finally { var logoutResult = Task.Run(() => _instaApi.LogoutAsync()).GetAwaiter().GetResult(); if (logoutResult.Succeeded) { Console.WriteLine("Logout succeed"); } } return(false); }
public Result InsertMemberPhoto(UploadPhoto model) { return(member.InsertUserPhoto(model.MemberId, model.ImageName)); }
public Result InsertCoachPhoto(UploadPhoto model) { return(coach.InsertUserPhoto(model.MemberId, model.ImageName)); }
public Result UpdateCoachPhoto(UploadPhoto model) { return(coach.UpdateUserPhoto(model.MemberId, model.ImageName)); }
protected void Submit_Click(object sender, EventArgs e) { string fileName = ""; //Read connection string "DWABookConnectionString" from web.config file. string strConn = ConfigurationManager.ConnectionStrings["ZZFashionCRMConnectionString"].ToString(); //Instatitate a SqlConnection object with the Connection String read. SqlConnection conn = new SqlConnection(strConn); string query = ""; if (UploadPhoto.HasFile) { string fileExtension = Path.GetExtension(UploadPhoto.FileName); SqlCommand command = new SqlCommand("SELECT COUNT(*) FROM Product", conn); conn.Open(); int Id = Convert.ToInt32(command.ExecuteScalar()) + 1; conn.Close(); fileName = Id.ToString() + fileExtension; string FileSavePath = MapPath("~/Images/Product/" + fileName); // Save image in application 'Images' folder UploadPhoto.SaveAs(FileSavePath); query = "INSERT INTO Product (ProductTitle, ProductImage, Price, EffectiveDate) " + "VALUES (@productTitle, @productImage, @price, @effectiveDate)"; } else { query = "INSERT INTO Product (ProductTitle, Price, EffectiveDate) " + "VALUES (@productTitle, @price, @effectiveDate)"; } //Instantiate a SqlCommand object, supply it with SQL statement INSERT //and the connection object for connecting to the database. SqlCommand cmd = new SqlCommand(query, conn); if (UploadPhoto.HasFile) { cmd.Parameters.AddWithValue("@productImage", fileName); } cmd.Parameters.AddWithValue("@productTitle", ProductTitle.Text); cmd.Parameters.AddWithValue("@price", Price.Text); cmd.Parameters.AddWithValue("@effectiveDate", EffectiveDate.SelectedDate); //A connection to database must be opened before any operations made. conn.Open(); //ExecuteNonQuery is used for INSERT, UPDATE, DELETE SQL statement. cmd.ExecuteNonQuery(); //A connection should be closed after operations. conn.Close(); Response.Redirect("~/LoginPages/ProductManager/ViewProduct"); }
protected void Page_Load(object sender, EventArgs e) { string strResult = ""; if (Request["TypeID"] == "ImgePath" && Session["Path"] != null) { strResult = Session["Path"].ToString(); Response.Clear(); Response.ContentType = "text/xml"; Response.Write(strResult); Response.End(); } if (Request["TypeID"] == "Image") { byte[] fileData = null; FileStream fs = new FileStream(Request["strFileName"], FileMode.Open, FileAccess.Read); fileData = new byte[(int)fs.Length]; fs.Read(fileData, 0, (int)fs.Length); Response.ContentType = "image/gif"; Response.BinaryWrite(fileData); Response.End(); fs.Close(); fs = null; return; } if (IsPostBack) { if (UploadPhoto.HasFile) { try { /*------------Added bY Manju on 11-10-2012----------------*/ //if (UploadPhoto.PostedFile.ContentType != "application/pdf") if (UploadPhoto.PostedFile.ContentType == "image/jpeg" || UploadPhoto.PostedFile.ContentType == "image/jpg") { if (UploadPhoto.PostedFile.ContentLength <= (1024 * 20)) { //UploadPhoto.SaveAs(Path.GetTempPath() + UploadPhoto.FileName); UploadPhoto.SaveAs(Path.GetTempPath() + Session.SessionID + UploadPhoto.FileName); } else { ClientScript.RegisterStartupScript(this.GetType(), "yy", "<script>alert('Image size should not be greater than 20kb');</script>"); return; } } else if (UploadPhoto.PostedFile.ContentType == "application/pdf") { if (Request["Flag"] == "D") { //UploadPhoto.SaveAs(Path.GetTempPath() + UploadPhoto.FileName); UploadPhoto.SaveAs(Path.GetTempPath() + Session.SessionID + UploadPhoto.FileName); } } else { ClientScript.RegisterStartupScript(this.GetType(), "yy", "<script>alert('Please Select JPG,JPEG Format Photos Only');</script>"); return; } } catch { } //ClientScript.RegisterStartupScript(this.GetType(), "wclose", "<script>window.returnValue='" + Path.GetTempPath().Replace("\\", "/") + UploadPhoto.FileName.Replace("\\", "-") + '^' + UploadPhoto.PostedFile.ContentLength + "';window.close();</script>"); //ClientScript.RegisterStartupScript(this.GetType(), "wclose", "<script>window.returnValue='" + Path.GetTempPath().Replace("\\", "/") + UploadPhoto.FileName.Replace("\\", "-") + "';window.close();</script>"); //Session["Path"] = Path.GetTempPath().Replace("\\", "/") + UploadPhoto.FileName.Replace("\\", "-"); //Session["Length"] = UploadPhoto.PostedFile.ContentLength; Session["Path"] = Path.GetTempPath().Replace("\\", "/") + Session.SessionID + UploadPhoto.FileName.Replace("\\", "-"); Session["Length"] = UploadPhoto.PostedFile.ContentLength; txtRetValue.Text = Session["Path"].ToString(); System.Web.HttpBrowserCapabilities browser = Request.Browser; //if (hdnValue.Value == "safari") if (browser.Browser == "Chrome") { //ClientScript.RegisterStartupScript(this.GetType(), "wclose", "<script>window.onbeforeunload= function(){ window.opener.document.getElementById('hdnSImagePath').value = document.getElementById('txtRetValue').value;window.opener.ffillImage(); };window.close();</script>"); ClientScript.RegisterStartupScript(this.GetType(), "wclose", "<script>window.onbeforeunload= function(){ window.opener.document.getElementById('hdnImage').value = document.getElementById('txtRetValue').value;window.opener.ffillImage(); };window.close();</script>"); } else { //ClientScript.RegisterStartupScript(this.GetType(), "wclose", "<script>window.returnValue='" + Path.GetTempPath().Replace("\\", "/") + UploadPhoto.FileName.Replace("\\", "-") + "';window.close();</script>"); ClientScript.RegisterStartupScript(this.GetType(), "wclose", "<script>window.returnValue='" + Path.GetTempPath().Replace("\\", "/") + Session.SessionID + UploadPhoto.FileName.Replace("\\", "-") + "';window.close();</script>"); } } else { ClientScript.RegisterStartupScript(this.GetType(), "wclose", "<script>window.returnValue='';window.close();</script>"); } //ClientScript.RegisterStartupScript(this.GetType(), "wclose", "<script>window.returnValue='" + UploadPhoto.PostedFile.FileName.Replace("\\", "/") + "';window.close();</script>"); return; } }
protected void Update_Click(object sender, EventArgs e) { string fileName = ""; //Read connection string "DWABookConnectionString" from web.config file. string strConn = ConfigurationManager.ConnectionStrings["ZZFashionCRMConnectionString"].ToString(); //Instatitate a SqlConnection object with the Connection String read. SqlConnection conn = new SqlConnection(strConn); string query = ""; if (UploadPhoto.HasFile) { string fileExtension = Path.GetExtension(UploadPhoto.FileName); fileName = ProductId.ToString() + fileExtension; string FileSavePath = MapPath("~/Images/Product/" + fileName); if (File.Exists(FileSavePath)) { File.Delete(FileSavePath); } // Save image in application 'Images' folder UploadPhoto.SaveAs(FileSavePath); query = "UPDATE Product SET ProductTitle=@title, ProductImage=@image, Price=@price, EffectiveDate=@date, Obsolete=@obsolete WHERE ProductID = " + ProductId; } else { query = "UPDATE Product SET ProductTitle=@title, Price=@price, EffectiveDate=@date, Obsolete=@obsolete WHERE ProductID = " + ProductId; } //Instantiate a SqlCommand object, supply it with SQL statement INSERT //and the connection object for connecting to the database. SqlCommand cmd = new SqlCommand(query, conn); if (UploadPhoto.HasFile) { cmd.Parameters.AddWithValue("@image", fileName); } cmd.Parameters.AddWithValue("@title", ProductTitle.Text.ToString()); cmd.Parameters.AddWithValue("@price", Price.Text.ToString()); cmd.Parameters.AddWithValue("@date", EffectiveDate.SelectedDate); if (ObsoleteOne.Checked) { cmd.Parameters.AddWithValue("@obsolete", 1); } else { cmd.Parameters.AddWithValue("@obsolete", 0); } //A connection to database must be opened before any operations made. conn.Open(); //ExecuteNonQuery is used for INSERT, UPDATE, DELETE SQL statement. cmd.ExecuteNonQuery(); //A connection should be closed after operations. conn.Close(); Response.Redirect("~/LoginPages/ProductManager/ViewProduct"); }