Beispiel #1
0
        public async Task <IHttpActionResult> ChangeAddress(ChangeBusinessAddressRequest changeBusinessAddressRequest)
        {
            // if the user is null or the user is not authenticated
            if (!IsUserAuthenticated)
            {
                return(Content(HttpStatusCode.Unauthorized, "User must be logged to get businesses."));
            }

            var ownerId = UserId;

            var myBusinesses =
                db.BusinessUsers.Where(
                    businessUser =>
                    businessUser.UserId == ownerId &&
                    businessUser.BusinessId == changeBusinessAddressRequest.BusinessId)
                .Include(businessUser => businessUser.Business).FirstOrDefault();

            var newBusiness = myBusinesses.Business;

            newBusiness.Address = changeBusinessAddressRequest.GetAddressString();

            newBusiness.Postcode = changeBusinessAddressRequest.Postcode;

            newBusiness.Location = PostcodesService.Lookup(changeBusinessAddressRequest.Postcode);


            await db.SaveChangesAsync();

            return(Ok());
        }
Beispiel #2
0
        public IEnumerable <Business> Search(string postcode, string type, double distance = 10.0, bool ascending = true, int page = 1,
                                             int pageSize = 25)
        {
            double fixedDistance = FixDistance(distance);
            int    fixedPage     = page < 1 ? 1 : page;
            int    fixedPageSize = pageSize < 10 ? 10 : pageSize;

            DbGeography postcodeLocation = PostcodesService.Lookup(postcode);

            BusinessType businessType = _businessTypeStore.FindByName(type);

            double distanceInMeters = GeoUtils.MilesToMeters(fixedDistance);

            int skip = (fixedPage - 1) * fixedPageSize;

            var searchFilter = _context.Businesses.Where(t => t.Location.Distance(postcodeLocation) <= distanceInMeters && t.BusinessTypeId == businessType.Id);

            if (ascending)
            {
                return(searchFilter.OrderBy(f => f.Location.Distance(postcodeLocation)).Skip(skip).Take(fixedPageSize));
            }
            else
            {
                return(searchFilter.OrderByDescending(f => f.Location.Distance(postcodeLocation)).Skip(skip).Take(fixedPageSize));
            }
        }
        public async Task <IHttpActionResult> Validate(string postcode)
        {
            if (!string.IsNullOrWhiteSpace(postcode))
            {
                var result = await PostcodesService.ValidateAsync(postcode);

                return(Ok(result));
            }

            return(BadRequest("the postcode code given in null or just contains white space characters."));
        }
        public IHttpActionResult Search(string businessType = null, string postcode = null, double distance = 10)
        {
            string userId = null;

            try
            {
                var user = User as ClaimsPrincipal;

                if (user != null)
                {
                    userId = user.Identity.GetUserId();
                }
            }
            catch (Exception)
            {
                //throw;
            }

            var
                applicationDbContext = db;

            var businessType2 = db.BusinessTypes.FirstOrDefault(type => type.Name == businessType);

            if (businessType2 == null)
            {
                return(Content(HttpStatusCode.NotFound, "The given business type could not be found in the database"));
            }

            var searchLocation = PostcodesService.Lookup(postcode);



            //  SearchStore searchStore = new SearchStore(applicationDbContext);

            // searchStore.Search(postcode, businessType);



            double distanceInMiles = distance;

            double distanceInMeters = GeoUtils.MilesToMeters(distanceInMiles);


            var searchResults =
                applicationDbContext.Businesses.Where(
                    t => t.BusinessTypeId == businessType2.Id && t.Location.Distance(searchLocation) <= distanceInMeters)
                .OrderBy(business => business.Location.Distance(searchLocation));

            //var q = applicationDbContext.Businesses;


            SearchResponse searchResponse = new SearchResponse();

            searchResponse.BusinessType   = businessType2.Name;
            searchResponse.BusinessTypeId = businessType2.Id;
            searchResponse.Postcode       = postcode;



            searchResponse.Latitude  = searchLocation.Latitude.Value;
            searchResponse.Longitude = searchLocation.Longitude.Value;

            searchResponse.Within  = distance;
            searchResponse.WithinM = distanceInMeters;

            List <BusinessSearchResult> results = new List <BusinessSearchResult>();

            foreach (Business business in searchResults)
            {
                double distanceFromPostcode = business.Location.Distance(searchLocation).Value;

                var result = new BusinessSearchResult()
                {
                    Distance   = Math.Round(distanceFromPostcode, 0),
                    Name       = business.Name,
                    BusinessId = business.Id,
                    Latitude   = business.Location.Latitude,
                    Longitude  = business.Location.Longitude,
                    Postcode   = business.Postcode,
                    Address    = business.Address,
                    Website    = business.Website,
                };

                results.Add(result);
            }

            searchResponse.Results = results;

            return(Ok(searchResponse));
        }
        private async Task <IHttpActionResult> Register2(AccountRegistrationRequest accountRegistrationRequest, DateTime?registrationDate, bool dummy = false)
        {
            if (accountRegistrationRequest != null)
            {
                if (ModelState.IsValid || IsUserAuthenticated)
                {
                    ApplicationDbContext context = ApplicationDbContext.Create();

                    UserStore <ApplicationUser> userStore = new UserStore <ApplicationUser>(context);

                    ApplicationUserManager userManager = new ApplicationUserManager(userStore);

                    string password = accountRegistrationRequest.Password;

                    string[] addressParts =
                    {
                        accountRegistrationRequest.AddressLine1,
                        accountRegistrationRequest.AddressLine2,
                        accountRegistrationRequest.TownCity
                    };

                    string address = string.Join(",\r\n",
                                                 addressParts.Where(part => !string.IsNullOrWhiteSpace(part)));

                    ApplicationUser newApplicationUser = new ApplicationUser();


                    if (IsUserAuthenticated)
                    {
                        newApplicationUser = await userStore.FindByIdAsync(this.UserId);
                    }


                    if (accountRegistrationRequest.FirstName != null)
                    {
                        newApplicationUser.FirstName = accountRegistrationRequest.FirstName;
                    }
                    if (accountRegistrationRequest.LastName != null)
                    {
                        newApplicationUser.LastName = accountRegistrationRequest.LastName;
                    }

                    newApplicationUser.Address = address;

                    if (accountRegistrationRequest.Postcode != null)
                    {
                        newApplicationUser.Postcode = accountRegistrationRequest.Postcode;
                    }

                    if (accountRegistrationRequest.EmailAddress != null)
                    {
                        newApplicationUser.Email = accountRegistrationRequest.EmailAddress;
                    }

                    if (!IsUserAuthenticated)
                    {
                        if (accountRegistrationRequest.EmailAddress != null)
                        {
                            newApplicationUser.UserName = accountRegistrationRequest.EmailAddress;
                        }
                    }

                    if (accountRegistrationRequest.DateOfBirth != default(DateTime))
                    {
                        newApplicationUser.DateOfBirth = accountRegistrationRequest.DateOfBirth;
                    }



                    if (accountRegistrationRequest.Gender != null)
                    {
                        if (accountRegistrationRequest.Gender.Contains("female"))
                        {
                            newApplicationUser.Gender = Gender.Female;
                        }
                    }


                    if (registrationDate != null)
                    {
                        newApplicationUser.RegistrationDate = registrationDate.Value;
                    }
                    else
                    {
                        newApplicationUser.RegistrationDate = DateTime.Now;
                    }

                    if (accountRegistrationRequest.MobileNumber != null)
                    {
                        newApplicationUser.PhoneNumber = accountRegistrationRequest.MobileNumber;
                    }

                    if (accountRegistrationRequest.Postcode != null)
                    {
                        newApplicationUser.Location = PostcodesService.Lookup(newApplicationUser.Postcode);
                    }


                    if (IsUserAuthenticated)
                    {
                        var result2 = await userManager.UpdateAsync(newApplicationUser);

                        if (result2.Succeeded)
                        {
                            return(Ok());
                        }

                        return(BadRequest(string.Join(", ", result2.Errors)));
                    }


                    var result = await userManager.CreateAsync(newApplicationUser, password);

                    if (result.Succeeded)
                    {
                        return(Ok());
                    }

                    return(BadRequest(string.Join(", ", result.Errors)));
                }

                string validationErrors = string.Join(",",
                                                      ModelState.Values.Where(E => E.Errors.Count > 0)
                                                      .SelectMany(E => E.Errors)
                                                      .Select(E => E.ErrorMessage)
                                                      .ToArray());

                return(BadRequest(validationErrors));
            }

            return(BadRequest("registration data is null."));
        }
Beispiel #6
0
        public async Task <IHttpActionResult> CreateRandomBusiness()
        {
            var business = new Business();


            // random business type.
            var businessType = db.BusinessTypes.OrderBy(r => Guid.NewGuid()).FirstOrDefault();

            // assign the business type id.
            business.BusinessTypeId = businessType.Id;

            var owner = db.Users.OrderBy(r => Guid.NewGuid()).FirstOrDefault();

            business.Name = owner.LastName + "'s " + businessType.Name;

            business.OpeningTimes = new List <BusinessOpeningTime>();
            business.OpeningTimes.Add(new BusinessOpeningTime
            {
                DayOfWeek   = DayOfWeek.Monday,
                OpeningTime = TimeSpan.FromHours(8),
                ClosingTime = TimeSpan.FromHours(18)
            });
            business.OpeningTimes.Add(new BusinessOpeningTime
            {
                DayOfWeek   = DayOfWeek.Tuesday,
                OpeningTime = TimeSpan.FromHours(8),
                ClosingTime = TimeSpan.FromHours(18)
            });
            business.OpeningTimes.Add(new BusinessOpeningTime
            {
                DayOfWeek   = DayOfWeek.Wednesday,
                OpeningTime = TimeSpan.FromHours(8),
                ClosingTime = TimeSpan.FromHours(18)
            });
            business.OpeningTimes.Add(new BusinessOpeningTime
            {
                DayOfWeek   = DayOfWeek.Thursday,
                OpeningTime = TimeSpan.FromHours(8),
                ClosingTime = TimeSpan.FromHours(18)
            });
            business.OpeningTimes.Add(new BusinessOpeningTime
            {
                DayOfWeek   = DayOfWeek.Friday,
                OpeningTime = TimeSpan.FromHours(8),
                ClosingTime = TimeSpan.FromHours(18)
            });
            business.OpeningTimes.Add(new BusinessOpeningTime
            {
                DayOfWeek   = DayOfWeek.Saturday,
                OpeningTime = TimeSpan.FromHours(8),
                ClosingTime = TimeSpan.FromHours(18)
            });
            business.OpeningTimes.Add(new BusinessOpeningTime
            {
                DayOfWeek   = DayOfWeek.Sunday,
                OpeningTime = TimeSpan.FromHours(10),
                ClosingTime = TimeSpan.FromHours(16)
            });

            //something.OrderBy(r => Guid.NewGuid()).Take(5)

            var randoms = new Random();

            var services = randoms.Next(1, 15);

            for (var i = 0; i < services; i++)
            {
                var isFree = randoms.NextDouble() >= 0.5;

                var price = isFree ? 0.0M : randoms.Next(0, 5000) / 100.0M;

                business.Services.Add(new Service
                {
                    Name        = $"Service {i + 1}",
                    Description = $"Radom Service {i + 1}",
                    Cost        = price,
                    Duration    = TimeSpan.FromMinutes(randoms.Next(0, 180))
                });
            }

            var d = RA();

            business.Users.Add(new BusinessUser {
                UserId = owner.Id, UserLevel = BusinessUserLevel.Owner
            });
            business.Postcode = d[9];
            business.Address  = string.Join(",\r\n", d);

            business.Location = PostcodesService.Lookup(business.Postcode);

            db.Businesses.Add(business);

            try
            {
                var a = await db.SaveChangesAsync();
            }
            catch (Exception exception)
            {
                throw;
            }


            return(Ok());
        }
Beispiel #7
0
        public async Task <IHttpActionResult> Register(BusinessRegistrationData businessRegistrationData)
        {
            try
            {
                // if the user is null or the user is not authenticated
                if (!IsUserAuthenticated)
                {
                    return(Content(HttpStatusCode.Unauthorized, "User must be logged in to create a business."));
                }


                // check that the model is valid.
                if (ModelState.IsValid)
                {
                    var newBusiness = new Business();

                    newBusiness.Name = businessRegistrationData.Name;

                    var businessType =
                        await db.BusinessTypes.FirstOrDefaultAsync(type => type.Name == businessRegistrationData.Type);

                    if (businessType == null)
                    {
                        return(Content(HttpStatusCode.BadRequest,
                                       $"The given business type {businessRegistrationData.Type} could not be found in the database"));
                    }

                    // set the business type id.
                    newBusiness.BusinessTypeId = businessType.Id;

                    newBusiness.Address = businessRegistrationData.GetAddressString();

                    newBusiness.Postcode = businessRegistrationData.Postcode;

                    newBusiness.Location = PostcodesService.Lookup(businessRegistrationData.Postcode);

                    AddBusinessOpeningTime(newBusiness, DayOfWeek.Monday, businessRegistrationData.OpeningTimeMonday,
                                           businessRegistrationData.ClosingTimeMonday);

                    AddBusinessOpeningTime(newBusiness, DayOfWeek.Tuesday, businessRegistrationData.OpeningTimeTuesday,
                                           businessRegistrationData.ClosingTimeTuesday);

                    AddBusinessOpeningTime(newBusiness, DayOfWeek.Wednesday, businessRegistrationData.OpeningTimeWednesday,
                                           businessRegistrationData.ClosingTimeWednesday);

                    AddBusinessOpeningTime(newBusiness, DayOfWeek.Thursday, businessRegistrationData.OpeningTimeThursday,
                                           businessRegistrationData.ClosingTimeThursday);

                    AddBusinessOpeningTime(newBusiness, DayOfWeek.Friday, businessRegistrationData.OpeningTimeFriday,
                                           businessRegistrationData.ClosingTimeFriday);

                    AddBusinessOpeningTime(newBusiness, DayOfWeek.Saturday, businessRegistrationData.OpeningTimeSaturday,
                                           businessRegistrationData.ClosingTimeSaturday);

                    AddBusinessOpeningTime(newBusiness, DayOfWeek.Sunday, businessRegistrationData.OpeningTimeSunday,
                                           businessRegistrationData.ClosingTimeSunday);

                    var ownerId = string.Empty;

                    newBusiness.PhoneNumber  = businessRegistrationData.ContactNumber;
                    newBusiness.FaxNumber    = businessRegistrationData.ContactFax;
                    newBusiness.EmailAddress = businessRegistrationData.ContactEmail;

                    // set the website.
                    newBusiness.Website = businessRegistrationData.Website;

                    if (!string.IsNullOrWhiteSpace(businessRegistrationData.OwnerEmailAddress))
                    {
                        // if not an administrator return a 403 error

                        var applicationUserStore = new ApplicationUserStore(db);

                        var applicationUser =
                            await applicationUserStore.FindByEmailAsync(businessRegistrationData.OwnerEmailAddress);

                        ownerId = applicationUser.Id;
                    }
                    else
                    {
                        if (!IsUserAuthenticated)
                        {
                            return(BadRequest("user bad"));
                        }

                        ownerId = UserId;
                    }
                    newBusiness.Users.Add(new BusinessUser {
                        UserId = ownerId, UserLevel = BusinessUserLevel.Owner
                    });

                    db.Businesses.Add(newBusiness);

                    await db.SaveChangesAsync();

                    return(Ok(ownerId));
                }

                return(InvalidModel());
            }
            catch (Exception exception)
            {
                return(Content(HttpStatusCode.BadRequest, $"Something happend {exception.Message}"));
            }
        }