Esempio n. 1
0
        /// <summary>
        /// 新增護產機構
        /// </summary>
        /// <param name="model">護產交換集</param>
        /// <returns>護產交換集新增後</returns>
        public override AgencyViewModel Create(AgencyViewModel model)
        {
            IContent p          = (model.PId != 0) ? GetNode(model.PId) : GetUnGroupNode(PM.AgencyRoot.ModelTypeAlias, PM.AgencyGroup.ModelTypeAlias);
            var      childNodes = GetChildNodes(p.Id, PM.Agency.ModelTypeAlias).Where(x => x.GetValue <string>(PM.Agency.GetModelPropertyType(f => f.AgencyID).Alias) == model.Agency.AgencyId);

            if (childNodes != null || childNodes.Any())
            {
                throw new Exception(ErrorMessage.AddDuplicate);
            }

            IContent content = CreateNewNode(p.Id, PM.Agency.ModelTypeAlias, model.Name);

            model.Set(ref content);
            SaveAndPublish(content);

            //新增聯絡人子節點
            IContent contacts = CreateNewNode(content.Id, PM.Contacts.ModelTypeAlias, NodeName.NodeNameContracts);

            model.Set(ref contacts);
            SaveAndPublish(contacts);
            //新增負責人子節點
            IContent principal = CreateNewNode(content.Id, PM.Principal.ModelTypeAlias, NodeName.NodeNamePricipal);

            model.Set(ref principal);
            SaveAndPublish(principal);

            return(model.Get(_helper.Content(content)));
        }
        private List<BannerItem> UmbracoEvents()
        {
            var helper = new UmbracoHelper(UmbracoContext.Current);
            List<BannerItem> ue = new List<BannerItem>();
            IPublishedContent root = helper.Content(1068);
            IPublishedContent eventRoot = helper.Content(Convert.ToInt32(root.GetProperty("seminars").Value));
            foreach (var itm in eventRoot.Children.Where("Visible").Where("end >= DateTime.Now.Date").OrderBy("start"))
            {
                string input = itm.GetProperty("end").Value.ToString();
                DateTime dateTime;
                if (DateTime.TryParse(input, out dateTime))
                {
                    if (dateTime > DateTime.Now)
                    {
                        var bi = new BannerItem();
                        bi.title = itm.HasValue("subHeader") ? itm.GetProperty("subHeader").Value.ToString() : itm.Name;
                        if (itm.HasValue("country"))
                            bi.Country = itm.GetProperty("country").ToString();
                        bi.link = new entryLink
                        {
                            href = itm.Url,
                            target = "_self"
                        };
                        bi.published = bi.StartDateTime = "Seminar starts "+itm.GetProperty("start").Value.ToString().ToDate().ToShortDateString();

                        bi.updated = itm.UpdateDate.ToShortDateString();
                        bi.TypeOfContent = Enum.GetName(typeof(TypeOfContent),TypeOfContent.UmbracoEvent);

                        ue.Add(bi);
                    }
                }
            }
            return ue;
        }
Esempio n. 3
0
        /// <summary>
        /// 新增分類
        /// </summary>
        /// <param name="model">分類交換集</param>
        /// <returns>分類交換集</returns>
        public override AgencyGroupViewModel Create(AgencyGroupViewModel model)
        {
            IContent p       = model.PId != 0 ? GetNode(model.PId) : GetUnGroupNode(PM.AgencyRoot.ModelTypeAlias, PM.AgencyGroup.ModelTypeAlias);
            IContent content = CreateNewNode(p.Id, PM.AgencyGroup.ModelTypeAlias, model.Name);

            model.Set(ref content);
            SaveAndPublish(content);

            return(model.Get(_helper.Content(content)));
        }
 public IPublishedContent Company()
 {
     var memberCompany = GetMember();
     var umbracoHelper = new UmbracoHelper(UmbracoContext.Current);
     // DKO: získá napojení na stránku firmy z nastavení uživatele v členské sekci
     return umbracoHelper.Content(memberCompany.Properties["CompanyPage"].Value);
 }
Esempio n. 5
0
        public List <FeaturedItem> GetFeaturedItemsModel()
        {
            List <FeaturedItem> model = new List <FeaturedItem>();
            //IPublishedContent homePage = Umbraco.AssignedContentItem.AncestorOrSelf(1);
            const int         HOME_PAGE_POSITION_IN_PATH = 1;
            int               homePageId = int.Parse(_currentPage.Path.Split(',')[HOME_PAGE_POSITION_IN_PATH]);
            IPublishedContent homePage   = _uHelper.Content(homePageId);
            // get the value of hp - featured
            ArchetypeModel featuredItems = homePage.GetPropertyValue <ArchetypeModel>("featuredItems");

            foreach (ArchetypeFieldsetModel fieldset in featuredItems)
            {
                var    imageId   = fieldset.GetValue <string>("image");
                var    mediaItem = _uHelper.Media(imageId);
                string imageUrl  = mediaItem.Url;

                var pageId = fieldset.GetValue <string>("page");
                IPublishedContent linkedToPage = _uHelper.TypedContent(pageId);
                string            linkUrl      = "";

                if (linkedToPage != null)
                {
                    linkUrl = linkedToPage.Url;
                }


                model.Add(new FeaturedItem(fieldset.GetValue <string>("name"), fieldset.GetValue <string>("category"), imageUrl, linkUrl));
            }

            return(model);
        }
Esempio n. 6
0
        // GET api/task/getInputs
        public List <object> GetInputs()
        {
            var taskDtos      = new List <object>();
            var umbracoHelper = new UmbracoHelper(UmbracoContext.Current);

            var tasks = umbracoHelper.Content(1590).Children;

            foreach (var task in tasks)
            {
                string[] inputsRaw = task.GetPropertyValue("input");
                var      inputs    = inputsRaw.Where(i => i != string.Empty).Select(str => str.Replace("\\n", "\n")).ToList();

                string[] outputsRaw = task.GetPropertyValue("output");
                var      outputs    = outputsRaw.Where(i => i != string.Empty).Select(str => str.Replace("\\n", "\n")).ToList();

                var n = inputs.Count;
                for (var i = 0; i < n; i++)
                {
                    taskDtos.Add(new
                    {
                        Id        = task.Id,
                        Input     = inputs[i],
                        Output    = outputs[i],
                        InputType = task.GetPropertyValue("inputType"),
                    });
                }
            }

            return(taskDtos);
        }
        // GET api/codeskeleton/get/{id}
        public GenericCodeSkeletonDto Get(string id)
        {
            var skeletonDtos  = new List <GenericCodeSkeletonDto>();
            var umbracoHelper = new UmbracoHelper(UmbracoContext.Current);

            var skeletons = umbracoHelper.Content(1518).Children;

            foreach (var skeleton in skeletons)
            {
                skeletonDtos.Add(new GenericCodeSkeletonDto
                {
                    Language           = skeleton.Name,
                    Skeleton           = skeleton.GetPropertyValue("skeleton"),
                    ReadLine           = skeleton.GetPropertyValue("inputReadLine").Replace("\\n", "\n"),
                    WriteLine          = skeleton.GetPropertyValue("outputWriteLine"),
                    ReadInteger        = skeleton.GetPropertyValue("inputReadInteger").Replace("\\n", "\n"),
                    ReadLineOfIntegers = skeleton.GetPropertyValue("inputReadLineOfIntegers").Replace("\\n", "\n"),
                    ReadInputIntegerNumberOfLinesOfIntegers = skeleton.GetPropertyValue("inputReadInputIntegerNumberOfLinesOfIntegers").Replace("\\n", "\n")
                });
            }
            var skeletonDto = skeletonDtos.FirstOrDefault(s => s.Language.Equals(id));

            if (skeletonDto == null)
            {
                return new GenericCodeSkeletonDto
                       {
                           Language = id,
                           Skeleton = string.Empty
                       }
            }
            ;

            return(skeletonDto);
        }
    }
Esempio n. 8
0
        public List <TargetedItemModel> GetTargetedItemsModel(string ItemsAlias    = "targetedItems", string ItemImageAlias          = "targetedItemImage", string ItemPageAlias = "targetedItemPage",
                                                              string ItemNameAlias = "targetedItemName", string ItemDescriptionAlias = "targetedItemDescription")
        {
            List <TargetedItemModel> model = new List <TargetedItemModel>();

            var targetedItems = _homePage.Value <IEnumerable <IPublishedElement> >(ItemsAlias);

            foreach (var item in targetedItems)
            {
                int imageId = item.Value <IPublishedContent>(ItemImageAlias).Id;

                var    mediaItem = _uHelper.Media(imageId);
                string imageUrl  = mediaItem.Url();

                int pageId = item.Value <IPublishedContent>(ItemPageAlias).Id;

                IPublishedContent linkedToPage = _uHelper.Content(pageId);
                string            linkUrl      = linkedToPage.Url();

                string name     = item.Value <string>(ItemNameAlias);
                string category = item.Value <string>(ItemDescriptionAlias);

                model.Add(new TargetedItemModel(name, category, imageUrl, linkUrl));
            }

            return(model);
        }
Esempio n. 9
0
        // GET api/task/getAll
        public IEnumerable <TaskDto> GetAll()
        {
            var taskDtos      = new List <TaskDto>();
            var umbracoHelper = new UmbracoHelper(UmbracoContext.Current);

            var tasks = umbracoHelper.Content(1590).Children;

            foreach (var task in tasks)
            {
                if (task.GetPropertyValue("enabled"))
                {
                    List <TestcaseDto> testCases = task.GetPropertyValue("testCases").ToObject <List <TestcaseDto> >();

                    IEnumerable <string> outputs = testCases.Select(x => x.Output);

                    if (outputs.Any())
                    {
                        taskDtos.Add(new TaskDto
                        {
                            Id          = task.Id,
                            Name        = task.Name,
                            Value       = task.GetPropertyValue("value"),
                            Description = ConstructDescription(task, task.GetPropertyValue("testCases").ToObject <List <TestcaseDto> >()),
                            IsEnabled   = task.GetPropertyValue("enabled"),
                            IsForDuel   = task.GetPropertyValue("competition")
                        });
                    }
                }
            }

            return(taskDtos);
        }
        private static void FindVariantsForTranslations(IPublishedContent content, Dictionary <string, IPublishedContent> translations, UmbracoHelper umbracoHelper, string cultureInfo = null)
        {
            //using relation name here to filter & not alias (as the relation has a confusing alias for some reason)
            var relations = Current.Services.RelationService.GetByParentOrChildId(content.Id).Where(r => r.RelationType.Name == "Translations");

            foreach (var item in relations)
            {
                var relatedId = item.ChildId != content.Id ? item.ChildId : item.ParentId;
                var variant   = umbracoHelper.Content(relatedId);

                if (variant == null) // not published
                {
                    continue;
                }

                var culture = variant.GetCultureFromDomains();

                // find the variants only for the culture we are looking for
                if (cultureInfo != null && !culture.Equals(cultureInfo))
                {
                    continue;
                }

                translations[culture] = variant;
            }
        }
        ///
        /// Utility extension to map a  to a BasketViewLine item.
        /// Notice that the ContentId is pulled from the extended data. The name can either
        /// be the Merchello product name via lineItem.Name or the Umbraco content page
        /// name with umbracoHelper.Content(contentId).Name
        ///
        ///
        ///The  to be mapped
        ///
        private static BasketViewLineItem ToBasketViewLineItem(this ILineItem lineItem)
        {
            var umbracoHelper = new UmbracoHelper(UmbracoContext.Current);

            var contentId = lineItem.ExtendedData.ContainsKey("umbracoContentId") ? int.Parse(lineItem.ExtendedData["umbracoContentId"]) : 0;

            var umbracoName = umbracoHelper.Content(contentId).Name;
            var merchelloProductName = lineItem.Name;

            return new BasketViewLineItem()
            {

                Key = lineItem.ExtendedData.GetProductKey(),// lineItem.Key,
                ContentId = contentId,
                ExtendedData = DictionaryToString(lineItem.ExtendedData),
                Name = merchelloProductName,
                //Name = umbracoName,
                Sku = lineItem.Sku,
                UnitPrice = lineItem.Price,
                TotalPrice = lineItem.TotalPrice,
                Quantity = lineItem.Quantity,
                Images = lineItem.ExtendedData.GetValue("images")

            };
        }
Esempio n. 12
0
        private string getNodeIdFromUdi(string media)
        {
            Current.Logger.Info(this.GetType(),"getNodeIdFromUdi(string media): value in media: "+media);
            var id = string.Empty;
            try
            {
                var udi = GuidUdi.Parse(media);
                //var typedContent = udi.ToPublishedContent();
                var umbracoContext = UmbracoContext.Current == null ? EnsureUmbracoContext() : UmbracoContext.Current;
                var umbracoHelper = new UmbracoHelper(umbracoContext, Current.Services);

                if (udi.ToString().ToLower().Contains("document"))
                {
                    var typedContent = umbracoHelper.Content(udi);
                    id = typedContent?.Id.ToString();
                }
                else if (udi.ToString().ToLower().Contains("media"))
                {
                    var typedContent = umbracoHelper.Media(udi);
                    id = typedContent?.Id.ToString();
                }
                

                
            }
            catch (Exception msg)
            {
                Current.Logger.Error(this.GetType(), "Error while processing getNodeIdFromUdi(string media): value in media: " + media, msg);
            }
            return id;

        }
        private string GetUmbracoUrl(string value, UmbracoHelper helper)
        {
            var content = helper.Content(value);

            return(content == null
                ? string.Empty
                : $"{content.Url}");
        }
        private string GetUmbracoTemplateAlias(string value, UmbracoHelper helper)
        {
            var content = helper.Content(value);

            return(content == null
                ? string.Empty
                : $"{StringHelpers.FirstCharToUpper(content.ContentType.Alias)}");
        }
        public string GetConfirmVerificationUrl(string tenantUid, string origin, string username, string languageCode, string id = "", string code = "")
        {
            var random = ContentHelper.RandomString(seed);

            code = !string.IsNullOrEmpty(code) ? code : random;
            var tenantRootPage   = new NodeHelper().GetTenantRoot(tenantUid);
            var confirmEmailPage = helper.Content(tenantRootPage.Id).Children.SingleOrDefault(x => x.ContentType.Alias == "ConfirmEmail");
            var query            = "?";

            query += !string.IsNullOrEmpty(id) ? $"a={id}&" : string.Empty;
            query += $"b={code}&c={username}";
            var confirmEmailPageUrl = confirmEmailPage != null?confirmEmailPage.UrlAbsolute() : "confirm-email";

            var verificationUrl = new Uri(new Uri(confirmEmailPageUrl), $"{query}");

            return(verificationUrl.ToString());
        }
        /// <summary>
        /// Gets a list of URLs, each corresponding to a page with a unique template
        /// </summary>
        /// <remarks>
        /// This is used so we can ping each URL to "warm-up" the compilation of the view it uses
        /// </remarks>
        /// <returns>A list of URLs</returns>
        public IEnumerable <string> GetTemplateUrlsToPing()
        {
            const string sql = @";WITH UniqueTemplateNode AS
            (
				SELECT C.nodeId,
	            ROW_NUMBER() OVER (PARTITION BY DT.TemplateNodeId ORDER BY C.NodeId) AS rn
				FROM cmsDocumentType DT
				INNER JOIN cmsTemplate ON DT.templateNodeId = cmsTemplate.nodeId
				INNER JOIN umbracoContent C ON C.contentTypeId = DT.contentTypeNodeId
            )
               SELECT nodeId FROM UniqueTemplateNode WHERE rn = 1";

            var query = new Sql(sql);

            var ids = new List <int>();

            using (var scope = this.scopeProvider.CreateScope(autoComplete: true))
            {
                ids = scope.Database.Fetch <int>(query);
            }

            foreach (var id in ids)
            {
                IPublishedContent node = null;

                try
                {
                    node = umbHelper.Content(id);
                }
                catch
                {
                    // we ignore it if we can't get an instance
                }

                if (node != null)
                {
                    string url = null;

                    try
                    {
                        url = node.Url(mode: UrlMode.Absolute);
                    }
                    catch
                    {
                        // we ignore it if the node doesn't have an absolute URL
                    }

                    if (!string.IsNullOrEmpty(url))
                    {
                        yield return(url);
                    }
                }
            }
        }
Esempio n. 17
0
        public static AuditableContent ConvertToAuditableContent(IPublishedContent IPub)
        {
            var iContent = umbContentService.GetById(IPub.Id);
            var ac       = new AuditableContent();

            ac.UmbContentNode = iContent;
            ac.IsPublished    = ac.UmbContentNode.Published;
            ac.DocTypeAlias   = iContent.ContentType.Alias;

            if (iContent.Template != null)
            {
                var template = umbFileService.GetTemplate((int)iContent.Template.Id);
                ac.TemplateAlias = template.Alias;
            }
            else
            {
                ac.TemplateAlias = "NONE";
            }

            if (ac.UmbContentNode.Published)
            {
                try
                {
                    var iPub = umbHelper.Content(iContent.Id);
                    ac.UmbPublishedNode = iPub;
                }
                catch (Exception e)
                {
                    try
                    {
                        //Get preview - unpublished
                        var iPub = umbContext.ContentCache.GetById(true, iContent.Id);
                        ac.UmbPublishedNode = iPub;
                    }
                    catch (Exception exception)
                    {
                        ac.UmbPublishedNode = null;
                        var nodeId   = iContent != null ? iContent.Id : 0;
                        var nodeName = iContent != null ? iContent.Name : "UNKNOWN - IContent is NULL";
                        LogHelper.Error <AuditableContent>($"Unable to get a PublishedContent for node #{nodeId} : '{nodeName}'", exception);
                    }
                }
            }

            ac.RelativeNiceUrl = ac.UmbPublishedNode != null ? ac.UmbPublishedNode.Url : "UNPUBLISHED";
            ac.FullNiceUrl     = ac.UmbPublishedNode != null?ac.UmbPublishedNode.UrlAbsolute() : "UNPUBLISHED";

            ac.NodePath       = AuditHelper.NodePath(iContent);
            ac.NodePathAsText = string.Join(siteAuditorService.DefaultDelimiter, ac.NodePath);

            return(ac);
        }
Esempio n. 18
0
        public PageViewModel(ISearchResult result, UmbracoHelper helper)
        {
            var content = helper.Content(result.Id);

            if (content != null)
            {
                Id          = content.Id;
                Title       = content.Name;
                Body        = content.Value <string>("bodyText");
                Url         = content.Url;
                PageContent = content.Value <string>("pageContent");
            }
        }
Esempio n. 19
0
        // GET api/task/get/{id}
        public TaskDto Get(int id)
        {
            var umbracoHelper = new UmbracoHelper(UmbracoContext.Current);

            var task = umbracoHelper.Content(id);

            if (task.Id == 0 || !task.DocumentTypeAlias.Equals("taskNew"))
            {
                throw new ArgumentException("No task found with given ID");
            }

            return(GetNewTaskDto(task));
        }
        //Prepublishing / preunpublishing
        private void SetUrlsToPurge(IPublishingStrategy sender, PublishEventArgs <IContent> e)
        {
            var    helper = new UmbracoHelper(UmbracoContext.Current);
            string domain = WebConfigurationManager.AppSettings[FastlyDomainKey];

            //Loop through content to publish and store the URLs for after publish finishes
            foreach (IContent content in e.PublishedEntities)
            {
                if (content.Status == ContentStatus.Published)
                {
                    IPublishedContent publishedContent = (IPublishedContent)helper.Content(content.Id);
                    urlsToPurge.Add(new Uri(domain + publishedContent.Url));
                }
            }
        }
Esempio n. 21
0
        // GET api/prize/getAll
        public List <PrizeDto> GetAll()
        {
            var prizeDtos     = new List <PrizeDto>();
            var umbracoHelper = new UmbracoHelper(UmbracoContext.Current);

            var prizes = umbracoHelper.Content(1164).Children;

            foreach (var prize in prizes)
            {
                var prizeDto = GetPrizeDto(prize);
                prizeDtos.Add(prizeDto);
            }

            return(prizeDtos);
        }
Esempio n. 22
0
        // GET api/prize/get/{id}
        public PrizeDto Get(int id)
        {
            var umbracoHelper = new UmbracoHelper(UmbracoContext.Current);

            var prize = umbracoHelper.Content(id);

            if (prize.Id == 0 || !prize.DocumentTypeAlias.Equals("prize"))
            {
                throw new ArgumentException("No prize found with given ID");
            }

            var prizeDto = GetPrizeDto(prize);

            return(prizeDto);
        }
Esempio n. 23
0
        public PageViewModel(ISearchResult result, string tenantUid, UmbracoHelper helper)
        {
            var tenantRoot  = new NodeHelper().GetTenantRoot(tenantUid);
            var contentRoot = helper.Content(tenantRoot.Id);
            var content     = contentRoot.Children().SingleOrDefault(x => x.Id == int.Parse(result.Id));

            if (content != null)
            {
                Id          = content.Id;
                Title       = content.Name;
                Body        = content.Value <string>("bodyText");
                Url         = content.Url;
                PageContent = content.Value <string>("pageContent");
            }
        }
Esempio n. 24
0
        // GET: Umbraco/Api/Spots/GetSpotById?spotId=1055
        public Spot GetSpotById(int spotId)
        {
            Spot          currentSpot = new Spot();
            UmbracoHelper helper      = new UmbracoHelper(UmbracoContext);

            var today    = DateTime.Today.ToShortDateString();
            var response = helper.Content(spotId);

            currentSpot.Id             = spotId;
            currentSpot.Name           = response.GetPropertyValue <string>(PropertyAlias.Name);
            currentSpot.Category       = response.GetPropertyValue <string>(PropertyAlias.Category);
            currentSpot.Description    = response.GetPropertyValue <string>(PropertyAlias.Description);
            currentSpot.Latitude       = response.GetPropertyValue <string>(PropertyAlias.Latitude);
            currentSpot.Longitude      = response.GetPropertyValue <string>(PropertyAlias.Longitude);
            currentSpot.GoogleMapsLink = "https://maps.google.com/?q=" + response.GetPropertyValue <string>(PropertyAlias.Latitude) + "," + response.GetPropertyValue <string>(PropertyAlias.Longitude);
            currentSpot.Image          = response.GetPropertyValue <string>(PropertyAlias.Image) != null
                ? Umbraco.TypedMedia(response.GetPropertyValue <string>(PropertyAlias.Image)).Url
                : "/resources/images/no-image.jpg";

            currentSpot.LastCheckInDate = response.GetPropertyValue <DateTime>(PropertyAlias.LastCheckInDate);
            currentSpot.CheckIns        = response.GetPropertyValue <int>(PropertyAlias.CheckIns);

            //Weather Properties
            currentSpot.OptimalWindSpeed         = response.GetPropertyValue <string>(PropertyAlias.OptimalWindSpeed);
            currentSpot.OptimalWindDirection     = response.GetPropertyValue <string>(PropertyAlias.OptimalWindDirection);
            currentSpot.OptimalWindDirectionList = response.GetPropertyValue <string>(PropertyAlias.OptimalWindDirectionList);
            currentSpot.Weather    = WeatherInfoService.GetWeatherFeed(response.GetPropertyValue <string>(PropertyAlias.WeatherUrl));
            currentSpot.WeatherUrl = !string.IsNullOrWhiteSpace(response.GetPropertyValue <string>(PropertyAlias.WeatherUrl))
                ? response.GetPropertyValue <string>(PropertyAlias.WeatherUrl).ToString().Replace("forecast.xml", "")
                : "http://www.yr.no/";

            //Calculate if spot is optimal
            currentSpot.IsSpotOptimal = IsSpotOptimal(currentSpot.Category, currentSpot.OptimalWindSpeed, currentSpot.OptimalWindDirectionList, currentSpot.Weather);


            //Social Properties
            currentSpot.FacebookUrl = response.GetPropertyValue <string>(PropertyAlias.FacebookUrl);
            currentSpot.WebsiteUrl  = response.GetPropertyValue <string>(PropertyAlias.WebsiteUrl);


            //If the last time the last check-in was made is NOT today, we reset it
            if (Convert.ToDateTime(currentSpot.LastCheckInDate).ToShortDateString() != today)
            {
                currentSpot.CheckIns = 0;
            }

            return(currentSpot);
        }
Esempio n. 25
0
        private bool SurveyMail(SurveyVM questions, SurveyVM answers)
        {
            string contactFromAddress = @System.Configuration.ConfigurationManager.AppSettings["ContactFromAddress"];
            string contactBCCAddress  = @System.Configuration.ConfigurationManager.AppSettings["ContactBCCAddress"];
            string userName           = @System.Configuration.ConfigurationManager.AppSettings["userName"];
            string password           = @System.Configuration.ConfigurationManager.AppSettings["password"];
            string host = @System.Configuration.ConfigurationManager.AppSettings["host"];
            int    port = Convert.ToInt32(@System.Configuration.ConfigurationManager.AppSettings["port"]);

            UmbracoHelper helper      = new UmbracoHelper(UmbracoContext.Current);
            var           contactPage = helper.Content(1065);                    //get contactpage data
            string        email       = contactPage.contactUsDestinationAddress; //get destination address

            if (string.IsNullOrEmpty(email))
            {
                return(false);
            }
            MailMessage mail = new MailMessage();

            mail.To.Add(email);
            mail.From = new MailAddress(contactFromAddress, "Phigenics");
            mail.Bcc.Add(contactBCCAddress);
            mail.Subject = "Survey submitted on " + DateTime.Now.ToString("d");
            try
            {
                string templateBody = RenderViewToString(questions, answers);
                mail.Body       = templateBody;
                mail.IsBodyHtml = true;
                var smtp = new SmtpClient();
                smtp.Host = host;
                smtp.Port = port;
                smtp.UseDefaultCredentials = false;
                smtp.EnableSsl             = true;
                var credential = new NetworkCredential
                {
                    UserName = userName,
                    Password = password
                };
                smtp.Credentials = credential;
                smtp.Send(mail);
            }
            catch (Exception ex)
            {
                LogHelper.Error(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "Mail Sending Error", ex);
                return(false);
            }
            return(true);
        }
Esempio n. 26
0
 public static BlogEntry TranslateSearchResultToBlogEntry(IPublishedContent results)
 {
     var helper = new UmbracoHelper(UmbracoContext.Current);
     var post = new BlogEntry();
     post.Title = results.GetPropertyValue<string>("uBlogsyContentTitle");
     var auth = helper.Content(results.GetPropertyValue<string>("uBlogsyPostAuthor"));
     post.Author = auth.uBlogsyAuthorName;
     var date = results.GetPropertyValue<string>("uBlogsyPostDate");
     post.Date = DateTime.Parse(date).ToString("D");
     var image = results.GetPropertyValue<string>("uBlogsyPostImage");
     if (!string.IsNullOrEmpty(image))
     post.Image =  helper.Media(image).umbracoFile;
     post.Summary = results.GetPropertyValue<string>("uBlogsyContentSummary");
     post.Url = results.Url();
     return post;
 }
Esempio n. 27
0
        public List <CasinoModel> GetAllCasinos()
        {
            List <CasinoModel> newsList     = new List <CasinoModel>();
            IPublishedContent  allHomeNodes = _umbracoHelper.Content(1168);

            allHomeNodes.Children.ToList().ForEach(m =>
            {
                newsList.Add(new CasinoModel
                {
                    Body    = m.GetProperty("bodyCasino")?.Value?.ToString(),
                    Title   = m.GetProperty("titleCasino")?.Value?.ToString(),
                    SiteUrl = m.Url
                });
            });
            return(newsList);
        }
Esempio n. 28
0
        public IPublishedContent GetConfiguration(Guid currentContentId, string configAlias)
        {
            string            configurationPropertyValue = string.Empty;
            IPublishedContent configurationNode          = null;

            if (umbracoHelper.TypedContent(currentContentId) != null)
            {
                IPublishedContent content              = umbracoHelper.Content(currentContentId);
                IPublishedContent homeNode             = content.AncestorOrSelf(NodeAlias.Homepage);
                IPublishedContent configCollectionNode = homeNode.Children.Where(n => n.DocumentTypeAlias == NodeAlias.Configuration).FirstOrDefault();
                if (configCollectionNode != null)
                {
                    configurationNode = configCollectionNode.Children.Where(n => n.DocumentTypeAlias == configAlias).FirstOrDefault();
                }
            }
            return(configurationNode);
        }
        /// <summary>
        /// Adds an extension method to UmbracoHelper to calculate a hash for the current visitor for all visitor groups
        /// </summary>
        /// <param name="helper">Instance of UmbracoHelper</param>
        /// <param name="groupMatchingService">The group matching cache</param>
        /// <param name="appCaches">Provides access to the runtime cache</param>
        /// <param name="personalisationGroupsRootNodeId">Id of root node for the personalisation groups</param>
        /// <param name="cacheUserIdentifier">Identifier for the user to use in the cache key (likely the session Id)</param>
        /// <param name="cacheForSeconds">Length of time in seconds to cache the generated personalisation group hash for the visitor</param>
        /// <returns>Has for the visitor for all groups</returns>
        public static string GetPersonalisationGroupsHashForVisitor(
            this UmbracoHelper helper,
            IGroupMatchingService groupMatchingService,
            AppCaches appCaches,
            Guid personalisationGroupsRootNodeId,
            string cacheUserIdentifier,
            int cacheForSeconds)
        {
            var personalisationGroupsRootNode = helper.Content(personalisationGroupsRootNodeId);

            if (!personalisationGroupsRootNode.IsDocumentType(AppConstants.DocumentTypeAliases.PersonalisationGroupsFolder))
            {
                throw new InvalidOperationException(
                          $"The personalisation groups hash for a visitor can only be calculated for a root node of type {AppConstants.DocumentTypeAliases.PersonalisationGroupsFolder}");
            }

            return(GetPersonalisationGroupsHashForVisitor(helper, groupMatchingService, appCaches, personalisationGroupsRootNode, cacheUserIdentifier, cacheForSeconds));
        }
Esempio n. 30
0
        public SiteRoot GetSiteRoot(int currentNodeId)
        {
            var node = _umbracoHelper.Content(currentNodeId);

            if (node == null)
            {
                _logger.Warn <CmsService>($"1.Node with id {currentNodeId} is null");
                return(null);
            }

            var siteNode = node.AncestorsOrSelf().SingleOrDefault(x => x.ContentType.Alias == SiteRoot.ModelTypeAlias) as SiteRoot;

            if (siteNode == null)
            {
                _logger.Warn <CmsService>("siteNode is null");
            }

            return(siteNode);
        }
        /// <summary>
        /// Utility extension to map a <see cref="ILineItem"/> to a BasketViewLine item.
        /// Notice that the ContentId is pulled from the extended data. The name can either
        /// be the Merchello product name via lineItem.Name or the Umbraco content page
        /// name with umbracoHelper.Content(contentId).Name
        ///
        /// </summary>
        /// <param name="lineItem">The <see cref="ILineItem"/> to be mapped</param>
        /// <returns><see cref="BasketViewLineItem"/></returns>
        private static BasketViewLineItem ToBasketViewLineItem(this ILineItem lineItem)
        {
            var umbracoHelper = new UmbracoHelper(UmbracoContext.Current);

            var contentId   = lineItem.ExtendedData.ContainsKey("umbracoContentId") ? int.Parse(lineItem.ExtendedData["umbracoContentId"]) : 0;
            var umbracoName = umbracoHelper.Content(contentId).Name;

            //var merchelloProductName = lineItem.Name;

            return(new BasketViewLineItem()
            {
                Key = lineItem.Key,
                ContentId = contentId,
                ExtendedData = DictionaryToString(lineItem.ExtendedData),
                //Name = merchelloProductName,
                Name = umbracoName,
                Sku = lineItem.Sku,
                UnitPrice = lineItem.Price,
                TotalPrice = lineItem.TotalPrice,
                Quantity = lineItem.Quantity
            });
        }
Esempio n. 32
0
        public CheeryQueryController(
            //IPublishedContentCache cache   /// causes an error
            UmbracoHelper helper,
            IPublishedContentQuery publishedContentQuery,
            IContentService contentService,
            IUmbracoContextFactory umbracoContextFactory)
        {
            _helper = helper;
            _publishedContentQuery = publishedContentQuery;
            _contentService        = contentService;
            _umbracoContextFactory = umbracoContextFactory;

            var page      = helper.Content(2141);
            var otherPage = publishedContentQuery.Content(2141);
            IPublishedContent anotherPage = null;

            using (var cref = umbracoContextFactory.EnsureUmbracoContext())
            {
                var cache = cref.UmbracoContext.Content;
                anotherPage = cache.GetById(2141);
            }
        }
Esempio n. 33
0
        /// <summary>
        /// Uses a Dictionary to store ALL the root nodes in cache.
        ///
        /// Uses the IDs in the Path property of the given node to get the Root node from the cached Dictionary.
        /// </summary>
        /// <param name="nodeId"></param>
        /// <returns></returns>
        public SiteRoot GetSiteRoot(int nodeId)
        {
            var cacheKey = CacheKey.Build <CmsServiceCachedProxy, Dictionary <int, SiteRoot> >("-1");

            var sites = _cache.Get <Dictionary <int, SiteRoot> >(cacheKey);

            SiteRoot siteNode;

            if (sites != null)
            {
                // Use the IDs in the Path property to get the Root node from the cached Dictionary.
                var node    = _umbracoHelper.Content(nodeId);
                var pathIds = node.Path.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Select(x => int.Parse(x));

                foreach (var id in pathIds)
                {
                    if (sites.ContainsKey(id))
                    {
                        siteNode = sites[id];

                        return(siteNode);
                    }
                }
            }

            // get here if there were no cached Site nodes, OR the Site node was not found in the dictionary
            sites    = new Dictionary <int, SiteRoot>();
            siteNode = _cmsService.GetSiteRoot(nodeId);

            if (siteNode != null)
            {
                // GetSiteNode might return null
                sites.Add(siteNode.Id, siteNode);
            }

            _cache.Add(cacheKey, sites);

            return(siteNode);
        }
Esempio n. 34
0
        public string RemoveContributor(int projectId, int memberId)
        {
            var memberShipHelper = new Umbraco.Web.Security.MembershipHelper(UmbracoContext.Current);
            var currentMember    = memberShipHelper.GetCurrentMemberId();

            if (currentMember <= 0)
            {
                return("false");
            }

            var umbracoHelper = new UmbracoHelper(UmbracoContext.Current);
            var content       = umbracoHelper.Content(projectId);

            if (content.GetPropertyValue <int>("owner") != currentMember)
            {
                return("false");
            }

            var projectContributor = new ProjectContributor(projectId, memberId);

            projectContributor.Delete();

            return("true");
        }
        public string SendEmail( int id ) 
        {
            // Parse the posted body string for my json object
            string body = null;
            using ( StreamReader reader = new StreamReader(HttpContext.Current.Request.InputStream) )
            {
                body = reader.ReadToEnd();
            }
            PostedData postedData = JsonConvert.DeserializeObject<PostedData>(body);

            // If testing is true, send to the entered test email address 
            if ( postedData.sendTestEmail && postedData.sendToAddress != String.Empty )
            {
                sendToAddress = postedData.sendToAddress;
            }
            else
            {
                sendToAddress = "*****@*****.**"; // this will be the [email protected] group (and should be set on a config file or via backend maybe?)
            }

            UmbracoHelper umbracoHelper = new UmbracoHelper(UmbracoContext.Current);

            IPublishedContent newsletter = umbracoHelper.Content(id);
            if ( newsletter != null )
            {
                string emailSubject = newsletter.GetPropertyValue("emailSubject").ToString();
                string emailContent = newsletter.GetPropertyValue("emailContent").ToString();
                string newsletterURL = newsletter.UrlAbsolute();

                if ( emailSubject == String.Empty || emailContent == String.Empty )
                {
                    resultStatus = "error";
                    resultMessage = "<strong>Email Subject or Content is empty.</strong> Please fix this before you are able to send the newsletter.";
                }
                else
                {
                    var msg = new MailMessage();
                    msg.To.Add(new MailAddress(sendToAddress));
                    msg.From = new MailAddress("*****@*****.**", "Stuart");
                    msg.Subject = emailSubject;
                    msg.IsBodyHtml = true;
                    
                    emailContent = emailContent.Replace(Environment.NewLine, "<br/>");

                    StringBuilder emailTemplate = new StringBuilder( System.IO.File.ReadAllText(HttpContext.Current.Server.MapPath("~/App_Plugins/EmailNewsletter/BackOffice/views/Email.cshtml")) );
                   
                    string emailBody = emailTemplate.ToString()
                                .Replace("{{emailContent}}", emailContent)
                                .Replace("{{newsletterURL}}", newsletterURL);

                    msg.Body = emailBody;

                    using ( SmtpClient smtp = new SmtpClient() )
                    {
                        smtp.Send(msg);
                        resultStatus = "success";
                        resultMessage = "Email has been sent successfully.";
                    }
                } 
            }


            ReturnJSON result = new ReturnJSON
            {
                status = resultStatus,
                message = resultMessage
            };


            return JsonConvert.SerializeObject(result);

        }
        public ActionResult Replies(int AdvertisementId)
        {
            TempData.Add("MemberCannotViewAdvertisement", false);
            var umbracoHelper = new UmbracoHelper(UmbracoContext.Current);
            var advertisement = umbracoHelper.Content(AdvertisementId) as IPublishedContent;

            var company = Company();
            var companyName = company.Name;

            if (advertisement.Parent.Parent.Id != company.Id)
            {
                TempData.Add("MemberCannotViewAdvertisement", true);
                return CurrentUmbracoPage();
            }

            var model = new RepliesForm();
            model.AdvertisementId = AdvertisementId;
            var replies = GetReplies(AdvertisementId);
            model.Replies = replies;
            // označit reakce za zobrazené
            foreach (var reply in replies)
            {
                if (!reply.ViewDate.HasValue)
                {
                    reply.ViewDate = DateTime.Now;
                    _db.Save(reply);
                }
                else if (!reply.IsViewed)
                {
                    reply.IsViewed = true;
                    _db.Save(reply);
                }
            }
            model.CompanyName = companyName;
            /*
            model.Selection = new Dictionary<int,bool>();
            foreach(var reply in model.Replies)
            {
                model.Selection.Add(reply.Id, false);
            }*/
            model.SubmitAction = ESubmitAction.None;
            model.EmailText = @"Dobrý den,<br /><br />
            děkujeme za Váš zájem o práci v naší firmě. Bohužel, do užšího výběru postoupili jiní uchazeči, kteří lépe odpovídali našim požadavkům.
            Ceníme si Vašich vědomostí a dovedností a proto jsme si dovolili diskrétně uložit Váš životopis do naší databáze uchazečů o zaměstnání.
            Rádi se s Vámi spojíme, vznikne-li u nás pracovní pozice odpovídající Vaší kvalifikaci.<br /><br />
            Sledujte i nadále naše nabídky volných pracovních míst, které naleznete na webovém portálu http://jobsplus.cz/. <br /><br />
            Přejeme Vám mnoho osobních i pracovních úspěchů.<br /><br />S pozdravem,<br />" + companyName;

            return PartialView(model);
        }
        public IPublishedContent Company()
        {
            /*
            var memberPicker = GetMemberId();

            var umbracoHelper = new UmbracoHelper(UmbracoContext.Current);
            var company = umbracoHelper.TypedContentSingleAtXPath("//dtCompanyList").Children.Where("cMemberPicker =" + memberPicker);

            if (company != null && company.Count() > 0)
                return (IPublishedContent)umbracoHelper.TypedContent(Convert.ToInt32(company.First().Id));
            else
                return null;
             */
            var memberCompany = GetMember();
            var umbracoHelper = new UmbracoHelper(UmbracoContext.Current);
            // DKO: získá napojení na stránku firmy z nastavení uživatele v členské sekci
            return umbracoHelper.Content(memberCompany.Properties["CompanyPage"].Value);
        }
Esempio n. 38
0
        public dynamic GetResults(UmbracoHelper umbracoHelper)
        {
            var sql = "exec spSelectDealerContentIDsWithinMiles @0, @1";
            var sqlArgs = new List<object>();
            sqlArgs.Add(this.Miles);
            sqlArgs.Add(this.ZipCode.Replace(" ", "").Trim());
            using (var connection = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["umbracoDbDSN"].ToString()))
            {
                connection.Open();
                var query = ApplicationContext.Current.DatabaseContext.Database.CreateCommand(connection, sql, sqlArgs.ToArray());
                var reader = query.ExecuteReader();

                var contentIDs = new Dictionary<int, decimal>();
                while (reader.Read()) {
                    contentIDs.Add(reader.GetInt32(0), Math.Round(Convert.ToDecimal(reader.GetDouble(1)), 2));
                }
                connection.Close();

                IEnumerable<IPublishedContent> content = ((DynamicPublishedContentList)umbracoHelper.Content(contentIDs.Select(c => c.Key))).AsQueryable<DynamicPublishedContent>();
                switch (this.ServiceType)
                {
                    case "Sales":
                        content = content.Where(c => c.AsDynamic().sales);
                        break;
                    case "Service":
                        content = content.Where(c => c.AsDynamic().service);
                        break;
                    case "Installation":
                        content = content.Where(c => c.AsDynamic().installation);
                        break;
                }

                return content.Select<dynamic, DealerSearchResult>(c => new DealerSearchResult() {
                    Url = c.Url,
                    Name = c.name,
                    Address1 = c.address.address1,
                    Address2 = c.address.address2 ?? "",
                    City = c.address.city,
                    State = c.address.state,
                    Zip = c.address.zip,
                    Phone = c.address.phone ?? "",
                    Lat = c.address.lat,
                    Lng = c.address.@long,
                    Services = GetServices(c),
                    Distance = contentIDs[c.Id],
                    DistanceString = string.Format("{0} - {1} miles", Math.Floor(contentIDs[c.Id]), Math.Ceiling(contentIDs[c.Id]))
                }).OrderBy(c => c.Distance).ToList();
            }
        }