public async Task <string> RedirectUrl(string url)
        {
            if (_legacyUrlRedirects.HasExpired())
            {
                var response = await _repository.GetRedirects();

                var redirects = response.Content as Redirects;
                _shortUrlRedirects.Redirects    = redirects.ShortUrlRedirects;
                _shortUrlRedirects.LastUpdated  = System.DateTime.Now;
                _legacyUrlRedirects.Redirects   = redirects.LegacyUrlRedirects;
                _legacyUrlRedirects.LastUpdated = System.DateTime.Now;
            }
            if (!DictionaryContainsBusinessId(_legacyUrlRedirects.Redirects, _businessId.ToString()))
            {
                return(string.Empty);
            }

            var businessIdLegacyUrlRedirects = _legacyUrlRedirects.Redirects[_businessId.ToString()];

            if (url.EndsWith("/"))
            {
                url = url.Substring(0, url.Length - 1);
            }

            return(businessIdLegacyUrlRedirects.ContainsKey(url)
                ? businessIdLegacyUrlRedirects[url]
                : GetWildcardShortUrlMatch(businessIdLegacyUrlRedirects, url));
        }
Beispiel #2
0
        public async Task Invoke(HttpContext context, BusinessId businessId)
        {
            var path = context.Request.Path;

            if (_shortUrlRedirects.HasExpired())
            {
                var response = await _repository.GetRedirects();

                var redirects = response.Content as Redirects;
                _shortUrlRedirects.Redirects    = redirects.ShortUrlRedirects;
                _shortUrlRedirects.LastUpdated  = System.DateTime.Now;
                _legacyUrlRedirects.Redirects   = redirects.LegacyUrlRedirects;
                _legacyUrlRedirects.LastUpdated = System.DateTime.Now;
            }

            if (_shortUrlRedirects.Redirects.ContainsKey(businessId.ToString()) && _shortUrlRedirects.Redirects[businessId.ToString()].ContainsKey(path))
            {
                var redirectTo = _shortUrlRedirects.Redirects[businessId.ToString()][path];
                _logger.LogInformation($"Short Url Redirecting from: {path}, to: {redirectTo}");
                context.Response.Redirect(redirectTo);
                context.Response.Headers["Cache-Control"] = "public, max-age=" + Cache.RedirectCacheDuration;
            }
            else
            {
                await _next.Invoke(context);
            }
        }
        public void ShouldSetBusinessIdIfBusinessIdIsInHeader()
        {
            var          context          = new DefaultHttpContext();
            const string businessIdString = "business-id";

            context.Request.Headers["BUSINESS-ID"] = businessIdString;
            _businessIdMiddleware.Invoke(context, _businessId);

            _businessId.ToString().Should().Be(businessIdString);
        }
        public async Task <IActionResult> Index(NewsroomViewModel model, [FromQuery] int page, [FromQuery] int pageSize)
        {
            if (model.DateFrom == null && model.DateTo == null && string.IsNullOrEmpty(model.DateRange))
            {
                if (ModelState["DateTo"] != null && ModelState["DateTo"].Errors.Count > 0)
                {
                    ModelState["DateTo"].Errors.Clear();
                }
                if (ModelState["DateFrom"] != null && ModelState["DateFrom"].Errors.Count > 0)
                {
                    ModelState["DateFrom"].Errors.Clear();
                }
            }

            var queries = new List <Query>();

            if (!string.IsNullOrEmpty(model.Tag))
            {
                queries.Add(new Query("tag", model.Tag));
            }
            if (!string.IsNullOrEmpty(model.Category))
            {
                queries.Add(new Query("Category", model.Category));
            }
            if (model.DateFrom.HasValue)
            {
                queries.Add(new Query("DateFrom", model.DateFrom.Value.ToString("yyyy-MM-dd")));
            }
            if (model.DateTo.HasValue)
            {
                queries.Add(new Query("DateTo", model.DateTo.Value.ToString("yyyy-MM-dd")));
            }

            var httpResponse = await _repository.Get <Newsroom>(queries : queries);

            if (!httpResponse.IsSuccessful())
            {
                return(httpResponse);
            }

            var newsRoom = httpResponse.Content as Newsroom;

            var urlSetting = _config.GetEmailAlertsNewSubscriberUrl(_businessId.ToString());

            model.AddQueryUrl(new QueryUrl(Url?.ActionContext.RouteData.Values, Request?.Query));
            _filteredUrl.SetQueryUrl(model.CurrentUrl);
            model.AddFilteredUrl(_filteredUrl);

            DoPagination(newsRoom, model, page, pageSize);

            model.AddNews(newsRoom);
            model.AddUrlSetting(urlSetting);

            return(View(model));
        }
 public GroupEmailBuilder(ILogger <GroupEmailBuilder> logger,
                          IHttpEmailClient emailClient,
                          IApplicationConfiguration configuration,
                          BusinessId businessId)
 {
     _logger        = logger;
     _configuration = configuration;
     _businessId    = businessId;
     _emailClient   = emailClient;
     _fromEmail     = _configuration.GetEmailEmailFrom(_businessId.ToString()).IsValid()
         ? _configuration.GetEmailEmailFrom(_businessId.ToString()).ToString()
         : string.Empty;
 }
 public Task <HttpStatusCode> SendImageViaEmail(IFormFile file, string groupName, string slug)
 {
     return(_emailClient.SendEmailToService(
                new EmailMessage(
                    $"A new image has been uploaded for the group {groupName} for approval",
                    $"A new image has been uploaded for the group {groupName} and is waiting for approval. <br /><br /> <a href='http://www.stockport.gov.uk/groups/{slug}'>Link to {groupName}</a>",
                    _configuration.GetEmailEmailFrom(_businessId.ToString()).ToString(),
                    _configuration.GetGroupSubmissionEmail(_businessId.ToString()).ToString(),
                    new List <IFormFile> {
         file
     }
                    )
                ));
 }
        public Task Invoke(HttpContext context, BusinessId businessId)
        {
            if (context.Request.Headers.TryGetValue("BUSINESS-ID", out StringValues idFromHeader))
            {
                businessId.SetId(idFromHeader);
                _logger.LogInformation($"BUSINESS-ID has been set to: {idFromHeader}");
            }
            else
            {
                // default to stockportgov if no businessid
                businessId.SetId(new StringValues("stockportgov"));
                // to run healthystockport locally, comment out the above line and uncomment line below
                //businessId.SetId(new StringValues("healthystockport"));
                context.Request.Headers.Add("BUSINESS-ID", businessId.ToString());

                if (context.Request.Path.HasValue &&
                    !context.Request.Path.Value.ToLower().Contains("/assets/") &&
                    !context.Request.Path.Value.ToLower().Contains("healthcheck"))
                {
                    _logger.LogInformation("BUSINESS-ID has not been set, setting to default");
                }
            }

            return(_next(context));
        }
Beispiel #8
0
        /// <summary>
        /// 转换成字符串
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendFormat("{0}{1}", BusinessId.ToString(), WebServiceConst.Separater_1);
            if (string.IsNullOrEmpty(ContractNo))
            {
                sb.AppendFormat("{0}{1}", "", WebServiceConst.Separater_1);
            }
            else
            {
                sb.AppendFormat("{0}{1}", ContractNo.ToString(), WebServiceConst.Separater_1);
            }

            if (string.IsNullOrEmpty(CustomerName))
            {
                sb.AppendFormat("{0}{1}", "", WebServiceConst.Separater_1);
            }
            else
            {
                sb.AppendFormat("{0}{1}", CustomerName.ToString(), WebServiceConst.Separater_1);
            }

            sb.AppendFormat("{0}{1}", RealLoanCapital.ToString(), WebServiceConst.Separater_1);
            sb.AppendFormat("{0}{1}", RefundAmt.ToString(), WebServiceConst.Separater_1);

            if (PayDate.HasValue)
            {
                sb.AppendFormat("{0}{1}", PayDate.Value.ToString("yyyy-MM-dd HH:mm:ss"), WebServiceConst.Separater_1);
            }
            else
            {
                sb.AppendFormat("{0}{1}", "", WebServiceConst.Separater_1);
            }

            if (ReceivedDate.HasValue)
            {
                sb.AppendFormat("{0}{1}", ReceivedDate.Value.ToString("yyyy-MM-dd HH:mm:ss"), WebServiceConst.Separater_1);
            }
            else
            {
                sb.AppendFormat("{0}{1}", "", WebServiceConst.Separater_1);
            }

            sb.AppendFormat("{0}{1}", PayType.ToString(), WebServiceConst.Separater_1);

            if (CancelTime.HasValue)
            {
                sb.Append(ReceivedDate.Value.ToString("yyyy-MM-dd HH:mm:ss"));
            }
            else
            {
                sb.Append("");
            }

            return(sb.ToString());
        }
Beispiel #9
0
        private Task <HttpStatusCode> SendEmailMessage(ContactUsDetails contactUsDetails)
        {
            var messageSubject = $"{contactUsDetails.Title} - {contactUsDetails.Subject}";

            _logger.LogDebug("Sending contact us form email");

            var fromEmail = _applicationConfiguration.GetEmailEmailFrom(_businessId.ToString()).IsValid()
                ? _applicationConfiguration.GetEmailEmailFrom(_businessId.ToString()).ToString()
                : string.Empty;

            return(_emailClient.SendEmailToService
                       (new EmailMessage(messageSubject,
                                         CreateMessageBody(contactUsDetails),
                                         fromEmail,
                                         contactUsDetails.ServiceEmail,
                                         contactUsDetails.Email,
                                         new List <IFormFile>())));
        }
        public virtual Dictionary <string, object> ToDictionary()
        {
            var dictionary = new Dictionary <string, object>
            {
                { "BusinessId", BusinessId.ToString() },
                { "BusinessName", BusinessName }
            };

            return(dictionary);
        }
Beispiel #11
0
        public async Task <IActionResult> Postcode(string query)
        {
            var urlSetting = _config.GetPostcodeSearchUrl(_businessId.ToString());

            if (urlSetting.IsValid())
            {
                var url = string.Concat(urlSetting, query);
                return(await Task.FromResult(Redirect(url)));
            }
            return(NotFound());
        }
        public async Task <IActionResult> Index()
        {
            var homepage = await _homepageService.GetHomepage();

            if (homepage == null)
            {
                return(new NotFoundResult());
            }

            var eventsFromApi = !string.IsNullOrEmpty(homepage.EventCategory) ? await _stockportApiEventsService.GetEventsByCategory(homepage.EventCategory) : new List <Event>();

            var homepageViewModel = new HomepageViewModel
            {
                HomepageContent = homepage,
                FeaturedEvent   = _businessId.ToString() != "healthystockport" ? await _eventsService.GetLatestFeaturedEventItem() : null,
                FeaturedNews    = _businessId.ToString() != "healthystockport" ? await _newsService.GetLatestNewsItem() : null,
                EventsFromApi   = eventsFromApi?.Take(3).ToList()
            };

            return(View(homepageViewModel));
        }
Beispiel #13
0
        public FileResult GetLogoImage()
        {
            var    folderpath   = ConfigurationManager.AppSettings["LogoImageFolder"].ToString();
            string imagename    = folderpath + "/" + "avatar.png";
            var    actualpath   = System.Web.HttpContext.Current.Server.MapPath(folderpath);
            var    searchstring = BusinessId.ToString();
            var    files        = Directory.GetFiles(actualpath, searchstring + ".*");

            if (files.Length > 0)
            {
                imagename = folderpath + "/" + Path.GetFileName(files[0]);
            }
            return(File(imagename, "image/jpg"));
        }
        public async Task <IActionResult> Index(string topicSlug)
        {
            var topicHttpResponse = await _repository.Get <Topic>(topicSlug);

            if (!topicHttpResponse.IsSuccessful())
            {
                return(topicHttpResponse);
            }

            var topic = topicHttpResponse.Content as Topic;

            var urlSetting = _config.GetEmailAlertsNewSubscriberUrl(_businessId.ToString());

            return(View(new TopicViewModel(topic, urlSetting.ToString())));
        }
        public async Task <IActionResult> Rss()
        {
            var httpResponse = await _repository.Get <EventResponse>();

            var host = Request != null && Request.Host.HasValue ? string.Concat(Request.IsHttps ? "https://" : "http://", Request.Host.Value, "/events/") : string.Empty;

            if (!httpResponse.IsSuccessful())
            {
                _logger.LogDebug("Rss: Http Response not sucessful");
                return(httpResponse);
            }

            var response            = httpResponse.Content as EventResponse;
            var emailFromAppSetting = _config.GetRssEmail(_businessId.ToString());
            var email = emailFromAppSetting.IsValid() ? emailFromAppSetting.ToString() : string.Empty;

            _logger.LogDebug("Rss: Creating News Feed");
            return(await Task.FromResult(Content(_rssFeedFactory.BuildRssFeed(response.Events, host, email), "application/rss+xml")));
        }
Beispiel #16
0
        public async Task SubmitAsync()
        {
            var success = await _siteService.CreateSiteAsync(new Site
            {
                BusinessId    = BusinessId,
                Name          = Name,
                AddressLine1  = AddressLine1,
                AddressLine2  = AddressLine2,
                PostCode      = PostCode,
                FirstName     = FirstName,
                SecondName    = SecondName,
                Email         = Email,
                ContactNumber = ContactNumber
            });

            if (success)
            {
                _navigationManager.NavigateTo($"/business-profile/{BusinessId.ToString()}");
            }
        }
        private List <Claim> GetClaims()
        {
            List <Claim> claims = new List <Claim>
            {
                new Claim(ClaimTypes.Name, BceidUserId),
                new Claim(ClaimTypes.Actor, "BusinessUser")
            };

            if (!string.IsNullOrEmpty(BceidDisplayName))
            {
                claims.Add(new Claim(ClaimTypes.Name, BceidDisplayName));
            }

            if (!string.IsNullOrEmpty(BceidEmail))
            {
                claims.Add(new Claim(ClaimTypes.Email, BceidEmail));
            }

            if (BusinessId != 0)
            {
                claims.Add(new Claim(UseridClaim, BusinessId.ToString()));
            }

            var permissions = GetActivePermissions()
                              .Select(p => new Claim(PermissionClaim, p.Code)).ToList();

            if (permissions.Any())
            {
                claims.AddRange(permissions);
            }

            var roles = GetActiveRoles()
                        .Select(r => new Claim(ClaimTypes.Role, r.Name)).ToList();

            if (roles.Any())
            {
                claims.AddRange(roles);
            }

            return(claims);
        }
        public virtual Task <HttpStatusCode> SendEmailAddNew(GroupSubmission groupSubmission)
        {
            var messageSubject = $"[Group] - {groupSubmission.Name}";

            _logger.LogInformation("Sending group submission form email");

            var attachments = new List <IFormFile>();

            if (groupSubmission.Image != null)
            {
                attachments.Add(groupSubmission.Image);
            }

            var emailBody = new GroupAdd
            {
                Name     = groupSubmission.Name,
                Location = groupSubmission.Address,
                Image    = groupSubmission.Image != null?FileHelper.GetFileNameFromPath(groupSubmission.Image) : "-",
                               Description        = groupSubmission.Description,
                               Email              = groupSubmission.Email,
                               Phone              = groupSubmission.PhoneNumber,
                               Website            = groupSubmission.Website,
                               DonationsNeeded    = groupSubmission.Donations,
                               Categories         = groupSubmission.CategoriesList,
                               VolunteeringText   = groupSubmission.Volunteering ? groupSubmission.VolunteeringText : "-",
                               VolunteeringNeeded = groupSubmission.Volunteering,
                               DonationsText      = groupSubmission.Donations ? groupSubmission.DonationsText : "-",
                               DonationUrl        = groupSubmission.DonationsUrl,
                               Facebook           = groupSubmission.Facebook,
                               Twitter            = groupSubmission.Twitter,
                               AgeRanges          = groupSubmission.AgeRanges.Where(o => o.IsSelected).Select(o => o.Name).ToList(),
                               Suitabilities      = groupSubmission.Suitabilities.Where(o => o.IsSelected).Select(o => o.Name).ToList()
            };

            return(_emailClient.SendEmailToService(new EmailMessage(messageSubject, _emailClient.GenerateEmailBodyFromHtml(emailBody),
                                                                    _fromEmail,
                                                                    _configuration.GetGroupSubmissionEmail(_businessId.ToString()).ToString(),
                                                                    groupSubmission.Email,
                                                                    attachments)));
        }
        public async Task <Healthcheck> Get()
        {
            Healthcheck healthcheck;
            var         httpResponse = await _httpMaker.Get(_urlGenerator.HealthcheckUrl(), new Dictionary <string, string> {
                { "Authorization", authenticationKey },
                { "X-ClientId", webAppClientId }
            });

            if (httpResponse != null)
            {
                healthcheck = BuildDependencyHealthcheck(httpResponse);
            }
            else
            {
                healthcheck = new UnavailableHealthcheck();
            }

            return(new Healthcheck(_appVersion, _businessId.ToString(), _sha, _featureToggles,
                                   new Dictionary <string, Healthcheck>()
            {
                { "contentApi", healthcheck }
            }, _environment, new List <RedisValueData>()));
        }
Beispiel #20
0
        public async Task <IViewComponentResult> InvokeAsync()
        {
            var googleAnalyticsCode = _config.GetGoogleAnalyticsCode(_businessId.ToString());

            return(await Task.FromResult(View(model : googleAnalyticsCode)));
        }
Beispiel #21
0
        public virtual Task <HttpStatusCode> SendEmailAddNew(EventSubmission eventSubmission)
        {
            var messageSubject = $"[Event date] - {eventSubmission.EventDate.Value.ToString("d MMMM yyyy")}, [Event] - {eventSubmission.Title}";

            _logger.LogInformation("Sending event submission form email");

            var attachments = new List <IFormFile>();

            if (eventSubmission.Image != null)
            {
                attachments.Add(eventSubmission.Image);
            }
            if (eventSubmission.Attachment != null)
            {
                attachments.Add(eventSubmission.Attachment);
            }

            var imagePath      = FileHelper.GetFileNameFromPath(eventSubmission.Image);
            var attachmentPath = FileHelper.GetFileNameFromPath(eventSubmission.Attachment);

            var emailBody = new EventAdd
            {
                Title          = eventSubmission.Title,
                EventDate      = eventSubmission.EventDate.HasValue ? ((DateTime)eventSubmission.EventDate).ToString("dddd dd MMMM yyyy") : "-",
                EndDate        = eventSubmission.EndDate.HasValue ? ((DateTime)eventSubmission.EndDate).ToString("dddd dd MMMM yyyy") : "-",
                StartTime      = eventSubmission.StartTime.HasValue ? ((DateTime)eventSubmission.StartTime).ToString("HH:mm") : "-",
                EndTime        = eventSubmission.EndTime.HasValue ? ((DateTime)eventSubmission.EndTime).ToString("HH:mm") : "-",
                Frequency      = !string.IsNullOrEmpty(eventSubmission.Frequency) ? eventSubmission.Frequency : "-",
                Fee            = !string.IsNullOrEmpty(eventSubmission.Fee) ? eventSubmission.Fee : "-",
                Location       = !string.IsNullOrEmpty(eventSubmission.Location) ? eventSubmission.Location : "-",
                SubmittedBy    = !string.IsNullOrEmpty(eventSubmission.SubmittedBy) ? eventSubmission.SubmittedBy : "-",
                Description    = !string.IsNullOrEmpty(eventSubmission.Description) ? eventSubmission.Description : "-",
                ImagePath      = !string.IsNullOrEmpty(imagePath) ? imagePath : "-",
                AttachmentPath = !string.IsNullOrEmpty(attachmentPath) ? attachmentPath : "-",
                SubmitterEmail = !string.IsNullOrEmpty(eventSubmission.SubmitterEmail) ? eventSubmission.SubmitterEmail : "-",
                Categories     = eventSubmission.CategoriesList,
                GroupName      = string.IsNullOrEmpty(eventSubmission.GroupName) ? string.Empty : $"Group name: {eventSubmission.GroupName}",
                Occurrences    = eventSubmission.Occurrences == 0 ? string.Empty : $"(occurs {eventSubmission.Occurrences} times)",
            };

            return(_emailClient.SendEmailToService(new EmailMessage(messageSubject, _emailClient.GenerateEmailBodyFromHtml(emailBody),
                                                                    _fromEmail,
                                                                    _configuration.GetEventSubmissionEmail(_businessId.ToString()).ToString(),
                                                                    eventSubmission.SubmitterEmail,
                                                                    attachments)));
        }
Beispiel #22
0
        public async Task <IViewComponentResult> InvokeAsync()
        {
            var shareIdSetting = _config.GetAddThisShareId(_businessId.ToString());

            return(await Task.FromResult(View(model : shareIdSetting)));
        }