Exemple #1
0
        public ActionResult Create([Bind(Include = "Name,SortOrder")] CityModel model)
        {
            using (log4net.NDC.Push("Create city post"))
            {
                _logger.Info("Save specific city");
                _logger.Info(model);
                if (ModelState.IsValid)
                {
                    _logger.Info("Model is valid, map to entity model");
                    var entityModel = MvcModelToDatabaseModelMapper.MapCityForCreate(model);
                    _entities.cities.Add(entityModel);
                    try
                    {
                        _entities.SaveChanges();
                    }
                    catch (Exception ex) {
                        _logger.Warn("Saving of city entity failed", ex);
                        return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError));
                    }
                    return(RedirectToAction("Index"));
                }

                return(View(model));
            }
        }
        public ActionResult Create([Bind(Include = "Id,CityId,Name,Address,ImageLocation,Description,Longitude,Latitude,SortOrder")] CarParkBuildingModel model)
        {
            using (log4net.NDC.Push("Create building post"))
            {
                _logger.Info("Save specific building");
                _logger.Info(model);
                if (ModelState.IsValid)
                {
                    _logger.Info("Model is valid, map to entity model");
                    var entityModel = MvcModelToDatabaseModelMapper.MapBuildingForCreate(model);
                    _entities.parking_location.Add(entityModel);
                    try
                    {
                        _entities.SaveChanges();
                    }
                    catch (Exception ex)
                    {
                        _logger.Warn("Saving of building entity failed", ex);
                        return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError));
                    }
                    return(RedirectToAction("Index"));
                }

                return(View(model));
            }
        }
        public ActionResult DeleteConfirmed(int id)
        {
            infringementpicture infringementpicture = db.infringementpictures.Find(id);

            db.infringementpictures.Remove(infringementpicture);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
        public IHttpActionResult Put(InfringementRequest request)
        {
            try
            {
                var entity       = new infringementEntities();
                var infringement = entity.infringements.FirstOrDefault(x => x.Number == request.InfringementNumber);

                if (infringement == null)
                {
                    return(NotFound());
                }

                RequestToEntityMapper.Map(request, infringement);
                entity.SaveChanges();
                return(GetByInfringementNumber(infringement.Number));
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
        }
        public Task <IEnumerable <FileDesc> > Post(string infringementNumber)
        {
            try
            {
                var folderName = String.Format("uploads/{0}", infringementNumber);
                var path       = HttpContext.Current.Server.MapPath("~/uploads/" + infringementNumber);
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                var entity = new infringementEntities();

                var infringement = entity.infringements.FirstOrDefault(x => x.Number == infringementNumber);
                var longitude    = (System.Web.HttpContext.Current.Request.Form["longitude"] ?? String.Empty).ToString();
                var latitude     = (System.Web.HttpContext.Current.Request.Form["latitude"] ?? String.Empty).ToString();
                var description  = (System.Web.HttpContext.Current.Request.Form["description"] ?? String.Empty).ToString();

                var rootUrl = Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.AbsolutePath, String.Empty);
                if (Request.Content.IsMimeMultipartContent())
                {
                    var streamProvider = new CustomMultipartFormDataStreamProvider(path);

                    var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith <IEnumerable <FileDesc> >(t =>
                    {
                        if (t.IsFaulted || t.IsCanceled)
                        {
                            throw new HttpResponseException(HttpStatusCode.InternalServerError);
                        }

                        var fileInfo = streamProvider.FileData.Select(i =>
                        {
                            var info = new FileInfo(i.LocalFileName);
                            return(new FileDesc(info.Name, rootUrl + "/" + folderName + "/" + info.Name, info.Length / 1024));
                            //return new FileDesc(info.Name,  folderName + "/" + info.Name, info.Length / 1024);
                        });

                        foreach (var info in fileInfo)
                        {
                            entity.infringementpictures.Add(new infringementpicture()
                            {
                                Latitude       = latitude,
                                Longitude      = longitude,
                                Description    = description,
                                InfringementId = infringement.Id,
                                Location       = info.Path
                            });
                        }

                        entity.SaveChanges();

                        return(fileInfo);
                    });

                    return(task);
                }
                else
                {
                    throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable,
                                                                           "This request is not properly formatted"));
                }
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
        public IHttpActionResult Post(InfringementRequest request)
        {
            try
            {
                var entity = new infringementEntities();

                user lUser = (from a in entity.users
                              where a.Email == request.LoginId && a.UserPassword == request.Password && a.IsActive == true
                              select a).FirstOrDefault();

                if (lUser != null)
                {
                    if (entity.infringements.FirstOrDefault(x => x.Number == request.InfringementNumber) != null)
                    {
                        //return BadRequest("Infringement already exists");
                        var error = "Infringement already exists with InfringementNumber:" + request.InfringementNumber;
                        return(BadRequest(error));
                    }
                    int infringementCity = entity.parking_location.FirstOrDefault(x => x.Id == request.BuildingId).CityId;

                    var carmodel1 = entity.carmodels.Where(x => x.Name == request.CarModel).FirstOrDefault();


                    infringement dbInfringement = RequestToEntityMapper.Map(request);
                    if (carmodel1 != null)
                    {
                        dbInfringement.ModelId = Convert.ToInt16(carmodel1.Id);
                    }

                    dbInfringement.CityId        = infringementCity;
                    dbInfringement.CreatedBy     = lUser.Id;
                    dbInfringement.CreatedDate   = System.DateTime.Now;
                    dbInfringement.Pay           = false;
                    dbInfringement.GeneratedFrom = 2;
                    entity.infringements.Add(dbInfringement);
                    entity.SaveChanges();

                    return(GetByInfringementNumber(request.InfringementNumber));
                }
                else
                {
                    var error = "Un-Authhorized access.  Please check your User details.";
                    return(Ok(error));
                }
            }

            catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
            {
                string errormsg = "";
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        System.Diagnostics.Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                        errormsg += validationError.PropertyName + " : " + validationError.ErrorMessage + ", ";
                    }
                }
                return(Ok(errormsg));
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
        }
Exemple #7
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"));
            }
        }
Exemple #8
0
        //[HttpPost]
        public void MNS()
        {
            _logger.Info("MNS called by Flo2Cash");
            var       notificationUrl = ConfigurationManager.AppSettings["Flo2CashNotificationUrl"];
            WebClient wClient         = new WebClient();

            wClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            string         postData          = "";
            string         Email             = "";
            string         transactionNumber = String.Empty;
            string         transactionResult = String.Empty;
            IList <String> customData        = new List <String>();
            string         amount            = String.Empty;

            for (int i = 0; i < Request.Form.AllKeys.Length; i++)
            {
                string key   = Request.Form.AllKeys[i];
                string value = Request.Form[i];

                if (key == "transaction_id")
                {
                    transactionNumber = value;
                }
                else if (key == "transaction_status")
                {
                    transactionResult = value;
                }
                else if (key == "custom_data")
                {
                    IList <String> customDataTemp = value.Split(new char[] { '$' });
                    customData = customDataTemp[0].Split(new char[] { ',' });
                    Email      = customDataTemp[1].ToString();
                }
                postData += key + "=" + Server.UrlEncode(value) + "&";
            }
            postData += "cmd" + "=" + "_xverify-transaction";
            _logger.Info("Posting the following data back  to Flo2Cash:" + postData);
            byte[] postBytes      = Encoding.ASCII.GetBytes(postData);
            byte[] responseBytes  = wClient.UploadData(notificationUrl, "POST", postBytes);
            string actionResponse = Encoding.ASCII.GetString(responseBytes);

            _logger.Info("Action response: " + actionResponse);
            if (actionResponse.Trim().ToUpper() == "VERIFIED")
            {
                foreach (var infr in customData)
                {
                    int infringementNumber = int.Parse(infr);
                    var infringement       = db.infringements.FirstOrDefault(x => x.Id == infringementNumber &&
                                                                             x.StatusId == 1);
                    if (infringement == null)
                    {
                        _logger.Warn("Payment made BUT infringement not found. Infrin num:" +
                                     infr + "txn:" + transactionNumber);
                    }
                    else
                    {
                        _logger.Warn("Payment made AND infringement found. Infrin num:" +
                                     infr + "txn:" + transactionNumber);
                    }
                    if (transactionResult == "2")
                    {
                        _logger.Info("Payment successful, change infringement status");
                        infringement.StatusId    = 2;
                        infringement.PaymentType = "Flow2Cash";
                    }

                    var infringementPayment = new infringement_payment
                    {
                        InfringementId    = infringementNumber,
                        PaymentResult     = transactionResult,
                        TransactionNumber = transactionNumber,
                        TransactionDate   = DateTime.Now
                    };

                    _logger.Info("Infringement payment record created" + infringementPayment);

                    db.infringement_payment.Add(infringementPayment);
                    try
                    {
                        db.SaveChanges();
                        //int[] infringementIds = Array.ConvertAll(Request.Form["custom_data"].ToString().Split(','), int.Parse);
                        string[] custom_data = Request.Form["custom_data"].ToString().Split('$');

                        int[] infringementIds = Array.ConvertAll(custom_data[0].ToString().Split(','), int.Parse);

                        List <infringement> payitems = db.infringements
                                                       .Where(x => infringementIds.Contains(x.Id)
                                                              // && x.StatusId == 1
                                                              ).ToList();

                        decimal totalamount = 0;

                        foreach (infringement info in payitems)
                        {
                            if (DateTime.Now > info.DueDate)
                            {
                                info.ActualAmountToPay = info.AfterDueDate.Value;
                                //info.DisplayDueAmount = "<b>" + info.AfterDueDate.Value + "</b>";
                                info.DisplayDueAmount = info.AfterDueDate.Value.ToString();
                                info.DisplayAmount    = info.Amount.ToString();
                            }
                            else
                            {
                                info.ActualAmountToPay = info.Amount;
                                info.DisplayDueAmount  = info.AfterDueDate.ToString();
                                //info.DisplayAmount = "<b>" + info.Amount.ToString() + "</b>";
                                info.DisplayAmount = info.Amount.ToString();
                            }

                            totalamount += info.ActualAmountToPay;
                        }

                        SendMail(payitems, transactionNumber, Email, totalamount);
                    }
                    catch (Exception ex)
                    {
                        _logger.Error("Payment record not saved in the database", ex);
                        throw;
                    }

                    _logger.Info("MNS completed");
                }
            }
        }