示例#1
0
        public ActionResult Edit([Bind(Include = "Id,IncidentTime,Number,Rego,ParkingLocationId,MakeId,ModelId,OtherMake,OtherModel,CarModel,InfringementTypeId,Amount,Comment,Latitude,Longitude,User,StatusId,,DueDate,AfterDueDate,Name,Street1,Street2,Suburb,PostCode,CountryId,CityName")] InfringementModel model)
        {
            using (log4net.NDC.Push("Post for editing infrin."))
            {
                if (ModelState.IsValid)
                {
                    _logger.Info("Model is valid, search for infringment in the database" + model.Number);
                    _logger.Info(model);
                    var entity = db.infringements.FirstOrDefault(x => x.Number == model.Number);
                    if (entity == null)
                    {
                        _logger.Warn("Infrin. not found");
                        return(new HttpNotFoundResult());
                    }

                    _logger.Info("Infrin. found, updating the database entity");
                    MvcModelToDatabaseModelMapper.MapInfringementForEdit(model, entity);
                    try
                    {
                        entity.User = "******";
                        db.SaveChanges();
                    }
                    catch (Exception ex)
                    {
                        _logger.Warn("Infrin. could not be updated", ex);
                        return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError));
                    }
                    return(RedirectToAction("Index"));
                }
                return(View(model));
            }
        }
        public static void MapInfringementForEdit(InfringementModel model, infringement entity)
        {
            entity.Amount = model.Amount;
            if (entity.Comment != null && entity.Comment != "")
            {
                entity.Comment = model.Comment.Trim();
            }
            else
            {
                entity.Comment = model.Comment;
            }
            entity.IncidentTime       = model.IncidentTime;
            entity.InfringementTypeId = model.InfringementTypeId;
            if (model.Latitude != null && model.Latitude != "")
            {
                entity.Latitude = model.Latitude.Trim();
            }
            else
            {
                entity.Latitude = model.Latitude;
            }
            if (model.Longitude != null && model.Longitude != "")
            {
                entity.Longitude = model.Longitude.Trim();
            }
            else
            {
                entity.Longitude = model.Longitude;
            }
            entity.MakeId = model.MakeId;
            //entity.Model = model.CarModel;
            entity.ModelId           = model.ModelId;
            entity.OtherModel        = model.OtherModel;
            entity.OtherMake         = model.OtherMake;
            entity.ParkingLocationId = model.ParkingLocationId;
            entity.Rego     = model.Rego;
            entity.StatusId = model.StatusId;

            entity.OtherMake    = model.OtherMake;
            entity.OtherModel   = model.OtherModel;
            entity.DueDate      = model.IncidentTime.AddDays(21);
            entity.AfterDueDate = entity.Amount + 20;

            entity.OwnerName             = model.Name;
            entity.Street1               = model.Street1;
            entity.Street2               = model.Street2;
            entity.Suburb                = model.Suburb;
            entity.PostCode              = model.PostCode;
            entity.CountryId             = model.CountryId;
            entity.CityName              = model.CityName;
            entity.OtherInfringementType = model.OtherInfringementType;
            entity.User = model.User;
        }
        public static infringement MapInfringementForCreate(InfringementModel model)
        {
            var entity = new infringement();

            var uploadTime = DateTime.Now;

            entity.UploadTime = uploadTime;
            model.StatusId    = (int)InfringementStatus.Pending;
            if (model.Number == null)
            {
                entity.Number = InfringementNumberGenerator.Generate(model.IncidentTime, model.User);
            }
            else
            {
                entity.Number = model.Number;
            }


            //string dateString = model.IncidentTime.ToString("yyyy-MM-dd hh:mm");

            //DateTime newdate = Convert.ToDateTime(dateString);
            //DateTime newdate1 = DateTime.Parse(dateString);
            //model.IncidentTime = newdate1;

            //DateTime dt = new DateTime();
            //DateTime dt1 = new DateTime(model.IncidentTime.Year, model.IncidentTime.Month, model.IncidentTime.Day, model.IncidentTime.Hour, model.IncidentTime.Minute, 0);
            //string[] startdatetime = dateString.ToString().Split(' ');
            //if (startdatetime.Length > 0)
            //{
            //    string[] startdate = startdatetime[0].Split('-');
            //    string[] starttime = startdatetime[1].Split(':');
            //    dt = new DateTime(Convert.ToInt32(startdate[0]), Convert.ToInt32(startdate[1]), Convert.ToInt32(startdate[2]), Convert.ToInt32(starttime[0]), Convert.ToInt32(starttime[1]), Convert.ToInt32(starttime[2]));
            //    model.IncidentTime = dt1;
            //    //entity.IncidentTime = dt;
            //}

            entity.User = model.User;
            MapInfringementForEdit(model, entity);
            return(entity);
        }
示例#4
0
        public ActionResult Create([Bind(Include = "Id,IncidentTime,Number,Rego,CityId,ParkingLocationId,MakeId,ModelId,OtherMake,OtherModel,InfringementTypeId,Amount,Comment,User,UploadTime,Latitude,Longitude,DueDate,AfterDueDate,OwnerName,Street1,Street2,Suburb,PostCode,CountryId,CityName")] InfringementModel infringement, string Submit, string GalleryImageScroll, HttpPostedFileBase upload)
        {
            using (log4net.NDC.Push("Create infringement post"))
            {
                if (Submit == "Add Photo")
                {
                    var validImageTypes = new string[]
                    {
                        "image/gif",
                        "image/jpg",
                        "image/jpeg",
                        "image/pjpeg",
                        "image/png"
                    };

                    if (upload != null && upload.ContentLength > 0)
                    {
                        if (!validImageTypes.Contains(upload.ContentType))
                        {
                            _logger.Warn("Please choose either a GIF, JPG or PNG image." + upload.ContentType);
                            ModelState.AddModelError("ImageUpload", "Please choose either a GIF, JPG or PNG image.");
                        }
                        else
                        {
                            ImageUpload imageUpload = new ImageUpload();

                            using (var binaryReader = new BinaryReader(upload.InputStream))
                            {
                                imageUpload.Image = binaryReader.ReadBytes(upload.ContentLength);
                            }

                            imageUpload.FileName    = upload.FileName;
                            imageUpload.ContentType = upload.ContentType;

                            List <ImageUpload> imageUploads = (List <ImageUpload>)Session["ImageList"];
                            imageUploads.Add(imageUpload);
                            Session["ImageList"] = imageUploads;

                            int galleryImageScroll = -1;
                            int.TryParse(GalleryImageScroll, out galleryImageScroll);
                            TempData["GalleryImageScroll"] = galleryImageScroll + 1;
                        }
                    }

                    ViewBag.Cities            = new SelectList(db.cities, "id", "name", infringement.CityId);
                    ViewBag.PLocations        = new SelectList(db.parking_location.Where(x => x.CityId == infringement.CityId).OrderBy(x => x.SortOrder), "Id", "Name", infringement.ParkingLocationId);
                    ViewBag.Makes             = new SelectList(db.makes, "id", "Name");
                    ViewBag.InfringementTypes = new SelectList(db.infringementtypes, "Id", "Type");
                    ViewBag.Models            = new SelectList(db.carmodels.Where(x => x.Id == 0), "Id", "Name");
                    ViewBag.Countries         = new SelectList(db.countries.OrderBy(x => x.CountryName), "Id", "CountryName");

                    return(View(infringement));
                }
                else if (Submit == "Save Infringement")
                {
                    var errors = ModelState
                                 .Where(x => x.Value.Errors.Count > 0)
                                 .Select(x => new { x.Key, x.Value.Errors })
                                 .ToArray();

                    if (ModelState.IsValid)
                    {
                        _logger.Info("model is valid, mapping to entity" + infringement);
                        try
                        {
                            infringement.User = "******";

                            var infring = db.infringements.FirstOrDefault(x => x.Number == infringement.Number);
                            if (infring != null)
                            {
                                infringement.Number = null;
                            }

                            var entityModel = MvcModelToDatabaseModelMapper.MapInfringementForCreate(infringement);

                            entityModel.CreatedBy   = (int)Session["UserId"];
                            entityModel.CreatedDate = System.DateTime.Now;

                            entityModel.Pay = false;
                            db.infringements.Add(entityModel);
                            db.SaveChanges();

                            infringement.Number = entityModel.Number;

                            if (Session["ImageList"] != null)
                            {
                                if (db.infringements.FirstOrDefault(x => x.Number == infringement.Number) == null)
                                {
                                    _logger.Warn("Infringement number does not exist in the database");
                                    ModelState.AddModelError("infringementNumber", "Infringement Number does not exist");
                                }
                                else
                                {
                                    //IRestRequest request = new RestRequest(
                                    //    String.Format("infringement/{0}/images", infringement.Number)
                                    //    , Method.POST);

                                    string apiLink = System.Configuration.ConfigurationManager.AppSettings["APIServerPath"];

                                    var client = new RestClient(apiLink + "api"); //"http://localhost:50247/api"

                                    List <ImageUpload> imageUploads = (List <ImageUpload>)Session["ImageList"];

                                    try
                                    {
                                        foreach (ImageUpload imageUpload in imageUploads)
                                        {
                                            //byte[] fileData = null;
                                            //using (var binaryReader = new BinaryReader(upload.InputStream))
                                            //{
                                            //    fileData = binaryReader.ReadBytes(upload.ContentLength);
                                            //}
                                            IRestRequest request = new RestRequest(
                                                String.Format("infringement/{0}/images", infringement.Number)
                                                , Method.POST);


                                            request.AddFileBytes(imageUpload.FileName,
                                                                 imageUpload.Image, imageUpload.FileName, imageUpload.ContentType);

                                            request.AddParameter(new Parameter
                                            {
                                                Name  = "Longitude",
                                                Type  = ParameterType.GetOrPost,
                                                Value = infringement.Longitude
                                            });

                                            request.AddParameter(new Parameter
                                            {
                                                Name  = "Latitude",
                                                Type  = ParameterType.GetOrPost,
                                                Value = infringement.Latitude
                                            });

                                            request.AddParameter(new Parameter
                                            {
                                                Name  = "Description",
                                                Type  = ParameterType.GetOrPost,
                                                Value = imageUpload.FileName
                                            });

                                            _logger.Info("Everything is valid, calling the rest client to save image");
                                            IRestResponse response = client.Execute(request);
                                            var           content  = response.Content; // raw content as string

                                            // already image information we are stroing through API.
                                            //var imageViewModel = new infringementpicture
                                            //{
                                            //    //Location = String.Format("infringement/{0}/images/{1}", infringement.Number, imageUpload.FileName),
                                            //    Location = String.Format("{0}/{1}", infringement.Number, imageUpload.FileName),
                                            //    Latitude = infringement.Latitude,
                                            //    Longitude = infringement.Longitude,
                                            //    InfringementId = entityModel.Id      // int.Parse(infringement.Number)
                                            //};

                                            //db.infringementpictures.Add(imageViewModel);

                                            //db.SaveChanges();
                                        }


                                        return(RedirectToAction("Index"));
                                    }
                                    catch (Exception ex)
                                    {
                                        _logger.Warn("Could not save image", ex);
                                        ModelState.AddModelError("ImageUpload", "Could not save image, try again");
                                        return(View(infringement));
                                    }
                                }
                            }
                        }
                        catch (InvalidOfficerCodeException ex)
                        {
                            _logger.Warn("Officer code is invalid");
                            ModelState.AddModelError("User", "Invalid Officer Code");
                            _logger.Info("Infringement model is not valid, return back to create view");
                            ViewBag.Cities            = new SelectList(db.cities, "id", "name");
                            ViewBag.Makes             = new SelectList(db.makes, "id", "Name");
                            ViewBag.InfringementTypes = new SelectList(db.infringementtypes, "Id", "Type");
                            ViewBag.Countries         = new SelectList(db.countries.OrderBy(x => x.CountryName), "Id", "CountryName");
                            return(View(infringement));
                        }
                        catch (Exception ex)
                        {
                            _logger.Warn("Saving of infrin. entity failed", ex);
                            return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError));
                        }

                        return(RedirectToAction("Index"));
                    }

                    _logger.Info("Infringement model is not valid, return back to create view");
                    ViewBag.Cities            = new SelectList(db.cities, "id", "name");
                    ViewBag.Makes             = new SelectList(db.makes, "id", "Name");
                    ViewBag.InfringementTypes = new SelectList(db.infringementtypes, "Id", "Type");
                    ViewBag.PLocations        = new SelectList(db.parking_location.Where(x => x.CityId == infringement.CityId).OrderBy(x => x.SortOrder), "Id", "Name", infringement.ParkingLocationId);
                    ViewBag.Countries         = new SelectList(db.countries.OrderBy(x => x.CountryName), "Id", "CountryName");
                    return(View(infringement));
                }

                return(RedirectToAction("Index"));
            }
        }