Exemple #1
0
        public void SendResetPassword(UmbracoHelper umbraco, string email, string guid)
        {
            try
            {
                //logger.Info<EmailHelper>("Send Reset: {0} {1}", email, guid);

                string from     = Current.Configs.Settings().Content.NotificationEmailAddress;
                string baseURL  = HttpContext.Current.Request.Url.AbsoluteUri.Replace(HttpContext.Current.Request.Url.AbsolutePath, string.Empty);
                var    resetUrl = baseURL + umbraco.GetDictionaryValue("ForumAuthConstants.ResetUrl", "/reset").TrimEnd('/') + "/?resetGUID=" + guid;

                var messageBody = umbraco.GetDictionaryValue("Forum.ResetBody", $@"<h2>Password Reset</h2>
            <p>we have received a request to reset your password</p>
            <p><a href='{resetUrl}'>Reset your password</a></p>");

                MailMessage message = new MailMessage(from, email)
                {
                    Subject    = umbraco.GetDictionaryValue("Forum.ResetSubject", "Reset your password"),
                    IsBodyHtml = true,
                    Body       = messageBody
                };

                SmtpClient client = new SmtpClient();
                client.Send(message);
            }
            catch (Exception ex)
            {
                logger.Error <ForumEmailHelper>("Error {0}", ex.Message);
            }
        }
Exemple #2
0
        public void SendVerifyAccount(UmbracoHelper umbraco, string email, string guid)
        {
            try
            {
                //logger.Info<ForumEmailHelper>("Send Verify: {0} {1}", email, guid);

                string from     = Current.Configs.Settings().Content.NotificationEmailAddress;
                string baseURL  = HttpContext.Current.Request.Url.AbsoluteUri.Replace(HttpContext.Current.Request.Url.AbsolutePath, string.Empty);
                var    resetUrl = baseURL + umbraco.GetDictionaryValue("ForumAuthConstants.VerifyUrl", "/verify").TrimEnd('/') + "/?verifyGUID=" + guid;

                var messageBody = umbraco.GetDictionaryValue("Forum.VerifyBody", $@"<h2>Verifiy your account</h2>
            <p>in order to use your account, you first need to verifiy your email address using the link below.</p>
            <p><a href='{resetUrl}'>Verify your account</a></p>");


                MailMessage message = new MailMessage(from, email)
                {
                    Subject    = umbraco.GetDictionaryValue("Forum.VerifySubject", "Verifiy your account"),
                    IsBodyHtml = true,
                    Body       = messageBody
                };

                using (var client = new SmtpClient())
                {
                    client.Send(message);// Your code here.
                }
            }
            catch (Exception ex)
            {
                logger.Error <ForumEmailHelper>("Problems sending verify email: {0}", ex.ToString());
            }
        }
Exemple #3
0
        public ContactFormViewModel GetViewModel(IPublishedContent componentContent)
        {
            var viewModel = new ContactFormViewModel()
            {
                NameLabel         = _umbracoHelper.GetDictionaryValue(DictionaryKeys.FormLabels.Name),
                EmailLabel        = _umbracoHelper.GetDictionaryValue(DictionaryKeys.FormLabels.Email),
                PhoneLabel        = _umbracoHelper.GetDictionaryValue(DictionaryKeys.FormLabels.Phone),
                MessageLabel      = _umbracoHelper.GetDictionaryValue(DictionaryKeys.FormLabels.Message),
                SubmitButtonLabel = _umbracoHelper.GetDictionaryValue(DictionaryKeys.FormLabels.SubmitButton)
            };

            if (componentContent == null)
            {
                return(viewModel);
            }

            PopulateComponentBaseProperties(viewModel, componentContent);

            viewModel.Title = componentContent.GetPropertyValue <string>(PropertyAliases.ContactForm.Title);
            viewModel.Copy  = componentContent.GetPropertyValue <string>(PropertyAliases.ContactForm.Copy);
            viewModel.LocationParameterString = componentContent
                                                .GetPropertyValue <string>(PropertyAliases.ContactForm.LocationParameterString);

            return(viewModel);
        }
Exemple #4
0
        public ProfileResponse SubmitProfile(ProfileViewModel model)
        {
            try
            {
                var currentUserEmail = CurrentUserEmail();
                var errors           = ValidateUser(currentUserEmail, model.SelectedRegions, model.Agreements, isNew: false);
                if (errors.Any())
                {
                    return new ProfileResponse
                           {
                               IsError = true,
                               ShouldDisplayMessage = true,
                               Message          = _umbracoHelper.GetDictionaryValue("Profile.Submit.Failure"),
                               ValidationErrors = errors
                           }
                }
                ;

                var user = _userRepository.GetUserBy(x => x.UserEmail == currentUserEmail);
                _mappingService.Map(model, user);

                if (!string.IsNullOrWhiteSpace(model.UserPassword))
                {
                    user.UserPassword = _hashingService.Hash(model.UserPassword);
                }

                _userRepository.Update(user, model.SelectedRegions, model.Agreements);
                _eventBus.Send(new AccountModifiedEvent {
                    UserId = user.Id, UserOldEmail = currentUserEmail
                });

                return(new ProfileResponse
                {
                    IsError = false,
                    Message = _umbracoHelper.GetDictionaryValue("Profile.Submit.Success"),
                    ShouldDisplayMessage = true
                });
            }
            catch (Exception exception)
            {
                Log.Error("Error during submitting profile", exception);

                return(new ProfileResponse
                {
                    IsError = true,
                    Message = exception.Message,
                    ShouldDisplayMessage = true
                });
            }
        }
Exemple #5
0
        private void LoadSettings()
        {
            //Get user-defined global settings

            GlobalRandomRelatedNumber = (_currPage.RandomRelatedNumber <= 0)?3:_currPage.RandomRelatedNumber;

            GlobalDateFormat = (string.IsNullOrEmpty(_currPage.DateFormat)) ? "dd/MM/yyyy" : _currPage.DateFormat;

            //Get label for "All" category menu option
            _allOptionLabel = string.IsNullOrEmpty(_currPage.AllOptionLabel)? _umbHelper.GetDictionaryValue("Theme.Gallery.All").ToString() : _currPage.AllOptionLabel;

            //See if there are any categories defined at all
            _hasCategories = _currPage.Descendant <FolderGenericCategories>().HasChildren <DGenericCategoryItem>();

            //Get number of columns
            _noOfCols = _currPage.Columns <= 0 ? 2 : _currPage.Columns;

            //Decide if masonry or grid
            Masonry = _currPage.Masonry;

            //Are images spaced?
            Spacing = _currPage.Spacing;

            //Get image upscaling
            UpscaleImages = _currPage.GetPropertyValue <bool>("upscaleImages", false);

            //Wide page
            Wide = _currPage.Wide;

            //Show counters
            ShowItemCount = _currPage.ShowItemCount;
        }
        public override object ProcessValue()
        {
            var pageContext = (PaginationContext)Context;
            var pageNumber  = pageContext.PageNumber;
            var pageSize    = pageContext.PageSize;
            var items       = GetNews().ToList();
            var totalItems  = items.Count;
            var totalPages  = (long)Math.Ceiling(totalItems / (decimal)pageSize);

            pageNumber = Math.Max(1, Math.Min(pageNumber, totalPages));

            var pagedItems = items
                             .Skip((int)(pageNumber - 1) * pageSize)
                             .Take(pageSize)
                             .As <NewsExtract>();

            return(new PagedCollection <NewsExtract>
            {
                CurrentPage = pageNumber,
                PageSize = pageSize,
                TotalItems = totalItems,
                TotalPages = totalPages,
                Items = pagedItems,
                PageLabel = _helper.GetDictionaryValue(StaticValues.Dictionary.News.PageLabel)
            });
        }
Exemple #7
0
        // Gets a dictionary value with a fallback
        public static string GetDictionaryValue(string key, string fallback)
        {
            UmbracoHelper uHelper = new UmbracoHelper(UmbracoContext.Current);
            var           value   = uHelper.GetDictionaryValue(key);

            return(!string.IsNullOrEmpty(value)
                ? value
                : fallback);
        }
        /// <summary>
        /// 数字文字列から日付文字列を取得する
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        public static IHtmlString BreadCrumbDateFormat(this HtmlHelper helper, string dateNumber)
        {
            try
            {
                var umbracoHelper = new UmbracoHelper(UmbracoContext.Current);
                var result        = string.Empty;
                int dateInt;
                if (!int.TryParse(dateNumber, out dateInt))
                {
                    return(new HtmlString(string.Empty));
                }
                switch (dateNumber.Length)
                {
                case (4):
                    result = string.Format(
                        umbracoHelper.GetDictionaryValue("BreadCrumbYear"),
                        new DateTime(int.Parse(dateNumber.Substring(0, 4)), 1, 1));
                    break;

                case (6):
                    result = string.Format(
                        umbracoHelper.GetDictionaryValue("BreadCrumbMonth"),
                        new DateTime(int.Parse(dateNumber.Substring(0, 4)), int.Parse(dateNumber.Substring(4, 2)), 1));
                    break;

                case (8):
                    result = string.Format(
                        umbracoHelper.GetDictionaryValue("BreadCrumbDay"),
                        new DateTime(int.Parse(dateNumber.Substring(0, 4)), int.Parse(dateNumber.Substring(4, 2)), int.Parse(dateNumber.Substring(6, 2))));
                    break;

                default:
                    break;
                }

                return(new HtmlString(result));
            }
            catch
            {
                return(new HtmlString(string.Empty));
            }
        }
        public ResultModel ValidateContactForm(ContactFormViewModel contactFormViewModel)
        {
            var resultModel = new ResultModel()
            {
                Message = _umbracoHelper.GetDictionaryValue(DictionaryKeys.ResultMessages.ContactDefault)
            };

            if (contactFormViewModel == null)
            {
                return(resultModel);
            }

            if (contactFormViewModel.Name.IsNullOrWhiteSpace())
            {
                resultModel.Message = _umbracoHelper.GetDictionaryValue(DictionaryKeys.ResultMessages.ContactNameEmpty);
                return(resultModel);
            }

            if (contactFormViewModel.Email.IsNullOrWhiteSpace())
            {
                resultModel.Message = _umbracoHelper.GetDictionaryValue(DictionaryKeys.ResultMessages.ContactEmailEmpty);
                return(resultModel);
            }

            if (!IsEmailValidFormat(contactFormViewModel.Email))
            {
                resultModel.Message = _umbracoHelper.GetDictionaryValue(DictionaryKeys.ResultMessages.ContactEmailInvalid);
                return(resultModel);
            }

            if (contactFormViewModel.Message.IsNullOrWhiteSpace())
            {
                resultModel.Message = _umbracoHelper.GetDictionaryValue(DictionaryKeys.ResultMessages.ContactMessageEmpty);
                return(resultModel);
            }

            resultModel.IsSuccess = true;
            return(resultModel);
        }
Exemple #10
0
        /// <summary>
        /// Metorda zwracająca klasę zawierającą elementy wyświetlane na stronie wszytskich ofert regionalnych
        /// </summary>
        /// <param name="model">Obiekt klasy RegionalOfferBoxViewModel</param>
        /// <returns>Gotowy model do wyświetlenia na stronie wszystkich artykułów</returns>
        public RegionalOfferBoxViewModel GetRegionalArticleBoxesModel(RegionalOfferBoxViewModel model)
        {
            var _offersNode = _umbracoHelper.TypedContent(model.CurrentUmbracoPageId);

            var _articleList = _offersNode.Children.Where("Visible").Select(q => new ArticleWithFilter(q));

            model.DisplayCount = new RegionalOffers(_offersNode).DisplayCount;

            #region Pobranie filtrów z bazy danych
            //Pobranie aktywnych filtrów z bazy danych
            var _regionFilterItemsFromDB = _dbService.GetAll <RegionDB>("PolRegioRegion", q => q.IsEnabled);

            model.RegionFilter = _regionFilterItemsFromDB.Where(q => q.Id != int.Parse(RegionVariables.all_poland_region_id)).Select(q => new FilterItem()
            {
                Id = q.Id, DisplayText = _umbracoHelper.GetDictionaryValue(q.DictionaryKey)
            }).ToList();
            model.RegionFilter.Insert(0, new FilterItem()
            {
                Id = 0, DisplayText = _umbracoHelper.GetDictionaryValue("News.Placeholder.AllRegions")
            });

            var _filterModel = new NewsFilterStateViewModel()
            {
                NewsRegionFiltr = model.SelectedRegionId
            };
            CookiesExtensions.CreateCookie(CookieVariables.OffersFilterCookie, StringExtensions.Base64Encode(JsonConvert.SerializeObject(_filterModel)));

            #endregion
            if (model.SelectedRegionId != 0)
            {
                _articleList = _articleList.Where(q => q.RegionFiltr.SavedValue != null && JsonConvert.DeserializeObject <IEnumerable <NuPickersSqlDropDownPicker> >(q.RegionFiltr.SavedValue.ToString()).Any(c => c.Key == model.SelectedRegionId.ToString()));
            }

            model.AllNewsCount = _articleList.Count();
            model.ArticleList  = _articleList.Take(model.DisplayCount).Select(q => new OfferBoxModel(q));

            return(model);
        }
        public List <KeyValuePair <string, string> > GetAllRegions()
        {
            var query             = new Sql().Select("*").From("polregioregion");
            var regionsFromDb     = _dbContext.Database.Fetch <RegionDB>(query);
            var regionsDictionary = regionsFromDb.ToDictionary(
                x => x.Id.ToString(),
                x => _umbracoHelper.GetDictionaryValue(x.DictionaryKey));

            var regions = regionsDictionary
                          .Where(x => !string.IsNullOrWhiteSpace(x.Value))
                          .OrderBy(x => x.Key)
                          .ToList();

            return(regions);
        }
Exemple #12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ConfigService"/> class.
        /// </summary>
        /// <exception cref="NullReferenceException">
        /// Throws if app setting Webpack:DevServerRoot is empty when Webpack:UseDevServer is enabled
        /// </exception>
        public ConfigService()
        {
            registerUrl = new Lazy <string>(GetRegisterUrl);

            if (ConfigurationManager.AppSettings.AllKeys.Contains("Webpack:UseDevServer"))
            {
                var webpackDevserver = ConfigurationManager.AppSettings["Webpack:UseDevServer"].TryConvertTo <bool>();
                if (webpackDevserver.Success)
                {
                    UseWebpackDevServer = webpackDevserver.Result;
                }

                if (ConfigurationManager.AppSettings.AllKeys.Contains("Webpack:DevServerRoot"))
                {
                    WebpackDevServerRoot = ConfigurationManager.AppSettings["Webpack:DevServerRoot"];

                    if (UseWebpackDevServer && string.IsNullOrEmpty(WebpackDevServerRoot))
                    {
                        throw new NullReferenceException(
                                  "App setting Webpack:DevServerRoot should not be empty when Webpack:UseDevServer is enabled!");
                    }
                }
            }

            // Get and set the page specific configurations.
            if (UmbracoContext.Current != null && UmbracoContext.Current.PageId.HasValue)
            {
                var helper = new UmbracoHelper(UmbracoContext.Current);
                MembersEmailConfirmationSubject = helper.GetDictionaryValue(
                    "Members.EmailConfirmationSubject",
                    "Members.EmailConfirmationSubject");
                MembersEmailForgotPasswordSubject = helper.GetDictionaryValue(
                    "Members.EmailForgotPasswordSubject",
                    "Members.EmailForgotPasswordSubject");
            }
        }
Exemple #13
0
        private object PopulateDictionary <Tdict>(CultureInfo culture) where Tdict : DictionaryBase
        {
            UmbracoHelper h     = UmbracoContext.Current == null ? new UmbracoHelper() : new UmbracoHelper(UmbracoContext.Current);
            var           dict  = Activator.CreateInstance <Tdict>();
            var           attr  = typeof(Tdict).GetCodeFirstAttribute <DictionaryAttribute>();
            var           props = typeof(Tdict).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance).Where(x => x.GetCodeFirstAttribute <ItemAttribute>() != null);

            foreach (var prop in props)
            {
                var key         = prop.GetCodeFirstAttribute <ItemAttribute>();
                var completeKey = string.Format("{0}_{1}", attr.DictionaryName, key.Key);
                prop.SetValue(dict, h.GetDictionaryValue(completeKey) ?? string.Empty);
            }
            return(dict);
        }
        public string GetTranslation(string label, string lang)
        {
            if (!CultureInfo.GetCultures(CultureTypes.AllCultures).Any(x => x.TwoLetterISOLanguageName == lang))
            {
                return(string.Empty);
            }

            var cultureInfo = new CultureInfo(lang);

            Thread.CurrentThread.CurrentCulture   = cultureInfo;
            Thread.CurrentThread.CurrentUICulture = cultureInfo;

            UmbracoHelper helper = new UmbracoHelper(UmbracoContext.Current);

            return(helper.GetDictionaryValue(label));
        }
    string GetEmailTemplate(string template, string dictionaryString, string postTitle, string body, string author, string threadUrl, bool newPost)
    {
        var umbHelper = new UmbracoHelper(UmbracoContext.Current);

        var dictionaryTemplate = umbHelper.GetDictionaryValue(dictionaryString);
        if ( !string.IsNullOrWhiteSpace(dictionaryTemplate)) {
            template = dictionaryTemplate;
        }

        Dictionary<string, string> parameters = new Dictionary<string, string>();
        parameters.Add("{{author}}", author);
        parameters.Add("{{postTitle}}", postTitle);
        parameters.Add("{{body}}", body);
        parameters.Add("{{threadUrl}}", threadUrl);
        parameters.Add("{{newOld}}", newPost ? "New" : "Updated");

        return template.ReplaceMany(parameters);;
    }
Exemple #16
0
        /// <summary>
        /// 翻訳辞書を使い公開日付のフォーマットを行う
        /// </summary>
        /// <param name="content">IPublishedContent</param>
        /// <param name="alias">日付パラメータのエイリアス</param>
        /// <param name="dictionalyKey">DictionalyのKey</param>
        /// <returns>IHtmlString</returns>
        public static IHtmlString DictionalyDateFormat(this HtmlHelper helper, IPublishedContent content, string alias, string dictionalyKey = "DateFormat")
        {
            var umbHelper = new UmbracoHelper(UmbracoContext.Current);

            try
            {
                return(new HtmlString(
                           string.Format(
                               umbHelper.GetDictionaryValue(dictionalyKey),
                               content.GetPropertyValue <DateTime>(alias)
                               )
                           ));
            }
            catch
            {
                return(new HtmlString(string.Empty));
            }
        }
        public ActionResult Submit(string name, string email, string phone, string message)
        {
            var contactFormViewModel = new ContactFormViewModel()
            {
                Name    = name,
                Email   = email,
                Phone   = phone,
                Message = message
            };

            var contactFormValidationResult = _contactService.ValidateContactForm(contactFormViewModel);

            if (!contactFormValidationResult.IsSuccess)
            {
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                if (Request.IsAjaxRequest())
                {
                    return(Json(new
                    {
                        success = false,
                        message = contactFormValidationResult.Message
                    }));
                }

                //set param
                return(Redirect("/"));
            }

            _emailService.Contact(contactFormViewModel).SendAsync().ConfigureAwait(true);
            _emailService.ContactConfirmation(contactFormViewModel).SendAsync().ConfigureAwait(true);
            Response.StatusCode = (int)HttpStatusCode.OK;

            if (Request.IsAjaxRequest())
            {
                return(Json(new {
                    success = true,
                    message = _umbracoHelper.GetDictionaryValue(DictionaryKeys.ResultMessages.ContactSubmitSuccess)
                }));
            }

            //set param
            return(Redirect("/"));
        }
Exemple #18
0
        internal static Task SendMailContactUs(UmbracoHelper umbracoHelper, IContent newContactRequest, IPublishedContent website, string lang)
        {
            var emailTemplate = GetEmailTeplate(Constants.ContactUsRequestTemplate);
            var body          = new StringBuilder();
            var service       = umbracoHelper.GetDictionaryValue(umbracoHelper.GetPreValueAsString(newContactRequest.GetValue <int>("contactUsServices")));

            body.AppendLine(emailTemplate.EmailTemplateEmailBody.ToString());
            body.Replace(ContactUsName, newContactRequest.GetValue <string>("contactUsName"))
            .Replace(ContactUsPhone, newContactRequest.GetValue <string>("contactUsPhone"))
            .Replace(ContactUsSubject, newContactRequest.GetValue <string>("contactUsSubject"))
            .Replace(ContactUsEmail, newContactRequest.GetValue <string>("contactUsEmail"))
            .Replace(ContactUsMessage, newContactRequest.GetValue <string>("contactUsMessage"))
            .Replace(ContactUsService, service)
            .Replace(ContactUsWebsite, newContactRequest.GetValue <string>("contactUsWebsite"))
            .Replace(ContactUsLang, newContactRequest.GetValue <string>("contactUsLanguage"));

            return(SendGridMailForTemplate(emailTemplate, body.ToString(),
                                           subject: emailTemplate.EmailTemplateSubject.Replace(ContactUsService, service)));
        }
    string GetEmailTemplate(string template, string dictionaryString, string postTitle, string body, string author, string threadUrl, bool newPost)
    {
        var umbHelper = new UmbracoHelper(UmbracoContext.Current);

        var dictionaryTemplate = umbHelper.GetDictionaryValue(dictionaryString);

        if (!string.IsNullOrWhiteSpace(dictionaryTemplate))
        {
            template = dictionaryTemplate;
        }

        Dictionary <string, string> parameters = new Dictionary <string, string>();

        parameters.Add("{{author}}", author);
        parameters.Add("{{postTitle}}", postTitle);
        parameters.Add("{{body}}", body);
        parameters.Add("{{threadUrl}}", threadUrl);
        parameters.Add("{{newOld}}", newPost ? "New" : "Updated");

        return(template.ReplaceMany(parameters));;
    }
Exemple #20
0
 protected virtual string LookupDictionaryValue(string dictKey, string defaultValue)
 {
     if (GlobalDictionary.ContainsKey(dictKey))
     {
         var value = UmbracoHelper.GetDictionaryValue(dictKey);
         if (!string.IsNullOrEmpty(value))
         {
             return(value);
         }
         return(defaultValue);
     }
     else
     {
         return(defaultValue);
     }
     //if (umbraco.cms.businesslogic.Dictionary.DictionaryItem.hasKey(dictKey))
     //{
     //    return library.GetDictionaryItem(dictKey);
     //}
     //return defaultValue;
 }
Exemple #21
0
        /// <summary>
        /// This method is terribly overloaded:
        /// </summary>
        /// <param name="umbraco"></param>
        /// <param name="keyOrFallback"></param>
        /// <param name="fallbackOrFirstFormatArg"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        public static string GetCachedDictionaryValueOrFallback(this UmbracoHelper umbraco,

                                                                string key,
                                                                string altText,
                                                                params object[] args)
        {
            var cacheKey = string.Concat("PinkDictionary_",
                                         key,
                                         "_",
                                         altText);

            var result = ApplicationContext.Current.ApplicationCache.RuntimeCache
                         .GetCacheItem(cacheKey,
                                       () => umbraco.GetDictionaryValue(key, altText))
                         .ToString();

            if (args != null && args.Length > 0)
            {
                result = string.Format(result, args);
            }

            return(result);
        }
        public string GetDictionaryValue(string name)
        {
            var umbracoHelper = new UmbracoHelper();

            return(umbracoHelper.GetDictionaryValue(name));
        }
Exemple #23
0
 public string GetDictionaryValue(string key) => UmbracoHelper.GetDictionaryValue(key);
Exemple #24
0
        public string GetDictionaryValue(UmbracoHelper umbraco, string key, params string[] defaultValues)
        {
            var result = umbraco.GetDictionaryValue(key);
               if (!string.IsNullOrWhiteSpace(result))
               return result;

               var languages = _localizationService.GetAllLanguages().OrderBy(x=>x.Id).ToArray();

               AddDictionaryItem(key,defaultValues,languages);

               return umbraco.GetDictionaryValue(key);
        }
Exemple #25
0
        public LocationModel(
            IPublishedContent content,
            IPublishedContent recommendationRepository,
            IContentService contentService,
            bool isDetails)
            : base(content)
        {
            if (content == null)
            {
                throw new ArgumentNullException("content");
            }

            if (contentService == null)
            {
                throw new ArgumentNullException("contentService");
            }

            if (recommendationRepository == null)
            {
                throw new ArgumentException("recommendationRepository");
            }

            this.Tags               = new List <string>();
            this.Categories         = new List <string>();
            this.IsDetails          = isDetails;
            this.GeoLocation        = content.GetPropertyValue <string>(Constants.Location.Properties.GEO_LOCATION);
            this.Address            = content.GetPropertyValue <string>(Constants.Location.Properties.ADDRESS);
            this.Openings           = content.GetPropertyValue <OpeningHoursModel>(Constants.Location.Properties.OPENING_HOURS);
            this.Image              = content.GetCropUrl(Constants.Location.Properties.IMAGE, Constants.Crop.LOCATION_IMAGE);
            this.FacebookImage      = content.GetCropUrl(Constants.Location.Properties.IMAGE, Constants.Crop.FACEBOOK_IMAGE);
            this.Url                = content.GetPropertyValue <string>(Constants.Location.Properties.URL);
            this.Phone              = content.GetPropertyValue <string>(Constants.Location.Properties.PHONE_NUMBER);
            this.Email              = content.GetPropertyValue <string>(Constants.Location.Properties.EMAIL);
            this.HashTags           = content.GetPropertyValue <string>(Constants.Location.Properties.HASHTAGS);
            this.Title              = content.GetPropertyValue <string>(Constants.Location.Properties.TITLE);
            this.WriterName         = content.GetPropertyValue <string>(Constants.Location.Properties.WRITER);
            this.ShortDescription   = content.GetPropertyValue <string>(this.ShortDescriptionProperty);
            this.LongDescription    = content.GetPropertyValue <string>(this.LongDescriptionProperty);
            this.PlacesToGoin2015   = content.GetPropertyValue <bool>(Constants.Location.Properties.PLACES_TO_GO_IN_2015);
            this.PlacesToGoIn2016   = content.GetPropertyValue <bool>(Constants.Location.Properties.PUBLISHED);
            this.FromRecommendation = content.GetPropertyValue <bool>(Constants.Location.Properties.FROM_RECOMMENDATION);
            this.Fotograf           = content.GetPropertyValue <string>(Constants.Location.Properties.FOTOGRAF);
            this.FotografURL        = content.GetPropertyValue <string>(Constants.Location.Properties.FOTOGRAF_URL);
            this.Created            = content.CreateDate;

            this.Id    = content.Id;
            this.OldId = content.GetPropertyValue <int>(Constants.Location.Properties.OLD_ID);

            this.TimesRecommended = recommendationRepository.Children(x => x.IsVisible() && x.GetPropertyValue <int>(Constants.Recommendation.Properties.LOCATION) == this.Id).Count();

            string categories = content.GetPropertyValue <string>(Constants.Location.Properties.CATEGORIES);

            if (categories != null)
            {
                this.Categories.AddRange(categories.Split(','));
            }

            string tags = content.GetPropertyValue <string>(Constants.Location.Properties.TAGS);

            if (tags != null)
            {
                this.Tags.AddRange(tags.Split(','));
            }

            IContent writer = contentService.GetById(content.GetPropertyValue <int>(Constants.Location.Properties.WRITER));

            if (writer != null)
            {
                this.WriterName = writer.GetValue <string>(Constants.Writer.Properties.NAME);
                this.WriterId   = writer.Id;
            }

            IContent translator = contentService.GetById(content.GetPropertyValue <int>(Constants.Location.Properties.TRANSLATOR));

            if (translator != null)
            {
                this.TranslatorName = translator.GetValue <string>(Constants.Writer.Properties.NAME);
                this.TranslatorId   = translator.Id;
            }

            UmbracoHelper helper = new UmbracoHelper(UmbracoContext.Current);

            if (this.Openings != null)
            {
                List <GroupOpeningHours> openingHours = new List <GroupOpeningHours>();

                openingHours.Add(new GroupOpeningHours(helper.GetDictionaryValue("Man"), this.Openings.Monday));
                openingHours.Add(new GroupOpeningHours(helper.GetDictionaryValue("Tir"), this.Openings.Tuesday));
                openingHours.Add(new GroupOpeningHours(helper.GetDictionaryValue("Ons"), this.Openings.Wednesday));
                openingHours.Add(new GroupOpeningHours(helper.GetDictionaryValue("Tor"), this.Openings.Thursday));
                openingHours.Add(new GroupOpeningHours(helper.GetDictionaryValue("Fre"), this.Openings.Friday));
                openingHours.Add(new GroupOpeningHours(helper.GetDictionaryValue("Lør"), this.Openings.Saturday));
                openingHours.Add(new GroupOpeningHours(helper.GetDictionaryValue("Søn"), this.Openings.Sunday));


                SimpleOpeningHours = new List <KeyValuePair <string, string> >();

                string fromDay = "";
                for (int i = 0; i < openingHours.Count; i++)
                {
                    var    openingHour  = openingHours[i];
                    string currentHours = string.Format("{0} - {1}", openingHour.Date.From, openingHour.Date.Till);

                    if ("-".Equals(currentHours.Trim()))
                    {
                        currentHours = helper.GetDictionaryValue("Lukket");
                    }

                    if (SimpleOpeningHours.Count > 0 && SimpleOpeningHours[SimpleOpeningHours.Count - 1].Value == currentHours)
                    {
                        SimpleOpeningHours.RemoveAt(SimpleOpeningHours.Count - 1);
                        SimpleOpeningHours.Add(new KeyValuePair <string, string>(string.Format("{0} - {1}", fromDay, openingHour.Day), currentHours));
                    }
                    else
                    {
                        fromDay = openingHour.Day;
                        SimpleOpeningHours.Add(new KeyValuePair <string, string>(fromDay, currentHours));
                    }
                }
            }
        }
Exemple #26
0
        /// <summary>
        /// Creates an Item with a publishedContent item in order to properly recurse and return the value.
        /// </summary>
        /// <param name="publishedContent"></param>
        /// <param name="elements"></param>
        /// <param name="attributes"></param>
        /// <remarks>
        /// THIS ENTIRE CLASS WILL BECOME LEGACY, THE FIELD RENDERING NEEDS TO BE REPLACES SO THAT IS WHY THIS
        /// CTOR IS INTERNAL.
        /// </remarks>
        internal item(IPublishedContent publishedContent, IDictionary elements, IDictionary attributes)
        {
            _fieldName = FindAttribute(attributes, "field");

            if (_fieldName.StartsWith("#"))
            {
                var umbHelper = new UmbracoHelper(Current.UmbracoContext, Current.Services);

                _fieldContent = umbHelper.GetDictionaryValue(_fieldName.Substring(1, _fieldName.Length - 1));
            }
            else
            {
                // Loop through XML children we need to find the fields recursive
                var recursive = FindAttribute(attributes, "recursive") == "true";

                if (publishedContent == null)
                {
                    if (recursive)
                    {
                        var recursiveVal = GetRecursiveValueLegacy(elements);
                        _fieldContent = recursiveVal.IsNullOrWhiteSpace() ? _fieldContent : recursiveVal;
                    }
                }

                //check for published content and get its value using that
                if (publishedContent != null && (publishedContent.HasProperty(_fieldName) || recursive))
                {
                    var pval = publishedContent.Value(_fieldName, fallback: Fallback.ToAncestors);
                    var rval = pval == null ? string.Empty : pval.ToString();
                    _fieldContent = rval.IsNullOrWhiteSpace() ? _fieldContent : rval;
                }
                else
                {
                    //get the vaue the legacy way (this will not parse locallinks, etc... since that is handled with ipublishedcontent)
                    var elt = elements[_fieldName];
                    if (elt != null && string.IsNullOrEmpty(elt.ToString()) == false)
                    {
                        _fieldContent = elt.ToString().Trim();
                    }
                }

                //now we check if the value is still empty and if so we'll check useIfEmpty
                if (string.IsNullOrEmpty(_fieldContent))
                {
                    var altFieldName = FindAttribute(attributes, "useIfEmpty");
                    if (string.IsNullOrEmpty(altFieldName) == false)
                    {
                        if (publishedContent != null && (publishedContent.HasProperty(altFieldName) || recursive))
                        {
                            var pval = publishedContent.Value(altFieldName, fallback: Fallback.ToAncestors);
                            var rval = pval == null ? string.Empty : pval.ToString();
                            _fieldContent = rval.IsNullOrWhiteSpace() ? _fieldContent : rval;
                        }
                        else
                        {
                            //get the vaue the legacy way (this will not parse locallinks, etc... since that is handled with ipublishedcontent)
                            var elt = elements[altFieldName];
                            if (elt != null && string.IsNullOrEmpty(elt.ToString()) == false)
                            {
                                _fieldContent = elt.ToString().Trim();
                            }
                        }
                    }
                }
            }

            ParseItem(attributes);
        }
Exemple #27
0
        /// <summary>
        /// Metorda zwracająca klasę zawierającą elementy wyświetlane na stronie wszytskich postępowań o sprzedaży
        /// </summary>
        /// <param name="model">Obiekt klasy AdvertisingOfSalesViewModel</param>
        /// <returns>Gotowy model do wyświetlenia na stronie wszystkich postępowań o sprzedaży</returns>
        public AdvertisingOfSalesViewModel GetProcedureBoxesModel(AdvertisingOfSalesViewModel model)
        {
            var _advertisingNode = _umbracoHelper.TypedContent(model.CurrentUmbracoPageId);
            var _procedureList   = _advertisingNode.Children.Where("Visible").Select(q => new AnnouncementOfSale(q));
            var _advertisingItem = new AdvertisingOfSales(_advertisingNode);

            model.DisplayCount = _advertisingItem.DisplayItemCount;
            model.ArchiveUrl   = _advertisingItem.ArchiveUrl;

            #region Pobranie filtrów z bazy danych
            //Pobranie aktywnych filtrów z bazy danych
            var _administrativeFilterItemsFromDB = _dbService.GetAll <AdministrativeDB>("PolRegioAdministrative", q => q.IsEnabled);

            model.AdministrativeFilter = _administrativeFilterItemsFromDB.Select(q => new FilterItem()
            {
                Id = q.Id, DisplayText = _umbracoHelper.GetDictionaryValue(q.DictionaryKey)
            }).ToList();
            model.AdministrativeFilter.Insert(0, new FilterItem()
            {
                Id = 0, DisplayText = _umbracoHelper.GetDictionaryValue("Advertising.Placeholder.AllAdministrative")
            });

            model.StatusFilter = Enum.GetValues(typeof(NoticesSalesStatusEnum)).Cast <NoticesSalesStatusEnum>().Select(q => new FilterItem()
            {
                Id = (int)q, DisplayText = _umbracoHelper.GetDictionaryValue(string.Format("Advertising.Placeholder.{0}", q))
            }).ToList();
            model.StatusFilter.Insert(0, new FilterItem()
            {
                Id = 0, DisplayText = _umbracoHelper.GetDictionaryValue("Advertising.Placeholder.Any")
            });
            #endregion
            #region SetFIlterStateCookie

            var _filterModel = new AdvertisingFilterStateModel()
            {
                SelectedStatusId         = model.SelectedStatusId,
                SelectedAdministrativeId = model.SelectedAdministrativeId,
                Name      = model.Name,
                Number    = model.Number,
                StartDate = model.StartDate,
                EndDate   = model.EndDate
            };
            CookiesExtensions.CreateCookie(CookieVariables.AdvertisingFilterCookie, StringExtensions.Base64Encode(JsonConvert.SerializeObject(_filterModel)));
            #endregion
            if (model.SelectedAdministrativeId != 0)
            {
                _procedureList = _procedureList.Where(q => q.Administrative.SavedValue != null && JsonConvert.DeserializeObject <IEnumerable <NuPickersSqlDropDownPicker> >(q.Administrative.SavedValue.ToString()).Any(c => c.Key == model.SelectedAdministrativeId.ToString()));
            }
            if (model.SelectedStatusId != 0)
            {
                _procedureList = _procedureList.Where(q => ((int)q.GetStatus()) == model.SelectedStatusId);
            }
            if (!string.IsNullOrEmpty(model.Name))
            {
                _procedureList = _procedureList.Where(q => q.Name.Trim().ToLower().Contains(model.Name.Trim().ToLower()));
            }
            if (!string.IsNullOrEmpty(model.Number))
            {
                _procedureList = _procedureList.Where(q => q.NumberOfProceedings.Trim().ToLower().Contains(model.Number.Trim().ToLower()));
            }
            if (model.StartDate.HasValue && model.EndDate.HasValue)
            {
                _procedureList = _procedureList.Where(q => q.InitiationOfProceedingsDate >= model.StartDate.Value && q.InitiationOfProceedingsDate <= model.EndDate.Value);
            }
            else if (model.StartDate.HasValue && !model.EndDate.HasValue)
            {
                _procedureList = _procedureList.Where(q => q.InitiationOfProceedingsDate >= model.StartDate.Value);
            }
            else if (!model.StartDate.HasValue && model.EndDate.HasValue)
            {
                _procedureList = _procedureList.Where(q => q.InitiationOfProceedingsDate <= model.EndDate.Value);
            }
            model.AllNewsCount  = _procedureList.Count();
            model.ProcedureList = _procedureList.OrderByDescending(q => q.InitiationOfProceedingsDate).Take(model.DisplayCount).Select(q => new AdvertisingBoxModel(q));
            return(model);
        }
        public NewsPageViewModel GetNewsBoxesModel(NewsPageViewModel model)
        {
            var _newsNode       = _umbracoHelper.TypedContent(model.CurrentUmbracoPageId);
            var _newsList       = _newsNode.Children.Where("Visible").Select(q => new ArticleWithDoubleFiltr(q));
            var _isParamFromUrl = !string.IsNullOrEmpty(model.SelectedTypeFromUrl);

            model.DisplayCount = new Information(_newsNode).DisplayItemsCount;

            #region Pobranie filtrów z bazy danych


            //Pobranie aktywnych filtrów z bazy danych
            var _regionFilterItemsFromDB = _dbService.GetAll <RegionDB>("PolRegioRegion", q => q.IsEnabled);
            var _newsTypeItemsFromDB     = _dbService.GetAll <ArticleTypeDB>("PolRegioArticleType", q => q.IsEnabled);

            model.RegionFilter = _regionFilterItemsFromDB.Select(q => new FilterItem()
            {
                Id = q.Id, DisplayText = _umbracoHelper.GetDictionaryValue(q.DictionaryKey)
            }).ToList();
            model.RegionFilter.Insert(0, new FilterItem()
            {
                Id = 0, DisplayText = _umbracoHelper.GetDictionaryValue("News.Placeholder.AllRegions")
            });
            if (model.NewsTypeFilter == null)
            {
                model.NewsTypeFilter = _newsTypeItemsFromDB.Select(q => new CheckBoxFilterItem()
                {
                    Id = q.Id, DisplayText = _umbracoHelper.GetDictionaryValue(q.DictionaryKey), IsChecked = (_isParamFromUrl && q.Name.ToLower() == model.SelectedTypeFromUrl.ToLower()) || (!_isParamFromUrl && model.SelectedTypeIds != null && model.SelectedTypeIds.Contains(q.Id))
                }).ToList();
            }

            var _selectedTypesId = model.NewsTypeFilter.Where(q => q.IsChecked).Select(q => q.Id);

            #region SetFilterStateCookie

            var _typesId     = _selectedTypesId as IList <int> ?? _selectedTypesId.ToList();
            var _filterModel = new NewsFilterStateViewModel()
            {
                NewsRegionFiltr = model.SelectedRegionId,
                NewsTypeFilter  = _typesId.ToList()
            };
            CookiesExtensions.CreateCookie(CookieVariables.NewsFilterCookie, StringExtensions.Base64Encode(JsonConvert.SerializeObject(_filterModel)));
            #endregion
            #endregion
            if (model.SelectedRegionId != 0)
            {
                var _departmentNode = new OfficeAccordion(_newsNode.AncestorOrSelf(DocumentTypeEnum.location.ToString()).DescendantOrSelf(DocumentTypeEnum.officeAccordion.ToString()));

                if (_departmentNode != null && _departmentNode.AddOffice != null)
                {
                    var _contactRegionList = _departmentNode.AddOffice.Fieldsets.Where(x => x != null && x.Properties.Any() && !x.Disabled).Select(q => new RegionContactBox(q));
                    model.RegionContact = _contactRegionList.Where(q => q.Region != null).FirstOrDefault(q => q.Region.Key == model.SelectedRegionId.ToString());
                }

                _newsList = _newsList.Where(q => q.ArticleRegions.SavedValue != null && JsonConvert.DeserializeObject <IEnumerable <NuPickersSqlDropDownPicker> >(q.ArticleRegions.SavedValue.ToString()).Any(c => c.Key == model.SelectedRegionId.ToString()));
            }
            if (_typesId.Count() > 0)
            {
                _newsList = _newsList.Where(q => q.ArticleCategory.SavedValue != null && _typesId.Contains(int.Parse(JsonConvert.DeserializeObject <IEnumerable <NuPickersSqlDropDownPicker> >(q.ArticleCategory.SavedValue.ToString()).Select(c => c.Key).FirstOrDefault())));
            }

            model.AllNewsCount  = _newsList.Count();
            model.NewsBoxesList = _newsList
                                  .OrderByDescending(q => q.ListArticleDate)
                                  .Take(model.DisplayCount)
                                  .Select(q => new NewsBoxModel(q));

            return(model);
        }
        /// <summary>
        /// Metoda zwracająca obiekt typu HeaderViewModel
        /// </summary>
        /// <param name="currentUmbracoPageId">id strony umbraco na której się znajdujemy</param>
        /// <returns>obiekt klasy HeaderViewModel</returns>
        public HeaderViewModel GetHeaderViewModel(int currentUmbracoPageId)
        {
            var _model = new HeaderViewModel();
            //Aktualna strona, na której się znajdujemy
            var _currentPage = _umbracoHelper.TypedContent(currentUmbracoPageId);
            //Aktualna lokalizacja, na której się znajdujemy
            var _localizationNode = _currentPage.AncestorOrSelf(DocumentTypeEnum.location.ToString());

            _model.Languages = _localizationNode.Parent.Children
                               .Where(x => x.DocumentTypeAlias == DocumentTypeEnum.location.ToString())
                               .Where(NodeAtributeEnum.Visible.ToString())
                               .Select(q => new LangLink()
            {
                IsActive     = q.Id == _localizationNode.Id,
                Url          = q.Url,
                Text         = q.Name,
                LanguageCode = _umbHelperService.GetCulture(q).TwoLetterISOLanguageName
            });

            var _localization = new Location(_localizationNode);

            _model.HomePageUrl     = _localizationNode.Url;
            _model.MenuItems       = new List <MenuItem>();
            _model.HelplineNumber  = _localization.HelplineNumber;
            _model.HelplineTooltip = _localization.HelplineTooltipText;

            _model.CookieInformation = new Cookies(_localizationNode);
            foreach (var _localizationChild in _localizationNode.Children.Where("Visible"))
            {
                var _item = new SelectMenuOrFooter(_localizationChild);
                if (_item.ChoiceMenuOrFooter != null && _item.ChoiceMenuOrFooter.ToString() == MenuPositionTypeEnum.Menu.ToString())
                {
                    //Level 1
                    var itemName = _localizationChild.Name;
                    if (_localizationChild.DocumentTypeAlias == DocumentTypeEnum.account.ToString())
                    {
                        itemName = _accountService.IsAuthenticated()
                            ? _localizationChild.GetPropertyValue <string>("loggedInMenuText")
                            : _localizationChild.GetPropertyValue <string>("guestMenuText");
                    }

                    var _menuItem = new MenuItem();
                    _menuItem.Url = new Link()
                    {
                        Text = itemName, IsActive = true
                    };

                    var _currentNodeChildren = _localizationChild.Children.Where("Visible");
                    if (_currentNodeChildren != null && _currentNodeChildren.Count() > 0)
                    {
                        //level 2
                        _menuItem.SubMenuItems = new List <MenuItem>();
                        foreach (var item in _currentNodeChildren)
                        {
                            if (ItemShouldNotBeDisplayed(item))
                            {
                                continue;
                            }

                            var _subMenuItem     = new MenuItem();
                            var _subMenuChildren = item.Children.Where("Visible");
                            var _hasSubMenu      = _localizationChild.DocumentTypeAlias == DocumentTypeEnum.ForTravelers.ToString() && _subMenuChildren.Count() > 0;
                            _subMenuItem.Url = new Link()
                            {
                                IsActive = true, Text = item.Name, Url = _hasSubMenu ? string.Empty : item.Url, DataCookie = item.IsDocumentType(RegionalOffers.ModelTypeAlias) ? CookieVariables.OffersFilterCookie : ""
                            };
                            if (_hasSubMenu)
                            {
                                if (item.DocumentTypeAlias == DocumentTypeEnum.Information.ToString())
                                {
                                    var _newsTypeItemsFromDB = _dbService.GetAll <ArticleTypeDB>("PolRegioArticleType", q => q.IsEnabled);
                                    _subMenuItem.SubMenuItems = _newsTypeItemsFromDB.Select(q => new MenuItem()
                                    {
                                        Url = new Link()
                                        {
                                            IsActive   = true,
                                            Url        = string.Format("{0}?type={1}", item.Url, q.Name.ToLower()),
                                            Text       = _umbracoHelper.GetDictionaryValue(q.DictionaryKey),
                                            DataCookie = CookieVariables.NewsFilterCookie
                                        }
                                    }).ToList();
                                    _subMenuItem.SubMenuItems.Insert(0, new MenuItem()
                                    {
                                        Url = new Link()
                                        {
                                            IsActive = true, Text = _umbracoHelper.GetDictionaryValue("Menu.Link.SeeAllInformation"), Url = item.Url, DataCookie = CookieVariables.NewsFilterCookie
                                        }
                                    });
                                }
                                else
                                {
                                    _subMenuItem.SubMenuItems = new List <MenuItem>();
                                    foreach (var itemLinks in _subMenuChildren)
                                    {
                                        if (itemLinks.DocumentTypeAlias == DocumentTypeEnum.searchConnection.ToString())
                                        {
                                            foreach (var itemLink in itemLinks.GetPropertyValue <JArray>("link"))
                                            {
                                                MenuItem _footerItem = new MenuItem()
                                                {
                                                    Url = new Link()
                                                    {
                                                        IsActive        = true,
                                                        Url             = itemLink.Value <string>("link"),
                                                        OpenInNewWindow = itemLink.Value <bool>("newWindow")
                                                    }
                                                };
                                                _footerItem.Url.Text = itemLinks.Name;
                                                _subMenuItem.SubMenuItems.Add(_footerItem);
                                            }
                                        }
                                        else
                                        {
                                            var _menuSubItem = new MenuItem()
                                            {
                                                Url = new Link()
                                                {
                                                    IsActive = true,
                                                    Url      = itemLinks.Url,
                                                    Text     = itemLinks.Name
                                                }
                                            };
                                            _subMenuItem.SubMenuItems.Add(_menuSubItem);
                                        }
                                    }
                                }
                            }

                            _menuItem.SubMenuItems.Add(_subMenuItem);
                        }
                    }
                    else
                    {
                        _menuItem.Url.Url = _localizationChild.Url;
                    }

                    _model.MenuItems.Add(_menuItem);
                }
            }


            //pobieranie alerta
            if (_localization.GetPropertyValue <bool>("LangAlertActive"))
            {
                _model.Alert = new HeaderAlertViewModel()
                {
                    Title          = _localization.GetPropertyValue <string>("LangAlertTitle"),
                    ButtonTitle    = _localization.GetPropertyValue <string>("LangAlertButtonTitle"),
                    ButtonUrl      = _localization.GetPropertyValue <string>("LangAlertButtonURL"),
                    IsButtonNewTab = _localization.GetPropertyValue <bool>("LangAlertButtonNewTab"),
                };
            }

            #region PobieranieOverlaya

            var overlayEnabledType = _localization.GetPropertyValue <int>("OverlayShowOn");
            var overlayIsEnabled   = false;

            switch (library.GetPreValueAsString(overlayEnabledType))
            {
            case "Strona główna":     // only main page
                if (_currentPage.Id == _localizationNode.Id)
                {
                    overlayIsEnabled = true;
                }
                break;

            case "Cała strona":     // whole page
                overlayIsEnabled = true;
                break;

            case "Wybrana kategoria":     // selected categories
                overlayIsEnabled = _localization.GetPropertyValue <string>("OverlayShowOnNodes")
                                   .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                   .Any(id => _umbracoHelper.TypedContent(id).IsAncestorOrSelf(_currentPage));
                break;

            case "Wyłączony":     //off
            default:
                break;
            }
            if (overlayIsEnabled)
            {
                _model.Overlay = new OverlayViewModel()
                {
                    DesktopImageUrl = _localization.GetPropertyValue <string>("OverlayPictureDesktop"),
                    MobileImageUrl  = _localization.GetPropertyValue <string>("OverlayPictureMobile"),
                    ImageAlt        = _localization.GetPropertyValue <string>("OverlayPictureAlt"),

                    ButtonUrl      = _localization.GetPropertyValue <string>("OverlayButtonUrl"),
                    ButtonIsNewTab = _localization.GetPropertyValue <bool>("OverlayButtonNewTab"),

                    Capping = _localization.GetPropertyValue <int>("OverlayCapping"),
                };
            }

            #endregion

            return(_model);
        }
Exemple #30
0
        public ArticlePageViewModel GetArticlePageViewModel(int currentUmbracoPageId)
        {
            var _currentArticle = _umbracoHelper.TypedContent(currentUmbracoPageId);

            var _model = new ArticlePageViewModel();

            _model.ArticleContent = new ArticleContent(_currentArticle);

            #region Pobranie Regionu i typu artykułu
            var _regionFilterItemsFromDB = _dbService.GetAll <RegionDB>("PolRegioRegion", q => q.IsEnabled);

            if (_currentArticle.DocumentTypeAlias == DocumentTypeEnum.articleWithFilter.ToString())
            {
                var _artilceWithFiltr = new ArticleWithFilter(_currentArticle);
                if (_artilceWithFiltr.RegionFiltr != null)
                {
                    var _articleRegion = JsonConvert.DeserializeObject <IEnumerable <NuPickersSqlDropDownPicker> >(_artilceWithFiltr.RegionFiltr.SavedValue.ToString()).FirstOrDefault();
                    if (_articleRegion != null)
                    {
                        var _regionFromDb = _regionFilterItemsFromDB.Where(q => q.Id.ToString() == _articleRegion.Key).FirstOrDefault();
                        if (_regionFromDb != null)
                        {
                            _model.ArticleRegion = _umbracoHelper.GetDictionaryValue(_regionFromDb.DictionaryKey);
                        }
                    }
                }
            }

            if (_currentArticle.DocumentTypeAlias == DocumentTypeEnum.articleWithDoubleFiltr.ToString())
            {
                var _artilceWithFiltr = new ArticleWithDoubleFiltr(_currentArticle);
                if (_artilceWithFiltr.ArticleCategory != null)
                {
                    var _articleType = JsonConvert.DeserializeObject <IEnumerable <NuPickersSqlDropDownPicker> >(_artilceWithFiltr.ArticleCategory.SavedValue.ToString()).FirstOrDefault();
                    _model.ArticleType = Enum.Parse(typeof(ArticleTypeEnum), _articleType.Key).ToString();
                }
                if (_artilceWithFiltr.ArticleRegions != null)
                {
                    var _articleRegion = JsonConvert.DeserializeObject <IEnumerable <NuPickersSqlDropDownPicker> >(_artilceWithFiltr.ArticleRegions.SavedValue.ToString()).FirstOrDefault();
                    if (_articleRegion != null)
                    {
                        var _regionFromDb = _regionFilterItemsFromDB.Where(q => q.Id.ToString() == _articleRegion.Key).FirstOrDefault();
                        if (_regionFromDb != null)
                        {
                            _model.ArticleRegion = _umbracoHelper.GetDictionaryValue(_regionFromDb.DictionaryKey);
                        }
                    }
                }
            }
            #endregion

            #region Galeria
            if (_model.ArticleContent.ArticleImageList != null)
            {
                _model.CarouselImages = _model.ArticleContent.ArticleImageList.Fieldsets.Where(x => x != null && x.Properties.Any() && !x.Disabled).Select(q => new ArticleCarouselItem()
                {
                    ArticleCarouselImage = q.GetValue <string>("addImage"),
                    ArticleCarouselDesc  = q.GetValue <string>("imageCarouselDesc"),
                    ArticleCarouselName  = q.GetValue <string>("imageName")
                });
            }
            #endregion

            #region Dokumenty
            if (_model.ArticleContent.AddDocumentDown != null)
            {
                _model.DownloadDocuments = _model.ArticleContent.AddDocumentDown.Fieldsets.Where(x => x != null && x.Properties.Any() && !x.Disabled).Select(q => new DownloadItem()
                {
                    DocumentUrl  = q.GetValue <string>("addDoc"),
                    DocumentName = q.GetValue <string>("articleDocName"),
                    DocumentDate = q.GetValue <DateTime>("chooseDate")
                });
            }
            #endregion
            #region Tags
            if (_model.ArticleContent.ArticleTag != null)
            {
                var _localizationNode = _currentArticle.AncestorOrSelf(DocumentTypeEnum.location.ToString());
                var nodes             = _localizationNode.Descendant(DocumentTypeEnum.articleListWithTag.ToString());

                IPublishedContent node = _umbracoHelper.TypedContent(nodes.Id);
                _model.TagListUrl = node.Url;


                var tagItem = _model.ArticleContent.ArticleTag.ToString().Split(',');
                _model.Tags = tagItem;
            }
            #endregion

            #region Data
            var _boxArticle = new ArticleBox(_currentArticle);
            if (_boxArticle != null && _boxArticle.ListArticleDate != DateTime.MinValue)
            {
                _model.ArticleDate = _boxArticle.ListArticleDate;
            }
            #endregion

            #region Sprawdzenie czy oferta czy informacja
            var _articleParent = _currentArticle.AncestorOrSelf(DocumentTypeEnum.OffersAndPromotions.ToString());
            if (_articleParent != null)
            {
                _model.IsOffersArticle = true;
            }
            #endregion
            return(_model);
        }