コード例 #1
0
        public ActionResult UodateImage(FormCollection collection)
        {
            string userid = HttpContext.User.Identity.GetUserId();
            User   user   = db.Users.Find(userid);

            System.IO.File.Delete(Server.MapPath(user.UserPhotoUrl));
            string uri = collection.Get("base64");

            if (uri != "")
            {
                //Remove the prefix from the base 64 string
                string base64 = string.Empty;
                if (uri.Contains(ExpectedImagePrefixJpeg))
                {
                    base64 = uri.Substring(ExpectedImagePrefixJpeg.Length);
                }
                else
                {
                    base64 = uri.Substring(ExpectedImagePrefixPng.Length);
                }
                //convert to byte array
                byte[] bytes = Convert.FromBase64String(base64);
                //declare the directory where the resulting image will be saved
                string directory = "~/Content/uploads/profiles/" + user.Id + "/";

                //Create the image object that will be the image
                Image image;
                //Use MemoryStream to read byte array
                using (MemoryStream ms = new MemoryStream(bytes))
                {
                    //create the image
                    image = Image.FromStream(ms);
                    //Make sure that the directory where the image is to be store actually exists;
                    if (Directory.Exists(Server.MapPath(directory)))
                    {
                        //Save the image to directory
                        image.Save(Server.MapPath(directory + "/Profile.jpg"), ImageFormat.Jpeg);
                        //Its called Mime type, buts just the URL where the image is located
                        user.UserPhotoUrl = directory.Replace("~", "") + "/Profile.jpg";
                    }
                }
            }

            db.Entry(user).State = System.Data.Entity.EntityState.Modified;
            db.SaveChanges();
            return(RedirectToAction("Index", "Manage", null));
        }
コード例 #2
0
        public bool MarkTrackAsPlayed(long id, long playlistId)
        {
            var playlist = context.Playlists.Include(p => p.PlaylistTracks).Single(p => p.Id == playlistId);
            var track    = playlist.PlaylistTracks.Single(t => t.Id == id);

            if (track == null)
            {
                return(false);
            }
            track.PlayedAt = DateTime.Now;

            context.Entry(track).State = EntityState.Modified;
            context.SaveChanges();
            return(true);
        }
コード例 #3
0
 public bool Update(PositionModel model)
 {
     try
     {
         tbl_CV tbl = new tbl_CV();
         tbl.Ma_CV           = model.Ma_CV;
         tbl.Ten_CV          = model.Ten_CV;
         tbl.Display         = model.Display;
         db.Entry(tbl).State = System.Data.Entity.EntityState.Modified;
         db.SaveChanges();
         return(true);
     }
     catch
     {
         return(false);
     }
 }
コード例 #4
0
ファイル: TeamDao.cs プロジェクト: toannd18/PTSC_QNG
 public bool Update(TeamModel model)
 {
     try
     {
         tbl_TO tbl = new tbl_TO();
         tbl.Ma_TO           = model.Ma_TO;
         tbl.Ten_TO          = model.Ten_TO;
         tbl.Ma_BP           = model.Ma_BP;
         db.Entry(tbl).State = System.Data.Entity.EntityState.Modified;
         db.SaveChanges();
         return(true);
     }
     catch
     {
         return(false);
     }
 }
コード例 #5
0
ファイル: WebApiController.cs プロジェクト: VadimSaltykov/Web
        public IHttpActionResult EditBook(int id, [FromBody] Book book)
        {
            if (book == null)
            {
                return(BadRequest());
            }
            if (id != book.BookId)
            {
                return(NotFound());
            }

            if (id == book.BookId)
            {
                db.Entry(book).State = EntityState.Modified;
                db.SaveChanges();
            }
            return(Ok(book));
        }
コード例 #6
0
ファイル: ResourceService.cs プロジェクト: qzfu/dams
 /// <summary>
 /// 修改文件复制状态
 /// </summary>
 /// <param name="res"></param>
 /// <returns></returns>
 public bool UpdateCopyStateResource(Resources res)
 {
     using (var db = new EFDbContext())
     {
         var entity = db.Resources.FirstOrDefault(x => x.ResourceId == res.ResourceId);
         entity.IsCopyEnd       = 1;
         db.Entry(entity).State = EntityState.Modified;
         try
         {
             db.SaveChanges();
             return(true);
         }
         catch (Exception e)
         {
             return(false);
         }
     }
 }
コード例 #7
0
        public async Task <IActionResult> CloseOrder([FromRoute] int id)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var order = await _context.Orders.FirstOrDefaultAsync(o => o.Id == id);

            if (order == null)
            {
                return(NotFound(new { status = 404, message = "Заказ не был найден" }));
            }
            order.OrderStatus           = OrderStatus.BarCooked;
            _context.Entry(order).State = EntityState.Modified;
            await _context.SaveChangesAsync();

            return(Ok(new { status = "success", message = "Заказ был закрыт" }));
        }
コード例 #8
0
        public IHttpActionResult Reject(int orderId, string reason)
        {
            var orderObj = db.AdoptionOrders.Find(orderId);

            if (orderObj != null)
            {
                if (orderObj.Date > DateTime.Now)
                {
                    orderObj.IsRejected      = true;
                    orderObj.RejectReason    = reason;
                    db.Entry(orderObj).State = EntityState.Modified;
                    db.SaveChanges();
                }
                else
                {
                    return(BadRequest("Срок отклонения истек!"));
                }
            }
            return(NotFound());
        }
コード例 #9
0
ファイル: Program.cs プロジェクト: rafaelvjb/general
        static void Main(string[] args)
        {
            System.Console.Write("Enter your name : ");
            string name = System.Console.ReadLine();

            System.Console.Write("Enter your age : ");
            int age = 0;

            Int32.TryParse(System.Console.ReadLine(), out age);
            System.Console.Write("You are current student");
            bool isCurrent = System.Console.ReadLine().ToUpper().Contains("Y") ? true : false;

            using (EFDbContext context = new EFDbContext())
            {
                Student student = new Student {
                    Name = name, Age = age, IsCurrent = isCurrent
                };
                context.Entry(student).State = System.Data.Entity.EntityState.Added;
                context.SaveChanges();
            }
            System.Console.ReadLine();
        }
コード例 #10
0
        public async Task <IActionResult> PutCategory([FromRoute] int id, [FromBody] Category category)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != category.Id)
            {
                return(BadRequest(new { status = "error", message = "Category id is not equal to id from route" }));
            }

            var categoryExist = _context.Categories.FirstOrDefault(c => c.Name == category.Name && c.Id != category.Id);

            if (categoryExist != null)
            {
                return(BadRequest(new { status = "error", message = "Категория с таким названием уже существует" }));
            }

            _context.Entry(category).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!CategoryExists(id))
                {
                    return(NotFound(new { status = "error", message = "Category was not found" }));
                }
                else
                {
                    throw;
                }
            }

            return(Ok(new { status = "success", message = "Changes was add" }));
        }
コード例 #11
0
        public async Task <IActionResult> PutTable([FromRoute] int id, [FromBody] Table table)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != table.Id)
            {
                return(BadRequest(new { status = "error", message = "Table id is not equal to id from route" }));
            }

            var tableExists = _context.Tables.FirstOrDefault(t => t.Name == table.Name && t.Id != table.Id);

            if (tableExists != null)
            {
                return(BadRequest(new { status = "error", message = "Стол с таким названием уже существует" }));
            }

            _context.Entry(table).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!TableExists(id))
                {
                    return(NotFound(new { status = "error", message = "Table was not found" }));
                }
                else
                {
                    throw;
                }
            }

            return(Ok(new { status = "success", message = "Changes was add" }));
        }
コード例 #12
0
        public async Task <ActionResult> Edit(QuestionAnswerDhamma questionanswerdhamma)
        {
            if (ModelState.IsValid)
            {
                QuestionAnswerDhamma qa = questionanswerdhamma;


                if (qa != null)
                {
                    TempData["message"] = string.Format("Question & Answer Dhamma Information has been saved");
                    db.Entry(qa).State  = EntityState.Modified;
                    await db.SaveChangesAsync();

                    return(RedirectToAction("Index"));
                }
                else
                {
                    return(RedirectToAction("Index"));
                }
            }
            return(View(questionanswerdhamma));
        }
コード例 #13
0
        public async Task <IActionResult> PutMeal([FromRoute] int id, [FromBody] Meal meal)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != meal.Id)
            {
                return(BadRequest(new { status = "error", message = "Meal id is not equal to id from route" }));
            }

            var mealExists = _context.Meals.FirstOrDefault(m => m.Name == meal.Name && m.Weight == meal.Weight && m.Id != meal.Id);

            if (mealExists != null)
            {
                return(BadRequest(new { status = "error", message = "Блюдо с таким названием и описанем уже существует" }));
            }

            _context.Entry(meal).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!MealExists(id))
                {
                    return(NotFound(new { status = "error", message = "Meal was not found" }));
                }
                else
                {
                    throw;
                }
            }

            return(Ok(new { status = "success", message = "Changes was add" }));
        }
コード例 #14
0
        public async Task <IActionResult> PutUser([FromRoute] int id, [FromBody] User user)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != user.Id)
            {
                return(BadRequest(new { status = "error", message = "User id is not equal to id from route" }));
            }
            var loginExist = _context.Users.FirstOrDefault(u => u.Login == user.Login && u.Id != user.Id);

            if (loginExist != null)
            {
                return(BadRequest(new { status = "error", message = "Пользователь с таким логином уже существует" }));
            }
            _context.Entry(user).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!UserExists(id))
                {
                    return(NotFound(new { status = "error", message = "User was not found" }));
                }
                else
                {
                    throw;
                }
            }

            return(Ok(new { status = "success", message = "Changes was add" }));
        }
コード例 #15
0
        public ActionResult AssignManager(int?id)
        {
            if (id == null)
            {
                return(RedirectToAction("Error500", "Home", null));
            }
            Fault fault = db.Faults.Find(id);

            if (fault == null)
            {
                return(HttpNotFound());
            }
            var userId = HttpContext.User.Identity.GetUserId();
            var orgMan = (from x in db.OrganisationManagers where x.UserId == userId select x).FirstOrDefault();

            if (orgMan == null)
            {
                ViewBag.Error = "You are not authorised to execute this action";
            }
            else
            {
                var org             = (from x in db.Organisations where x.OrganisationId == orgMan.OrganisationId select x).FirstOrDefault();
                var orgsDepartments = (from x in db.Departments where x.OrganisationId == org.OrganisationId select x).ToList();
                foreach (var dept in orgsDepartments)
                {
                    if (dept.CategoryId == fault.CategoryId)
                    {
                        var manager = (from x in db.DepartmentManagers where x.DepartmentId == dept.DepartmentId select x).FirstOrDefault();
                        fault.ManagerId       = manager.DepartmentManagerId;
                        db.Entry(fault).State = EntityState.Modified;
                        db.SaveChanges();
                    }
                }
                if (fault.ManagerId == 0)
                {
                    ViewBag.Error = "You have no department to manage this type of fault, yet.";
                }
                else
                {
                    return(RedirectToAction("Management", "Organisations", null));
                }
            }
            return(RedirectToAction("Management", "Organisations", null));
        }
コード例 #16
0
 // Сохранить студента
 public void SaveStudent(Student student)
 {
     try
     {
         if (student == null)
         {
             throw new ArgumentException("Student null");
         }
     }
     catch (ArgumentException ex)
     {
         Console.WriteLine($"Exeption was thown: {ex}");
         throw ex;
     }
     if (student.StudentId == 0)
     {
         context.Student.Add(student);
     }
     else
     {
         context.Entry(student).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
     }
     context.SaveChanges();
 }
コード例 #17
0
 public ActionResult Edit(Vacacion vacacion)
 {
     if (vacacion.Periodo > 20)
     {
         string error = "El periodo máximo de vacaciones es 20 días";
         ModelState.AddModelError("Periodo", error);
     }
     if (vacacion.Periodo <= 5)
     {
         string error = "El periodo mínimo de vacaciones es 5 días";
         ModelState.AddModelError("Periodo", error);
     }
     if (ModelState.IsValid)
     {
         vacacion.FechaFin        = vacacion.FechaInicio.AddDays(vacacion.Periodo);
         vacacion.Estado          = "Aprobado";
         vacacion.Anho            = vacacion.FechaFin.Year;
         db.Entry(vacacion).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     ViewBag.IdPersonalInterno = new SelectList(db.PersonalesInternos, "IdPersonalInterno", "ApellidoMaterno", vacacion.IdPersonalInterno);
     return(View(vacacion));
 }
コード例 #18
0
 // Сохранить преподавателя
 public void SaveTeacher(Teacher teacher)
 {
     try
     {
         if (teacher == null)
         {
             throw new ArgumentException("Teacher null");
         }
     }
     catch (ArgumentException ex)
     {
         Console.WriteLine($"Exeption was thown: {ex}");
         throw ex;
     }
     if (teacher.TeacherId == 0)
     {
         context.Teacher.Add(teacher);
     }
     else
     {
         context.Entry(teacher).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
     }
     context.SaveChanges();
 }
コード例 #19
0
        public async Task <ActionResult> Edit(TProduct prod, HttpPostedFileBase image = null)
        {
            if (ModelState.IsValid)
            {
                if (image != null)
                {
                    prod.ImageMimeType = image.ContentType;
                    prod.ImageData     = new byte[image.ContentLength];
                    image.InputStream.Read(prod.ImageData, 0, image.ContentLength);
                }
                db.Entry(prod).State = EntityState.Modified;
                await db.SaveChangesAsync();

                //repository.SaveProduct(prod);
                TempData["message"] = string.Format("Изменения в товаре \"{0}\" были сохранены", prod.Name_Product);

                return(RedirectToAction("Index"));
            }
            else
            {
                // Что-то не так со значениями данных
                return(View(prod));
            }
        }
コード例 #20
0
 // Созранить работу
 public void SaveHomework(Homework homework)
 {
     try
     {
         if (homework == null)
         {
             throw new ArgumentNullException("Homework null");
         }
     }
     catch (ArgumentNullException ex)
     {
         Console.WriteLine($"Exeption was thown: {ex}");
         throw ex;
     }
     if (homework.HomeworkId == 0)
     {
         context.Homework.Add(homework);
     }
     else
     {
         context.Entry(homework).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
     }
     context.SaveChanges();
 }
コード例 #21
0
        public void Edit(User user)
        {
            context.Entry(user).State = EntityState.Modified;

            Save();
        }
コード例 #22
0
ファイル: EventController.cs プロジェクト: pacmad/TicketBox-1
        public async Task <ActionResult> Edit(int?id, byte[] rowVersion)
        {
            string[] fieldsToBind = new string[] { "Name", "Location", "TimeEvent", "Description", "SpecialEvent", "TypeEventID", "RowVersion" };

            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            var eventToUpdate = await db.Events.FindAsync(id);

            if (eventToUpdate == null)
            {
                Event deletedEvent = new Event();

                TryUpdateModel(deletedEvent, fieldsToBind);

                ModelState.AddModelError(string.Empty,
                                         "Unable to save changes. The department was deleted by another user.");

                ViewBag.TypeEventId = new SelectList(db.TypeEvents, "TypeEventId", "Name", deletedEvent.TypeEventID);
                return(View(deletedEvent));
            }

            if (TryUpdateModel(eventToUpdate, fieldsToBind))
            {
                try
                {
                    db.Entry(eventToUpdate).OriginalValues["RowVersion"] = rowVersion;
                    await db.SaveChangesAsync();

                    return(RedirectToAction("Index"));
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    var entry         = ex.Entries.Single();
                    var clientValues  = (Event)entry.Entity;
                    var databaseEntry = entry.GetDatabaseValues();
                    if (databaseEntry == null)
                    {
                        ModelState.AddModelError(string.Empty,
                                                 "Unable to save changes. The department was deleted by another user.");
                    }
                    else
                    {
                        var databaseValues = (Event)databaseEntry.ToObject();

                        if (databaseValues.Name != clientValues.Name)
                        {
                            ModelState.AddModelError("Name", "Current value: "
                                                     + databaseValues.Name);
                        }
                        if (databaseValues.Location != clientValues.Location)
                        {
                            ModelState.AddModelError("Location", "Current value: "
                                                     + String.Format("{0:c}", databaseValues.Location));
                        }
                        if (databaseValues.TimeEvent != clientValues.TimeEvent)
                        {
                            ModelState.AddModelError("TimeEvent", "Current value: "
                                                     + String.Format("{0:d}", databaseValues.TimeEvent));
                        }
                        if (databaseValues.TypeEventID != clientValues.TypeEventID)
                        {
                            ModelState.AddModelError("TypeEventID", "Current value: "
                                                     + db.TypeEvents.Find(databaseValues.TypeEventID).Name);
                        }
                        if (databaseValues.Description != clientValues.Description)
                        {
                            ModelState.AddModelError("Description", "Current value: "
                                                     + String.Format("{0:d}", databaseValues.Description));
                        }
                        if (databaseValues.SpecialEvent != clientValues.SpecialEvent)
                        {
                            ModelState.AddModelError("SpecialEvent", "Current value: "
                                                     + String.Format("{0:d}", databaseValues.SpecialEvent));
                        }

                        ModelState.AddModelError(string.Empty, "The record you attempted to edit "
                                                 + "was modified by another user after you got the original value. The "
                                                 + "edit operation was canceled and the current values in the database "
                                                 + "have been displayed. If you still want to edit this record, click "
                                                 + "the Save button again. Otherwise click the Back to List hyperlink.");
                        eventToUpdate.RowVersion = databaseValues.RowVersion;
                    }
                }
                catch (RetryLimitExceededException /* dex */)
                {
                    //Log the error (uncomment dex variable name and add a line here to write a log.
                    ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
                }
            }
            ViewBag.TypeEventId = new SelectList(db.TypeEvents, "TypeEventId", "Name", eventToUpdate.TypeEventID);
            return(View(eventToUpdate));
        }
コード例 #23
0
        public ActionResult ReportFault([Bind(Include = "Description")] Fault fault, FormCollection collection)
        {
            //Get Latitude from hidden input of name='latitude'
            string lat = collection.Get("latitude");
            //Get Longitude value from hidden input of name='longitude'
            string lng = collection.Get("longitude");
            //Get the id of the logged on user
            string guid = HttpContext.User.Identity.GetUserId();
            //Since only public users may report faults, get an object of type PublicUser
            PublicUser user = (from x in db.PublicUsers where x.UserId == guid select x).FirstOrDefault();

            if (user != null)
            {
                /*-----------Add LatLng to Model-----------------*/
                //Due to some computer systems using commas instead of periods for decimal points
                //Therefore, check to see if "," exists. If so, replace with a period
                if (lat.Contains(","))
                {
                    lat.ToString().Replace(",", ".");
                    lng.ToString().Replace(",", ".");
                    //add values to the fault object. Data type must be double for best results for geolocation
                    //On a side note, no idea why I had to include CultureInfo, it works this way so f**k it.
                    fault.Latitude  = Convert.ToDouble(lat, CultureInfo.InvariantCulture);
                    fault.Longitude = Convert.ToDouble(lng, CultureInfo.InvariantCulture);
                }
                else
                {
                    //Since we are dealing with periods, just add the values as is
                    fault.Latitude  = Convert.ToDouble(lat, CultureInfo.InvariantCulture);
                    fault.Longitude = Convert.ToDouble(lng, CultureInfo.InvariantCulture);
                }

                /*---------Add Public User Id and Date Created-----------*/
                fault.PublicUserId = user.PublicUserId;
                fault.DateCreated  = DateTime.Now;

                /*----------Add Category Id and Manager Id---------------*/
                //get category ID from formcollection with name="CategoryId"
                int categoryId = Convert.ToInt32(collection.Get("CategoryId"));
                fault.CategoryId = categoryId;

                /*------------Add Severity Id----------------------------*/
                //get severity level from formcollection with name="SeveritySlider"
                int SeverityLevel = Convert.ToInt32(collection.Get("SeveritySlider"));
                fault.SeverityId = SeverityLevel;

                /*----------------Add Upload image here------------------*/
                //So this was hard. Using HttpPostedFileBase should have worked. But no.
                //So I learnt that base64 string can can be grabbed from javascript and appended to
                //an hidden input where I grabbed in from the formcollection
                string data_uri = collection.Get("base64Label");
                //check that base64 is not null, else do not add to fault. It is nullable
                if (data_uri != "")
                {
                    //Remove the prefix from the base 64 string
                    string base64 = string.Empty;
                    if (data_uri.Contains(ExpectedImagePrefixJpeg))
                    {
                        base64 = data_uri.Substring(ExpectedImagePrefixJpeg.Length);
                    }
                    else
                    {
                        base64 = data_uri.Substring(ExpectedImagePrefixPng.Length);
                    }
                    //convert to byte array
                    byte[] bytes = Convert.FromBase64String(base64);
                    //declare the directory where the resulting image will be saved
                    string directory = "~/Content/img/faults/" + user.PublicUserId + "/";

                    //Create the image object that will be the image
                    //Create the image object that will be the image
                    Image image;
                    Image thumbnail;
                    //Use MemoryStream to read byte array
                    using (MemoryStream ms = new MemoryStream(bytes))
                    {
                        //create the image
                        image     = Image.FromStream(ms);
                        thumbnail = Image.FromStream(ms);
                        var imageRectangle = new Rectangle(0, 0, 85, 85);
                        var bitmapVersion  = new Bitmap(image);
                        bitmapVersion = bitmapVersion.Clone(imageRectangle, PixelFormat.DontCare);
                        //Make sure that the directory where the image is to be store actually exists;
                        if (Directory.Exists(directory))
                        {
                            //We need a unique directory for the image. So I've used the public users ID and The date created
                            string date = (fault.DateCreated.Day.ToString() + fault.DateCreated.Month.ToString() + fault.DateCreated.Year.ToString() + fault.DateCreated.TimeOfDay.ToString().Replace(":", "")).Replace(".", "");
                            //Save the image to directory
                            image.Save(Server.MapPath(directory + date + ".jpg"), ImageFormat.Jpeg);
                            bitmapVersion.Save(Server.MapPath(directory + date + ".png"), ImageFormat.Png);
                            //Its called Mime type, buts just the URL where the image is located
                            fault.ImageURL       = directory.Replace("~", "") + date + ".jpg";
                            fault.ImageThumbnail = directory.Replace("~", "") + date + ".png";
                        }
                        else
                        {
                            string date = fault.DateCreated.Day.ToString() + fault.DateCreated.Month.ToString() + fault.DateCreated.Year.ToString() + fault.DateCreated.TimeOfDay.ToString().Replace(":", "");
                            //Directory does not exist so damn well create it
                            Directory.CreateDirectory(Server.MapPath(directory));
                            image.Save(Server.MapPath(directory + date + ".jpg"), ImageFormat.Jpeg);
                            bitmapVersion.Save(Server.MapPath(directory + date + "..png"), ImageFormat.Png);
                            fault.ImageURL       = directory.Replace("~", "") + date + ".jpg";
                            fault.ImageThumbnail = directory.Replace("~", "") + date + ".png";
                        }
                    }
                }
                /*-------------Add Sub-category------------------------*/
                //Get sub-category from formcollection with name='subCatId'
                int subCatId = Convert.ToInt32(collection.Get("subCatId"));
                //Sub-category is nullable so only add if it exists
                if (subCatId != 0)
                {
                    fault.SubCategoryId = subCatId;
                }
                /*-------------Add Progress Bools--------------*/
                fault.NotStarted = true;
                fault.InProgress = false;
                fault.Resolved   = false;
                /*-------------Increment Count of Category Used--------------------------*/
                Category category = db.Categories.Find(fault.CategoryId);
                int      count    = category.Count + 1;
                category.Count = count;

                /*------------Save changes to Database-----------------*/
                try
                {
                    db.Faults.Add(fault);
                    db.Entry(category).State = EntityState.Modified;
                    db.SaveChanges();

                    /*-----------Email Manager Fault Details-----------*/
                    Email EmailFault = new Email();
                    EmailFault.ProcesFault(fault, db);

                    //Finally Add Suburb to ReportSuburb Table
                    var          helpers = new Helpers();
                    string       suburb  = helpers.GetSuburb(Convert.ToDouble(lat, CultureInfo.InvariantCulture), Convert.ToDouble(lng, CultureInfo.InvariantCulture));
                    ReportSuburb rSuburb = (from x in db.ReportSuburbs where x.Suburb == suburb select x).FirstOrDefault();
                    if (rSuburb == null)
                    {
                        ReportSuburb newSubReport = new ReportSuburb()
                        {
                            Suburb = suburb
                        };
                        db.ReportSuburbs.Add(newSubReport);
                        db.SaveChanges();
                    }
                    else
                    {
                        db.ReportSuburbs.Add(rSuburb);
                        db.SaveChanges();
                    }

                    //Redirect to Index
                    return(RedirectToAction("ThanksForReporting", new { id = fault.FaultId }));
                }
                catch (Exception ex)
                {
                    return(RedirectToAction("TroubleShooting", "Home", ex));
                }
            }
            else
            {
                return(RedirectToAction("Login", "Account", null));
            }
        }
コード例 #24
0
        public void Edit(Department department)
        {
            context.Entry(department).State = EntityState.Modified;

            Save();
        }
コード例 #25
0
 public void Update(User user)
 {
     db.Entry(user).State = EntityState.Modified;
 }
コード例 #26
0
 public void UpdateVehicleModel(VehicleModel vehicleModel)
 {
     _context.Entry(vehicleModel).State = EntityState.Modified;
 }
コード例 #27
0
ファイル: EntityUtility.cs プロジェクト: TK0431/FrameWork
 /// <summary>
 /// 更新
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="model"></param>
 /// <returns></returns>
 public int Update <T>(T table) where T : class
 => TryCatchUpdateConcurrencyException(() => _db.Entry <T>(table).State = EntityState.Modified);
コード例 #28
0
 public User UpdateUser(User user)
 {
     context.Entry(user).State = System.Data.Entity.EntityState.Modified;
     context.SaveChanges();
     return(user);
 }
コード例 #29
0
 public void Update(User item)
 {
     db.Entry(item).State = EntityState.Modified;
 }
コード例 #30
0
 public void Delete(int Id)
 {
     var obj = Get(Id);
     context.Entry(obj).State = System.Data.Entity.EntityState.Deleted;
     context.SaveChanges();
 }