public async Task <IActionResult> EditProfilePic(ImgUpload newImg)
        {
            try
            {
                string apiResponse = "";
                using (var httpClient = new HttpClient())
                {
                    var formData = new MultipartFormDataContent();
                    using (var filestream = newImg.Img.OpenReadStream())
                    {
                        formData.Add(new StringContent(newImg.Id.ToString()), "Id");
                        formData.Add(new StreamContent(filestream), "Img", newImg.Img.FileName);
                        using (var response = await httpClient.PostAsync(httpServer + "/Members/img", formData))
                        {
                            apiResponse = await response.Content.ReadAsStringAsync();

                            log.Info("Medlems profilbild uppdaterad Status: " + response.StatusCode);
                        }
                    }
                }
                return(RedirectToAction("Index"));
            }

            catch (Exception)
            {
                TempData["Result"] = "Det gick inte uppdatera profilbilden";
                return(RedirectToAction("Index"));
            }
        }
예제 #2
0
        public ActionResult Delete(int id)
        {
            POST PostDelete = postsModels.GetItem(id);

            if (Check.checkPostDelete(PostDelete))
            {
                string pictureOld = PostDelete.PICTURE;
                if (postsModels.DeleteItem(id) > 0)
                {
                    var       dataFile  = Server.MapPath("~/Assets/Upload/Post/" + pictureOld);
                    ImgUpload imgUpload = new ImgUpload();
                    imgUpload.Delete(dataFile);
                    Session["mes"] = "Xóa thành công!!!";
                }
                else
                {
                    Session["mes_er"] = "Xóa thất bại";
                }
            }
            else
            {
                Session["mes_er"] = "Xóa thất bại! không đủ quyền";
            }
            return(RedirectToAction("Index", "PostManager"));
        }
        public async Task <IActionResult> EditProfilePic(int id)
        {
            try
            {
                Member member = new Member();
                using (var httpClient = new HttpClient())
                {
                    using (var response = await httpClient.GetAsync(httpServer + "/Members/" + id))
                    {
                        string apiResponse = await response.Content.ReadAsStringAsync();

                        member = JsonConvert.DeserializeObject <Member>(apiResponse);
                    }
                }
                ViewBag.Name = member.FirstName;
                ImgUpload imgUpload = new ImgUpload();

                imgUpload.Id = id;
                return(View(imgUpload));
            }
            catch
            {
                TempData["Result"] = "Det gick inte uppdatera profilbilden";
                return(RedirectToAction("Index"));
            }
        }
예제 #4
0
        public async Task RemoveImg(ClaimsPrincipal claimsPrincipal, ImgUpload img)
        {
            RemoveImg(img);
            await _context.SaveChangesAsync();

            if (claimsPrincipal.IsInRole("Admin"))
            {
                var user = await _userManager.GetUserAsync(claimsPrincipal);

                if (img.UserId == user.Id)
                {
                    return;
                }
                var subject = "[Cmagru][ImgRemoved][no-reply] Img removed by admin";
                var body    = "The <b>Admin</b> has just removed one of your images.";
                if (user.EmailConfirmed)
                {
                    body += "<br /> You can contact the admin on the following email: " + user.Email;
                }

                UserUtils.SendEmailNotif(
                    _context,
                    _emailService,
                    img.UserId,
                    subject,
                    body
                    );
            }
        }
예제 #5
0
        public ActionResult Upload(ImageUploadViewModel formData)
        {
            //Get File and Create Path
            var    uploadedFile = Request.Files[0];
            string filename     = $"{DateTime.Now.Ticks}{uploadedFile.FileName}";
            var    serverPath   = Server.MapPath(@"~\Uploads");
            var    fullPath     = Path.Combine(serverPath, filename);

            //Resize Image
            //WebImage img = new WebImage(uploadedFile.InputStream);
            //if (img.Width > 1000)
            //    img.Resize(1000, 1000);

            //Save Image
            uploadedFile.SaveAs(fullPath);

            //Create ImgUpload Entry
            var uploadModel = new ImgUpload
            {
                Caption = formData.Caption,
                File    = filename,
                OwnerId = User.Identity.GetUserId(),
                TypeRef = "ProfilePic",
            };

            db.ImgUploads.Add(uploadModel);
            db.SaveChanges();

            return(Redirect("Index"));
        }
예제 #6
0
 public ActionResult Regis(USER User, HttpPostedFileBase Picture)
 {
     if (ModelState.IsValid || User.PASSWORD != null || !User.PASSWORD.Equals(""))
     {
         if (userModels.CheckEmail(User.EMAIL))
         {
             //upload file
             if (Picture != null && Picture.ContentLength > 0)
             {
                 var       path      = Server.MapPath("~/Assets/Upload/User/");
                 ImgUpload imgUpload = new ImgUpload();
                 User.PICTURE = imgUpload.Upload(Picture, path);
             }
             User.ACTIVE  = false;
             User.ID_ROLE = roleModels.GetItemName(ConstanAppkey.USER()).ID;
             if (userModels.AddItem(User) > 0)
             {
                 Session["mes_su"] = "Đăng ký thành công. chờ xét duyệt";
                 return(RedirectToAction("Index", "Login"));
             }
             else
             {
                 Session["mes_er"] = "Đăng ký thất bại, thử lại!";
                 return(RedirectToAction("Regis", "Login"));
             }
         }
         else
         {
             Session["mes_er"] = "Email đã đăng ký!!!";
         }
     }
     return(RedirectToAction("Regis", "Login"));
 }
예제 #7
0
        public ActionResult Delete(int id)
        {
            USER User = userModels.GetItem(id);

            if (Check.checkUserAdd(User))
            {
                string picture = User.PICTURE;
                int    i       = userModels.Delete(id);
                if (i > 0)
                {
                    var       dataFile  = Server.MapPath("~/Assets/Upload/User/" + picture);
                    ImgUpload imgUpload = new ImgUpload();
                    imgUpload.Delete(dataFile);
                    Session["mes"] = "Xóa thành công";
                }
                else if (i == -1)
                {
                    Session["mes_er"] = "Xóa bình luận của người này trước";
                }
                else
                {
                    Session["mes_er"] = "Xóa thất bại";
                }
            }
            else
            {
                Session["mes_er"] = "Xóa thất bại! không đủ quyền";
            }
            return(RedirectToAction("Index", "UserManager"));
        }
예제 #8
0
        public async Task <IActionResult> UploadImage(ImgUpload model)
        {
            dynamic imgName = await _image.UploadImage(model.File);

            return(Ok(await _employeeService.UpdateImg(new Employee {
                Id = model.Id, Avatar = imgName.Value
            })));
        }
        public ActionResult Index(USER UserSubmit, FormCollection form, HttpPostedFileBase Picture)
        {
            CustomPrincipal prin = (CustomPrincipal)User;

            UserSubmit.ACTIVE = prin.ACTIVE;
            if (ModelState.IsValid)
            {
                if (userModels.CheckEmailEdit(UserSubmit.EMAIL, prin.ID))
                {
                    USER user1 = userModels.GetItem(prin.ID);
                    //upload file
                    string picture_new = "";
                    string picture_old = "";
                    if (Picture != null && Picture.ContentLength > 0)
                    {
                        // create new file
                        ImgUpload imgUpload = new ImgUpload();
                        var       path      = Server.MapPath("~/Assets/Upload/User/");
                        UserSubmit.PICTURE = imgUpload.Upload(Picture, path);
                        picture_new        = UserSubmit.PICTURE;
                        picture_old        = user1.PICTURE;
                    }
                    else
                    {
                        UserSubmit.PICTURE = user1.PICTURE;
                    }
                    UserSubmit.ID_ROLE = user1.ID_ROLE;
                    if (userModels.EditItem(prin.ID, UserSubmit) > 0)
                    {
                        if (!picture_old.Equals(""))
                        {
                            // delete file old
                            var       dataFile  = Server.MapPath("~/Assets/Upload/User/" + picture_old);
                            ImgUpload imgUpload = new ImgUpload();
                            imgUpload.Delete(dataFile);
                        }
                        Session["mes"] = "Sửa thành công";
                    }
                    else
                    {
                        if (!picture_new.Equals(""))
                        {
                            // delete file old
                            var       dataFile  = Server.MapPath("~/Assets/Upload/User/" + picture_new);
                            ImgUpload imgUpload = new ImgUpload();
                            imgUpload.Delete(dataFile);
                        }
                        Session["mes_er"] = "Sửa thất bại";
                    }
                }
                else
                {
                    Session["mes_er"] = "Email đã tồn tại";
                }
            }
            return(RedirectToAction("Index", "ProfileManager"));
        }
예제 #10
0
    protected void btnLocation_Click(object sender, EventArgs e)
    {
        try
        {
            /*Create location object and assign values from controls, we will use this object to pass values from one layer to other.*/
            LocationInfo locationInfo = new LocationInfo();
            locationInfo.LocationName = txtLocatioName.Text.Trim();
            locationInfo.Description  = txtDescription.Text.Trim();

            /*Creating dataaccess object to insert/update the assigned data.*/
            Location location = new Location();

            if (SessionManager.LocationInfo == null) /* this operation is to save new location*/
            {
                FileInfo file = new FileInfo(ImgUpload.FileName);
                string   ext  = file.Extension.ToLower();
                if (ext != ".jpg" && ext != ".jpeg" && ext != ".gif" && ext != ".tif" && ext != ".bmp" && ext != ".png") /*Checking file extension*/
                {
                    lblMessage.Text = "Uploaded file is not a valid image. supported formats (jpg, jpeg, gif, tif, bmp, png)";
                    return;
                }
                else if (ImgUpload.FileContent.Length > 2.5 * 1024 * 1024)/*Checking uploaded file size.*/
                {
                    lblMessage.Text = "File size should not exceed 2.5 MB.";
                    return;
                }
                else
                {
                    /*Saving file to server physical path.*/
                    string imgLoc = "~/LocationImages/" + Guid.NewGuid().ToString() + ImgUpload.FileName;
                    locationInfo.LocationUrl = imgLoc;
                    ImgUpload.SaveAs(MapPath(imgLoc));
                    location.InsertLocation(locationInfo);
                }
            }
            else/*this operation is to update existing location*/
            {
                /*Before updating the data, assigning the LocationId and LocationUrl to newly created locationInfo Object*/
                locationInfo.LocationId  = SessionManager.LocationInfo.LocationId;
                locationInfo.LocationUrl = SessionManager.LocationInfo.LocationUrl;
                location.UpdateLocation(locationInfo);

                /*Making session null*/
                SessionManager.LocationInfo = null;

                trImage.Visible = false;
                RequiredFieldValidator3.Enabled = true;
                ImgUpload.Visible = true;
            }
            ClearControls();
            lblMessage.Text = "Location saved successfully.";
        }
        catch (Exception ex)
        {
            lblMessage.Text = "Unable to save Location.";
        }
    }
예제 #11
0
    private void InsertData()
    {
        //get IP
        string ipaddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

        if (ipaddress == "" || ipaddress == null)
        {
            ipaddress = Request.ServerVariables["REMOTE_ADDR"];
        }
        // Get Data by IP
        string       APIKey   = "0b125cbd194ae7f525cb15d5a10832c2dad87e17441dc89b4b61a291d28fcef8";
        string       url      = string.Format("http://api.ipinfodb.com/v3/ip-city/?key={0}&ip={1}&format=json", APIKey, ipaddress);
        WebClient    client   = new WebClient();
        string       json     = client.DownloadString(url);
        Registration location = new JavaScriptSerializer().Deserialize <Registration>(json);

        //Detected Device type
        HttpBrowserCapabilities brows = Request.Browser;

        if (brows.IsMobileDevice)
        {
            DevicesType = "Smart Mobile Device";
        }
        else
        {
            DevicesType = "Desktop Device";
        }

        //encrypt password MD5
        string EncryptionPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(txtpassword.Text.Trim(), "MD5");

        // Database
        SqlConnection con = new SqlConnection(conString);
        SqlCommand    cmd = new SqlCommand("Insert into UsersData (Name,Username, Email, Password,Age,Avater,Ip_Address,CountryName,CityName,RegionName,CountryCode,ZipCode,TimeZone,Machein,TimeDate) values('" + txtname.Text.Trim() + "','" + txtuname.Text.Trim() + "', '" + txtemail.Text.Trim() + "', '" + EncryptionPassword + "','" + txtAge.Text.Trim() + "','" + "~/Avater/" + ImgUpload.FileName.Trim() + "','" + location.IPAddress + "','" + location.CountryName + "','" + location.CityName + "','" + location.RegionName + "','" + location.CountryCode + "','" + location.ZipCode + "','" + location.TimeZone + "','" + DevicesType + "','" + DateTime.UtcNow.ToString("dd/MM/yyyy hh:mm:ss tt") + "')", con);

        ImgUpload.SaveAs(Server.MapPath("~/Avater/" + Path.GetFileName(ImgUpload.FileName)));
        con.Open();

        bool Status = Convert.ToBoolean(cmd.ExecuteNonQuery());

        con.Close();

        if (Status)     //?
        {
            cmd = new SqlCommand("update UsersData set Status = 1 where Username = @Username", con);
            cmd.Parameters.AddWithValue("@Username", txtuname.Text); //Server.HtmlEncode()
            con.Open();
            cmd.ExecuteNonQuery();
            Response.Redirect("Chat.aspx");   //yes go online
            con.Close();
        }
        else
        {
            LabelSignup.Text = "An unexpected problem occurred";
        }
    }
예제 #12
0
        // Gets the image path
        private string UploadImage()
        {
            // gets path of image
            string imgPath = string.Format("../NewsImages/{0}", ImgUpload.FileName);

            // saves to folder folder
            ImgUpload.SaveAs(Server.MapPath(imgPath));

            return(imgPath);
        }
예제 #13
0
        public async Task <ActionResult <object> > PostImg()
        {
            string root = "pcx/";

            if (!Directory.Exists(root))
            {
                Directory.CreateDirectory(root);
            }
            PCXcontainer containerTemp = new PCXcontainer();

            containerTemp.IPaddress = Request.HttpContext.Connection.RemoteIpAddress.ToString();
            ImgUpload temp = new ImgUpload();

            Request.Headers["filename"] = Regex.Replace(Request.Headers["filename"], "[^a-zA-Z0-9% ._]", string.Empty);
            containerTemp.filename      = Request.Headers["filename"] + ".pcx";
            containerTemp.originalImg   = root + DateTime.Now.ToString("dd-MM-yyyy-hh_mm-ss-ffff") + "_" + Request.Headers["filename"] + ".pcx";
            temp.FileName = containerTemp.filename;
            using (var fs = new FileStream("wwwroot/" + containerTemp.originalImg, FileMode.Create))
            {
                Request.Body.CopyTo(fs);
            }

            try
            {
                var      extension       = ImageExtensions.GetImageFormat(Request.Headers["extension"]);
                var      stringExtension = Request.Headers["extension"];
                PCXImage image           = new PCXImage("wwwroot/" + containerTemp.originalImg);
                containerTemp.version = image.FileVersion;
                Bitmap convertedImage = new Bitmap(image.Image);
                image.Dispose();

                using (var bitmap = new Bitmap(convertedImage))
                {
                    string filename = root + DateTime.Now.ToString("dd-MM-yyyy-hh-mm-ss-ffff") + "_" + Request.Headers["filename"] + stringExtension;
                    bitmap.Save("wwwroot/" + filename, extension);
                    containerTemp.convertedImg = filename;
                }
                containerTemp.dateTime       = DateTime.Now;
                containerTemp.downloadFormat = stringExtension;
                containerTemp.height         = convertedImage.Height;
                containerTemp.width          = convertedImage.Width;
                convertedImage.Dispose();
                _context.PCXcontainers.RemoveRange(_context.PCXcontainers.OrderBy(x => x.dateTime).Take(_context.PCXcontainers.Count() - 4));
                _context.PCXcontainers.Add(containerTemp);
                await _context.SaveChangesAsync();

                temp.id = _context.PCXcontainers.Last().id;
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e.Message);
                return(NotFound());
            }
            return(temp);
        }
예제 #14
0
        public async Task <IActionResult> Create(SingleTourViewModel model, List <IFormFile> sources)
        {
            ViewData["Guides"] = await userManager.GetUsersInRoleAsync("beledci");


            if (ModelState.IsValid)
            {
                if (model.Requirement == null || model.Guides.Count == 0)
                {
                    return(View());
                }

                if (model.singleTour.StartDate >= model.singleTour.EndDate)
                {
                    ModelState.AddModelError("timeCheck", "Seyahetin Bitme tarixi baslangis tarixinden once ola bilmez");
                    return(View());
                }
                _context.Add(model.singleTour);
                await _context.SaveChangesAsync();

                //Images of Place
                foreach (var item in sources)
                {
                    var res = await ImgUpload.SaveImage(Path.Combine(hostingEnvironment.WebRootPath, "img", "tours"), item);

                    var img = new AllImage();
                    img.Source = res;
                    _context.Images.Add(img);
                    await _context.SaveChangesAsync();

                    var tourImg = new OneTourImage();
                    tourImg.AllImageId   = img.Id;
                    tourImg.SingleTourId = model.singleTour.Id;
                    tourImg.IsIntro      = true;
                    _context.OneTourImages.Add(tourImg);
                }
                //Requirements
                ReqSeperator(model.singleTour, model.Requirement);
                //Guides for Tour
                foreach (var guide in model.Guides)
                {
                    var TourGuides = new GuideToTourPvt();
                    TourGuides.TourId  = model.singleTour.Id;
                    TourGuides.GuideId = guide;
                    _context.GuideToTourPvts.Add(TourGuides);
                }
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["TourTypeId"] = new SelectList(_context.TourTypes, "Id", "Name", model.singleTour.TourTypeId);

            return(View());
        }
예제 #15
0
        protected void Submit_btn_Click(object sender, EventArgs e)
        {
            byte[] imgarr = null;
            String query;

            //get image
            if (ImgUpload.HasFile)
            {
                String path = Server.MapPath(Path.GetFileName(ImgUpload.FileName));
                ImgUpload.SaveAs(path);
                imgarr = UrlToByteArr(path);
            }
            //set query
            if ((bool)Session["isEdit"])
            {
                if (imgarr != null)
                {
                    query = "UPDATE Employees SET Emp_name=?, Jobtitle=?, Startdate=?, Picblob=? WHERE ID=?;";
                }
                else
                {
                    query = "UPDATE Employees SET Emp_name=?, Jobtitle=?, Startdate=? WHERE ID=?;";
                }
            }
            else
            {
                query = "INSERT INTO Employees(Emp_name,Jobtitle,Startdate,Picblob) VALUES(?,?,?,?);";
            }
            //execute sql
            dbconn.Open();
            OdbcTransaction dbtrans = dbconn.BeginTransaction();
            OdbcCommand     dbcmd   = new OdbcCommand(query, dbconn, dbtrans);

            dbcmd.Parameters.Add("Emp_name", OdbcType.VarChar).Value  = Name_txt.Text;
            dbcmd.Parameters.Add("Jobtitle", OdbcType.VarChar).Value  = Title_txt.Text;
            dbcmd.Parameters.Add("Startdate", OdbcType.VarChar).Value = Startdate_txt.Text;
            if (imgarr != null)//if user gives a new image
            {
                dbcmd.Parameters.Add("Picblob", OdbcType.VarBinary).Value = imgarr;
            }
            if ((bool)Session["isEdit"])//if editing an entry
            {
                dbcmd.Parameters.Add("ID", OdbcType.Int).Value = Int32.Parse(id);
            }
            dbcmd.ExecuteNonQuery();
            //commit and end transaction
            dbtrans.Commit();
            dbconn.Close();
            //reset edit session state
            Session["isEdit"] = false;
            Response.Redirect("EmployeeTable.aspx");
        }
예제 #16
0
        private async Task UplodImgAsync(byte[] imgBytes, ApplicationUser user)
        {
            var imgUpload = new ImgUpload()
            {
                RawImg     = imgBytes,
                UserId     = user.Id,
                UploadTime = DateTime.Now
            };

            var result = await _context.ImgUploads.AddAsync(imgUpload);

            await _context.SaveChangesAsync();
        }
예제 #17
0
        public ActionResult Upload(ImageUploadViewModel formData, int?id)
        {
            //Get File and Create Path
            var    uploadedFile = Request.Files[0];
            string filename     = $"{DateTime.Now.Ticks}{uploadedFile.FileName}";
            var    serverPath   = Server.MapPath(@"~\Uploads");
            var    fullPath     = Path.Combine(serverPath, filename);

            //Resize Image
            //WebImage img = new WebImage(uploadedFile.InputStream);
            //if (img.Width > 1000)
            //    img.Resize(1000, 1000);

            //Save Image
            uploadedFile.SaveAs(fullPath);

            var userId = User.Identity.GetUserId();
            int qId    = 0;

            //Get Question Id if not provided
            if (id == null)
            {
                qId = db.Questions
                      .Where(q => q.OwnerId == userId)
                      .OrderByDescending(q => q.Created)
                      .Select(q => q.Id)
                      .FirstOrDefault();
            }
            else
            {
                qId = (int)id;
            }

            //Create ImgUpload Entry
            var uploadModel = new ImgUpload
            {
                Caption = formData.Caption,
                File    = filename,
                OwnerId = User.Identity.GetUserId(),
                RefId   = qId,
                TypeRef = "QAttach",
            };

            db.ImgUploads.Add(uploadModel);
            db.SaveChanges();

            return(RedirectToAction("Index"));
        }
예제 #18
0
        public ActionResult Add(POST Post, FormCollection form, HttpPostedFileBase PICTURE)
        {
            CustomPrincipal prin = (CustomPrincipal)User;

            if (ModelState.IsValid)
            {
                //upload file
                if (PICTURE != null && PICTURE.ContentLength > 0)
                {
                    var       path      = Server.MapPath("~/Assets/Upload/Post/");
                    ImgUpload imgUpload = new ImgUpload();
                    Post.PICTURE = imgUpload.Upload(PICTURE, path);
                }
                if (prin.ROLE.Equals(ConstanAppkey.ADMIN()))
                {
                    if (this.Request.Form["ACTIVE"] != null)
                    {
                        Post.ACTIVE = true;
                    }
                    else
                    {
                        Post.ACTIVE = false;
                    }
                }
                else
                {
                    Post.ACTIVE = false;
                }
                Post.ID_USER = prin.ID;
                int idPosst = postsModels.AddItem(Post);
                if (idPosst > 0)
                {
                    Session["mes"] = "Thêm thành công";
                }
                else
                {
                    var       dataFile  = Server.MapPath("~/Assets/Upload/Post/" + Post.PICTURE);
                    ImgUpload imgUpload = new ImgUpload();
                    imgUpload.Delete(dataFile);
                    Session["mes_er"] = "Thêm thất bại";
                }
                return(RedirectToAction("Index", "PostManager"));
            }

            ViewBag.ListCategories = categoriesModels.GetAllItem();
            return(View(Post));
        }
예제 #19
0
        protected string UploadFile()
        {
            string folderPath = Server.MapPath("~/imgs/");

            //Check whether Directory (Folder) exists.
            if (!Directory.Exists(folderPath))
            {
                //If Directory (Folder) does not exists Create it.
                Directory.CreateDirectory(folderPath);
            }

            //Save the File to the Directory (Folder).
            ImgUpload.SaveAs(folderPath + Path.GetFileName(ImgUpload.FileName));

            //Display the Picture in Image control.
            return("~/imgs/" + Path.GetFileName(ImgUpload.FileName));
        }
예제 #20
0
        public async Task <IActionResult> DeleteConfirmed(int id)
        {
            var singleTour = await _context.SingleTours.FindAsync(id);

            List <int> imgIdList  = new List <int>();
            var        imgoftours = _context.OneTourImages.Where(p => p.SingleTourId == id);

            foreach (var item in imgoftours)
            {
                if (!imgIdList.Exists(p => p == item.AllImageId))
                {
                    imgIdList.Add(item.AllImageId);
                }

                _context.OneTourImages.Remove(item);
            }
            foreach (var imgId in imgIdList)
            {
                var delImg = ImgUpload.DeleteImage(Path.Combine(hostingEnvironment.WebRootPath, "img", "tours"), _context.Images.Find(imgId).Source);

                if (delImg)
                {
                    _context.Images.Remove(_context.Images.Find(imgId));
                }
            }

            var guideoftours = _context.GuideToTourPvts.Where(p => p.TourId == id);

            foreach (var item in guideoftours)
            {
                _context.GuideToTourPvts.Remove(item);
            }

            var reqsoftours = _context.Requirements.Where(p => p.SingleTourId == id);

            foreach (var item in reqsoftours)
            {
                _context.Requirements.Remove(item);
            }
            _context.SingleTours.Remove(singleTour);
            await _context.SaveChangesAsync();

            return(RedirectToAction(nameof(Index)));
        }
예제 #21
0
 public ActionResult Add(USER UserR, FormCollection form, HttpPostedFileBase Picture)
 {
     if (Check.checkUserAdd(UserR))
     {
         if (ModelState.IsValid || UserR.PASSWORD != null || !UserR.PASSWORD.Equals(""))
         {
             if (userModels.CheckEmail(UserR.EMAIL))
             {
                 //upload file
                 if (Picture != null && Picture.ContentLength > 0)
                 {
                     var       path      = Server.MapPath("~/Assets/Upload/User/");
                     ImgUpload imgUpload = new ImgUpload();
                     UserR.PICTURE = imgUpload.Upload(Picture, path);
                 }
                 if (this.Request.Form["ACTIVE"] != null)
                 {
                     UserR.ACTIVE = true;
                 }
                 else
                 {
                     UserR.ACTIVE = false;
                 }
                 if (userModels.AddItem(UserR) > 0)
                 {
                     Session["mes"] = "Thêm thành công!!!";
                 }
                 else
                 {
                     Session["mes_er"] = "Thêm thất bại!!!";
                 }
                 return(RedirectToAction("Index", "UserManager"));
             }
             else
             {
                 Session["mes_er"] = "Email đã đăng ký!!!";
             }
         }
     }
     ViewBag.ListRole = roleModels.GetAllItems();
     return(View(UserR));
 }
        public ImgUpload PostImg([FromForm] ImgUpload img)
        {
            string WebbSiteUrl = "http://193.10.202.72/membersAPI/uploads/";

            try
            {
                string path     = _enviroment.WebRootPath + "\\uploads\\";
                string fileName = img.Img.FileName.ToLower();
                //Kontrollera så filen inte är större än 5mb och att filen är en bild
                if (img.Img.Length > 0 && img.Img.Length < 5000000 && (fileName.Contains("jpg") || fileName.Contains("png")))
                {
                    Member setImg = _context.Members.Where(m => m.Id == img.Id).FirstOrDefault();
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    using (FileStream fileStream = System.IO.File.Create(path + img.Img.FileName))
                    {
                        if (setImg != null)
                        {
                            var member = _context.Members.Find(img.Id);
                            member.ProfilePicture = WebbSiteUrl + img.Img.FileName;
                            _context.SaveChanges();
                        }
                        img.Img.CopyTo(fileStream);
                        fileStream.Flush();
                        return(img);
                    }
                }
                else
                {
                    log.Error("Medlemmen " + img.Id + "misslyckade ladda upp bild");
                    return(null);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
예제 #23
0
        public IHttpActionResult ImgUpload([FromBody] ImgUpload model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            try
            {
                File.WriteAllBytes(HostingEnvironment.MapPath($"ProfileUsersImages/{model.Base64imgName}"),
                                   Convert.FromBase64String(model.Base64img));

                BAL.ImgUpload(model.Base64imgName, int.Parse(model.UserID));

                return(Ok("ok"));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            return(BadRequest());
        }
예제 #24
0
 private void RemoveImg(ImgUpload img)
 {
     _context.ImgUploads.Remove(img);
     _context.Comments.RemoveRange(_context.Comments.Where(c => c.ContentId == img.Id));
     _context.Likes.RemoveRange(_context.Likes.Where(l => l.ContentId == img.Id));
 }
예제 #25
0
        public async Task <IActionResult> Edit(int id, TourViewModel model, string requirement, IFormFile[] sources)
        {
            if (id != model.Tour.Id)
            {
                return(NotFound());
            }

            if (!ModelState.IsValid)
            {
                return(View(model.Tour));
            }


            model.Tour.Requirements = _context.Requirements.Where(p => p.SingleTourId == model.Tour.Id).ToList();
            if (sources.Length != 0)
            {
                for (int i = 0; i < sources.Length; i++)
                {
                    var res = await ImgUpload.SaveImage(Path.Combine(hostingEnvironment.WebRootPath, "img", "tours"), sources[i]);

                    var img = new AllImage();
                    img.Source = res;
                    _context.Images.Add(img);
                    await _context.SaveChangesAsync();

                    var tourImg = new OneTourImage();
                    tourImg.AllImageId   = img.Id;
                    tourImg.SingleTourId = model.Tour.Id;
                    tourImg.IsIntro      = true;
                    _context.OneTourImages.Add(tourImg);
                }
            }

            if (model.Photos != null)
            {
                foreach (var item in model.Photos)
                {
                    if (!item.Selected)
                    {
                        continue;
                    }
                    var delImg = ImgUpload.DeleteImage(Path.Combine(hostingEnvironment.WebRootPath, "img", "tours"), item.Source);
                    if (delImg)
                    {
                        _context.OneTourImages.Remove(_context.OneTourImages.FirstOrDefault(p => p.AllImageId == item.Id));
                        _context.Images.Remove(_context.Images.FirstOrDefault(p => p.Id == item.Id));
                    }
                }
            }

            try
            {
                _context.Update(model.Tour);
                foreach (var item in model.Requirements)
                {
                    if (!item.Selected)
                    {
                        continue;
                    }
                    _context.Requirements.Remove(_context.Requirements.First(p => p.Id == item.Id));
                }


                if (requirement != null)
                {
                    ReqSeperator(model.Tour, requirement);
                }
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!SingleTourExists(model.Tour.Id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }
            ViewData["TourTypeId"] = new SelectList(_context.TourTypes, "Id", "Name", model.Tour.TourTypeId);
            return(RedirectToAction(nameof(Index)));
        }
예제 #26
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            WebClient client = new WebClient();

            client.Headers["Content-type"] = "application/json";
            client.Encoding = Encoding.UTF8;
            if (Request.QueryString["status"] == "update")
            {
                ViewState["UserID"] = Request.QueryString["mId"];

                string apiUrlUser = Utilities.BASE_URL + "/api/Users";
                if (Session["SystemRole"].ToString() == "1")
                {
                    Committee.Models.User memberManger = new Models.User()
                    {
                        ID                  = Convert.ToInt32(Request.QueryString["mId"]),
                        Name                = txtMemberName.Text,
                        UserEmailId         = txtMemberEmail.Text,
                        Phone               = txtPhoneNumber.Text,
                        Title               = txtMemberJob.Text,
                        SecrtaryOfDept      = ddlmangerForDept?.SelectedItem?.Value,
                        WorkSide            = txtWorkSide.Text,
                        SystemRole          = Convert.ToInt32(ddlMemberType?.SelectedItem?.Value),
                        UserName            = txtuserNameOfManager.Text,
                        UserPassword        = Encryptor.MD5Hash(txtPasswordOfManager.Text),
                        Address             = txtAddress.Text,
                        UserImage           = "/" + ImgUpload?.PostedFile?.FileName,
                        ManagerOfDepartment = ddlmangerForDept?.SelectedItem?.Value
                    };

                    if (string.IsNullOrEmpty(txtuserNameOfManager.Text))
                    {
                        memberManger.UserName = memberManger.Name;
                    }
                    else
                    {
                        memberManger.UserName = txtuserNameOfManager.Text;
                    }
                    if (ViewState["Phone"].ToString() == txtPhoneNumber.Text.Trim().ToLower())
                    {
                        memberManger.Phone = txtPhoneNumber.Text.Trim().ToLower();
                        if (ImgUpload.PostedFile != null && ImgUpload.PostedFile.ContentLength > 0)
                        {
                            string fname = Path.GetFileName(ImgUpload.PostedFile.FileName);
                            ImgUpload.SaveAs(Server.MapPath(Path.Combine("~/MasterPage/Uploads/", fname)));
                            ImgUser.ImageUrl = "~/MasterPage/Uploads/" + fname;

                            memberManger.UserImage = "/" + fname;
                        }
                        else
                        {
                            memberManger.UserImage = ImgUser.ImageUrl.Replace("~/MasterPage/Uploads/", "");
                        }


                        string inputJson = (new JavaScriptSerializer()).Serialize(memberManger);
                        client.UploadString(apiUrlUser + "/PutUser?id=" + Convert.ToInt32(ViewState["UserID"]), inputJson);
                        Response.Redirect("MemberMangement.aspx?id=redirectUpdate");
                    }
                    else
                    {
                        bool phoneExist = WebApiConsume.ValidateUserPhone(txtPhoneNumber.Text.Trim().ToLower());
                        if (!phoneExist)
                        {
                            memberManger.Phone = txtPhoneNumber.Text.Trim().ToLower();
                            if (ImgUpload.PostedFile != null && ImgUpload.PostedFile.ContentLength > 0)
                            {
                                string fname = Path.GetFileName(ImgUpload.PostedFile.FileName);
                                ImgUpload.SaveAs(Server.MapPath(Path.Combine("~/MasterPage/Uploads/", fname)));
                                ImgUser.ImageUrl = "~/MasterPage/Uploads/" + fname;

                                memberManger.UserImage = "/" + fname;
                            }
                            else
                            {
                                memberManger.UserImage = ImgUser.ImageUrl;
                            }
                            string inputJson = (new JavaScriptSerializer()).Serialize(memberManger);

                            client.UploadString(apiUrlUser + "/PutUser?id=" + Convert.ToInt32(ViewState["UserID"]), inputJson);
                            Response.Redirect("MemberMangement.aspx?id=redirectUpdate");
                        }
                        else
                        {
                            Page.ClientScript.RegisterStartupScript(this.GetType(), "toastr_message", "toastr.success('هذا الرقم موجود من قبل .من فضلك قك بتسجيل رقم اخر')", true);
                        }
                    }
                }
                else
                {
                    Committee.Models.User memberUpdate = new Models.User()
                    {
                        ID          = Convert.ToInt32(Request.QueryString["mId"]),
                        Name        = txtMemberName.Text,
                        UserEmailId = txtMemberEmail.Text,

                        Title               = txtMemberJob.Text,
                        SecrtaryOfDept      = Session["DeptId"].ToString(),
                        WorkSide            = txtWorkSide.Text,
                        SystemRole          = Convert.ToInt32(ddlMemberRole.SelectedItem.Value),
                        UserName            = txtUserName.Text,
                        UserPassword        = Encryptor.MD5Hash(txtPass.Text),
                        Address             = txtAddress.Text,
                        ManagerOfDepartment = Session["DeptId"].ToString(),

                        // UserImage = "/" + ImgUpload?.PostedFile?.FileName
                    };
                    if (string.IsNullOrEmpty(txtUserName.Text))
                    {
                        memberUpdate.UserName = memberUpdate.Name;
                    }
                    if (ViewState["Phone"].ToString() == txtPhoneNumber.Text.Trim().ToLower())
                    {
                        memberUpdate.Phone = txtPhoneNumber.Text.Trim().ToLower();
                        if (ImgUpload.PostedFile != null && ImgUpload.PostedFile.ContentLength > 0)
                        {
                            string fname = Path.GetFileName(ImgUpload.PostedFile.FileName);
                            ImgUpload.SaveAs(Server.MapPath(Path.Combine("~/MasterPage/Uploads/", fname)));
                            ImgUser.ImageUrl = "~/MasterPage/Uploads/" + fname;

                            memberUpdate.UserImage = "/" + fname;
                        }
                        else
                        {
                            memberUpdate.UserImage = ImgUser.ImageUrl.Replace("~/MasterPage/Uploads/", "");
                        }


                        string inputJson = (new JavaScriptSerializer()).Serialize(memberUpdate);
                        client.UploadString(apiUrlUser + "/PutUser?id=" + Convert.ToInt32(ViewState["UserID"]), inputJson);
                        Page.ClientScript.RegisterStartupScript(this.GetType(), "toastr_message", "toastr.success('تم تعديل بيانات العضو بنجاح', 'تم')", true);
                    }
                    else
                    {
                        bool phoneExist = WebApiConsume.ValidateUserPhone(txtPhoneNumber.Text.Trim().ToLower());
                        if (!phoneExist)
                        {
                            memberUpdate.Phone = txtPhoneNumber.Text.Trim().ToLower();
                            if (ImgUpload.PostedFile != null && ImgUpload.PostedFile.ContentLength > 0)
                            {
                                string fname = Path.GetFileName(ImgUpload.PostedFile.FileName);
                                ImgUpload.SaveAs(Server.MapPath(Path.Combine("~/MasterPage/Uploads/", fname)));
                                ImgUser.ImageUrl = "~/MasterPage/Uploads/" + fname;

                                memberUpdate.UserImage = "/" + fname;
                            }
                            else
                            {
                                memberUpdate.UserImage = ImgUser.ImageUrl;
                            }
                            string inputJson = (new JavaScriptSerializer()).Serialize(memberUpdate);

                            client.UploadString(apiUrlUser + "/PutUser?id=" + Convert.ToInt32(ViewState["UserID"]), inputJson);
                            Response.Redirect("MemberMangement.aspx?id=redirectUpdate");
                        }
                        else
                        {
                            Page.ClientScript.RegisterStartupScript(this.GetType(), "toastr_message", "toastr.success('هذا الرقم موجود من قبل .من فضلك قك بتسجيل رقم اخر')", true);
                        }
                    }
                }
            }

            else if (Request.QueryString["status"] == "new")
            {
                bool phoneExist = WebApiConsume.ValidateUserPhone(txtPhoneNumber.Text.Trim().ToLower());
                if (!phoneExist)
                {
                    if (ImgUpload.PostedFile != null && ImgUpload.PostedFile.ContentLength > 0)
                    {
                        string fname = Path.GetFileName(ImgUpload.PostedFile.FileName);
                        ImgUpload.SaveAs(Server.MapPath(Path.Combine("~/MasterPage/Uploads/", fname)));
                    }


                    string apiUrlMember = Utilities.BASE_URL + "/api/Users";

                    if (Session["SystemRole"].ToString() == "1")
                    {
                        int    systemRole = 0;
                        string secRole    = null;
                        if (ddlMemberType.SelectedItem.Value == "4")
                        {
                            systemRole = 4;
                            secRole    = ddlmangerForDept?.SelectedItem?.Value;
                        }
                        if (ddlMemberType.SelectedItem.Value == "5")
                        {
                            systemRole = 5;
                            secRole    = null;
                        }
                        Committee.Models.User memberManger = new Models.User()
                        {
                            Name                = txtMemberName.Text,
                            UserEmailId         = txtMemberEmail.Text,
                            Phone               = txtPhoneNumber.Text,
                            Title               = txtMemberJob.Text,
                            SecrtaryOfDept      = secRole,
                            WorkSide            = txtWorkSide.Text,
                            SystemRole          = systemRole,
                            UserName            = txtUserName.Text,
                            UserPassword        = Encryptor.MD5Hash(txtPasswordOfManager.Text),
                            Address             = txtAddress.Text,
                            UserImage           = "/" + ImgUpload?.PostedFile?.FileName,
                            ManagerOfDepartment = ddlmangerForDept?.SelectedItem?.Value,
                        };

                        if (string.IsNullOrEmpty(txtuserNameOfManager.Text))
                        {
                            memberManger.UserName = memberManger.Name;
                        }
                        else
                        {
                            memberManger.UserName = txtuserNameOfManager.Text;
                        }
                        string inputJsonMember = (new JavaScriptSerializer()).Serialize(memberManger);


                        client.UploadString(apiUrlMember + "/PostUser", inputJsonMember);
                    }
                    else
                    {
                        Committee.Models.User member = new Models.User()
                        {
                            Name                = txtMemberName.Text,
                            UserEmailId         = txtMemberEmail.Text,
                            Phone               = txtPhoneNumber.Text,
                            Title               = txtMemberJob.Text,
                            SecrtaryOfDept      = ddlmangerForDept?.SelectedItem?.Value,
                            WorkSide            = txtWorkSide.Text,
                            SystemRole          = 6,
                            UserName            = txtUserName.Text,
                            UserPassword        = Encryptor.MD5Hash(txtPass.Text),
                            Address             = txtAddress.Text,
                            UserImage           = "/" + ImgUpload?.PostedFile?.FileName,
                            ManagerOfDepartment = Session["DeptId"].ToString(),
                        };
                        if (string.IsNullOrEmpty(txtUserName.Text))
                        {
                            member.UserName = member.Name;
                        }
                        string inputJson = (new JavaScriptSerializer()).Serialize(member);


                        client.UploadString(apiUrlMember + "/PostUser", inputJson);
                    }



                    ResetControld();
                    Response.Redirect("MemberMangement.aspx?id=redirectSave");
                }
                else
                {
                    // Page.ClientScript.RegisterStartupScript(this.GetType(), "toastr_message", "toastr.success('هذا الرقم موجود من قبل .من فضلك قك بتسجيل رقم اخر', 'تم')", true);
                    ScriptManager.RegisterClientScriptBlock(this.Page, this.Page.GetType(), "تم", "alert('هذا الرقم موجود من قبل .من فضلك قك بتسجيل رقم اخر');", true);
                }
            }
        }
예제 #27
0
        public ActionResult Edit(int id, POST Post, FormCollection form, HttpPostedFileBase PICTURE)
        {
            CustomPrincipal prin = (CustomPrincipal)User;

            if (ModelState.IsValid)
            {
                POST   PostEdit    = postsModels.GetItem(id);
                string picture_old = "";
                string picture_new = "";
                //upload file
                if (PICTURE != null && PICTURE.ContentLength > 0)
                {
                    var       path      = Server.MapPath("~/Assets/Upload/Post/");
                    ImgUpload imgUpload = new ImgUpload();
                    Post.PICTURE = imgUpload.Upload(PICTURE, path);
                    picture_new  = Post.PICTURE;
                    picture_old  = PostEdit.PICTURE;
                }
                else
                {
                    Post.PICTURE = PostEdit.PICTURE;
                }
                if (this.Request.Form["ACTIVE"] != null)
                {
                    Post.ACTIVE = true;
                }
                else
                {
                    if (prin.ROLE.Equals(ConstanAppkey.ADMIN()) || prin.ROLE.Equals(ConstanAppkey.MOD()))
                    {
                        Post.ACTIVE = false;
                    }
                    else
                    {
                        Post.ACTIVE = PostEdit.ACTIVE;
                    }
                }
                int idPosst = postsModels.EditItem(id, Post);
                if (idPosst > 0)
                {
                    if (!picture_old.Equals(""))
                    {
                        var       dataFile  = Server.MapPath("~/Assets/Upload/Post/" + picture_old);
                        ImgUpload imgUpload = new ImgUpload();
                        imgUpload.Delete(dataFile);
                    }
                    Session["mes"] = "Sửa thành công";
                }
                else
                {
                    if (!picture_new.Equals(""))
                    {
                        var       dataFile  = Server.MapPath("~/Assets/Upload/Post/" + picture_new);
                        ImgUpload imgUpload = new ImgUpload();
                        imgUpload.Delete(dataFile);
                    }
                    Session["mes_er"] = "Sửa thất bại";
                }
                return(RedirectToAction("Index", "PostManager"));
            }
            ViewBag.ListCategories = categoriesModels.GetAllItem();
            return(View(Post));
        }
예제 #28
0
        public ActionResult Edit(int id, USER UserE, FormCollection form, HttpPostedFileBase Picture)
        {
            CustomPrincipal prin = (CustomPrincipal)User;

            if (userModels.CheckEmailEdit(UserE.EMAIL, id))
            {
                if (roleModels.GetItem(UserE.ID_ROLE).NAME.Equals(ConstanAppkey.ADMIN()))
                {
                    if (!(id == prin.ID && prin.ROLE.Equals(ConstanAppkey.ADMIN())))
                    {
                        ViewBag.ListRole = roleModels.GetAllItems();
                        return(View(UserE));
                    }
                }
                if (prin.ROLE.Equals(ConstanAppkey.ADMIN()) && id == prin.ID)
                {
                    UserE.ID_ROLE = roleModels.GetItemName(ConstanAppkey.ADMIN()).ID;
                }
                if (this.Request.Form["ACTIVE"] != null)
                {
                    UserE.ACTIVE = true;
                }
                else
                {
                    UserE.ACTIVE = false;
                }
                if (ModelState.IsValid)
                {
                    USER user1 = userModels.GetItem(id);
                    //upload file
                    string picture_new = "";
                    string picture_old = "";
                    if (Picture != null && Picture.ContentLength > 0)
                    {
                        // create new file
                        ImgUpload imgUpload = new ImgUpload();
                        var       path      = Server.MapPath("~/Assets/Upload/User");
                        UserE.PICTURE = imgUpload.Upload(Picture, path);
                        picture_new   = UserE.PICTURE;
                        picture_old   = user1.PICTURE;
                    }
                    else
                    {
                        UserE.PICTURE = user1.PICTURE;
                    }
                    if (userModels.EditItem(id, UserE) > 0)
                    {
                        if (!picture_old.Equals(""))
                        {
                            // delete file old
                            var       dataFile  = Server.MapPath("~/Assets/Upload/User/" + picture_old);
                            ImgUpload imgUpload = new ImgUpload();
                            imgUpload.Delete(dataFile);
                        }
                        Session["mes"] = "Sửa thành công";
                    }
                    else
                    {
                        if (!picture_new.Equals(""))
                        {
                            // delete file old
                            var       dataFile  = Server.MapPath("~/Assets/Upload/User/" + picture_new);
                            ImgUpload imgUpload = new ImgUpload();
                            imgUpload.Delete(dataFile);
                        }
                        Session["mes_er"] = "Sửa thất bại";
                    }
                    return(RedirectToAction("Index", "UserManager"));
                }
            }
            else
            {
                ViewBag.message_er = "Sửa thất bại! Email đã tồn tại";
            }
            ViewBag.ListRole = roleModels.GetAllItems();
            return(View(UserE));
        }
예제 #29
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (IsValid)
            {
                try
                {
                    conn.Open();
                    command.Connection  = conn;
                    command1.Connection = conn;


                    if (ImgUpload.HasFile && ImgUpload.PostedFile.ContentLength > 0)
                    {
                        Path = ("~/ReviewImages/" + ImgUpload.FileName);
                        ImgUpload.SaveAs(Server.MapPath(Path));
                    }
                    // get the users name
                    string userName = HttpContext.Current.User.Identity.Name;
                    //set the commandType to storedprocedure
                    command.CommandType = CommandType.StoredProcedure;

                    //set the commandText to the name of our stored procedure
                    command.CommandText = "[dbo].[WriteReview]";

                    //provide values for the procedure's parameters
                    command.Parameters.AddWithValue("@Title", txtTitle.Text);
                    command.Parameters.AddWithValue("@Photo", Path);
                    command.Parameters.AddWithValue("@Username", HttpContext.Current.User.Identity.Name);
                    if (ddlType.SelectedIndex == 0)
                    {
                        command.Parameters.AddWithValue("@FishingType", 1);
                    }
                    else
                    {
                        command.Parameters.AddWithValue("@FishingType", 2);
                    }

                    command.Parameters.AddWithValue("@Region", ddlCounties.SelectedValue);
                    command.Parameters.AddWithValue("@ReviewText", txtDescription.Text);
                    if (ddlRiverOrLake.SelectedIndex == 0)
                    {
                        command.Parameters.AddWithValue("@River", ddlRiverLake.SelectedValue);
                        command.Parameters.AddWithValue("@Lake", DBNull.Value);
                    }
                    else
                    {
                        command.Parameters.AddWithValue("@Lake", ddlRiverLake.SelectedValue);
                        command.Parameters.AddWithValue("@River", DBNull.Value);
                    }
                    command.Parameters.Add("@review", SqlDbType.Int).Direction = ParameterDirection.Output;
                    //execute the command
                    command.ExecuteNonQuery();
                    reviewID = (int)command.Parameters["@review"].Value;

                    command1.CommandType = CommandType.StoredProcedure;
                    //set the commandText to the name of our stored procedure
                    command1.CommandText = "[dbo].[AddFishCaught]";

                    if (ddlType.SelectedIndex == 0)
                    {
                        for (int i = 0; i < cbxCoarse.Items.Count - 1; i++)
                        {
                            if (cbxCoarse.Items[i].Selected)
                            {
                                command1.Parameters.AddWithValue("@FishSpecies", cbxCoarse.Items[i].Value);
                                command1.Parameters.AddWithValue("@reviewId", reviewID);
                                command1.ExecuteNonQuery();
                                command1.Parameters.Clear();
                            }
                        }
                    }
                    else
                    {
                        for (int i = 0; i < cbxGame.Items.Count - 1; i++)
                        {
                            if (cbxGame.Items[i].Selected)
                            {
                                command1.Parameters.AddWithValue("@reviewId", (Object)reviewID ?? DBNull.Value);;
                                command1.Parameters.AddWithValue("@FishSpecies", cbxGame.Items[i].Value);

                                command1.ExecuteNonQuery();
                                command1.Parameters.Clear();
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    lblError.Text = ex.Message;
                }
                finally
                {
                    conn.Close();
                }

                Response.Redirect("ReviewDetails.aspx?id=" + reviewID);
            }
        }
예제 #30
0
        protected void Button1_Click1(object sender, EventArgs e)
        {
            try
            {
                _dtowebsite = new DtoWebsite();
                _bllwebsite = new BllWebsite();

                _dtowebsite.UserId      = GetUserId();
                _dtowebsite.WebSiteName = TextBox1.Text;
                _dtowebsite.WebsiteUrl  = TextBox2.Text;
                _dtowebsite.WebsiteId   = Convert.ToInt64(ViewState["websiteid"]);
                _dtowebsite.WebsiteType = dplstwebsitetype.SelectedValue;

                _dtowebsite.Tag     = chktag.Checked;
                _dtowebsite.Emotion = chkemotion.Checked;
                if (chktag.Checked)
                {
                    _dtowebsite.AddTag  = chkaddable.Checked;
                    _dtowebsite.RateTag = chkrateable.Checked;
                }
                else
                {
                    chkaddable.Style.Add("display", "none");
                    chkrateable.Style.Add("display", "none");
                }

                if (chkemotion.Checked)
                {
                    _dtowebsite.AddEmotion = chkemoaddable.Checked;
                }
                else
                {
                    chkemoaddable.Style.Add("display", "none");
                }

                var isValidFile = false;

                if (ImgUpload.FileName != "")
                {
                    string[] validFileTypes = { "bmp" };
                    var      ext            = Path.GetExtension(ImgUpload.PostedFile.FileName);
                    for (var i = 0; i < validFileTypes.Length; i++)
                    {
                        if (ext == "." + validFileTypes[i])
                        {
                            isValidFile             = true;
                            _dtowebsite.WebsiteLogo = Guid.NewGuid() + "." + ext;
                            ImgUpload.SaveAs(Server.MapPath("~/Images/WebsiteLogo/") + _dtowebsite.WebsiteLogo);
                            break;
                        }
                    }
                    if (!isValidFile)
                    {
                        lbluplderrmsg.Text = "Invalid File. Please upload a File with extension " +
                                             string.Join(",", validFileTypes);
                    }
                }
                else
                {
                    if (imgweblogo.ImageUrl == "")
                    {
                        _dtowebsite.WebsiteLogo = ConvertTextToImage(TextBox1.Text.Substring(0, 1).ToUpper(), "Arial",
                                                                     30, Color.White, Color.Black, 50, 50);
                    }
                    isValidFile = true;
                }

                if (isValidFile)
                {
                    int flag = Convert.ToInt16(_bllwebsite.UpdateWebsite(_dtowebsite));
                    switch (flag)
                    {
                    case -1:
                        LblRegisterWebsite.Text    = "Website URL Already Exists";
                        LblRegisterWebsite.Visible = true;
                        break;

                    case -2:
                        LblRegisterWebsite.Text    = "WebsiteName Already Exists";
                        LblRegisterWebsite.Visible = true;
                        break;

                    default:
                        LblRegisterWebsite.Visible = false;
                        Response.Redirect("../User/Setting.aspx");
                        break;
                    }

                    Response.Redirect("../User/Setting.aspx");
                }
            }
            catch (Exception ex)
            {
                ex.ToExceptionless().Submit();
            }
        }