public void GuidUdiCtorTest() { var guid = Guid.NewGuid(); var udi = new GuidUdi(Constants.UdiEntityType.AnyGuid, guid); Assert.AreEqual(Constants.UdiEntityType.AnyGuid, udi.EntityType); Assert.AreEqual(guid, udi.Guid); Assert.AreEqual("umb://" + Constants.UdiEntityType.AnyGuid + "/" + guid.ToString("N"), udi.ToString()); }
private IEntitySlim GetElement(GuidUdi udi) { if (udi != null) { return(entityService.Get(udi.Guid)); } return(null); }
public IEnumerable <ContentRedirectUrl> GetContentRedirectUrls(string contentUdi) { var mapper = Mapper.Engine; var contentKey = GuidUdi.TryParse(contentUdi, out var guidIdi) ? guidIdi.Guid : default(Guid); var redirectUrlService = Services.RedirectUrlService; var redirects = mapper.Map <IEnumerable <ContentRedirectUrl> >(redirectUrlService.GetContentRedirectUrls(contentKey)); return(redirects); }
protected uSyncDependency CreateDependency(string udiString, DependencyFlags flags) { if (GuidUdi.TryParse(udiString, out GuidUdi udi)) { return(CreateDependency(udi, flags)); } return(null); }
public void SetValue(IContentBase content, string alias, string value) { if (string.IsNullOrWhiteSpace(value)) { content.SetValue(alias, value); return; } var links = JsonConvert.DeserializeObject <JArray>(value); if (links != null) { foreach (var link in links) { GuidUdi udi; string url; // Only do processing on an item if the Id or the url is set if (TryParseJTokenAttr(link, "id", out udi)) { // Check the type of the link var nodeObjectType = link["isMedia"] != null ? UmbracoObjectTypes.Media : UmbracoObjectTypes.Document; // Get the Id corresponding to the Guid // it *should* succeed when deploying, due to dependencies management // nevertheless, assume it can fail, and then create an invalid localLink var idAttempt = _entityService.GetIdForKey(udi.Guid, nodeObjectType); if (idAttempt) { link["id"] = idAttempt.Success ? idAttempt.Result : 0; } } else if (TryParseJTokenAttr(link, "url", out url)) { // Check weather the url attribut of the link contains a udi, if so, replace it with the // path to the file, i.e. the regex replaces <udi> with /path/to/file var newUrl = MediaUdiSrcRegex.Replace(url, match => { var udiString = match.Groups["udi"].ToString(); GuidUdi foundUdi; if (GuidUdi.TryParse(udiString, out foundUdi) && foundUdi.EntityType == Constants.UdiEntityType.Media) { // (take care of nulls) var media = _mediaService.GetById(foundUdi.Guid); if (media != null) { return(media.GetUrl("umbracoFile", _logger)); } } return(string.Empty); }); link["url"] = newUrl; } } content.SetValue(alias, JsonConvert.SerializeObject(links)); } }
private bool TryParseJTokenAttr(JToken link, string attrName, out GuidUdi attrValue) { if (link[attrName] != null) { var val = link[attrName].ToString(); return(GuidUdi.TryParse(val, out attrValue)); } attrValue = null; return(false); }
private void CreateVideo(GuidUdi parentUdi, string title, string thumbnailUrl, string videoUrl) { var video = _contentService.CreateContent(title, parentUdi, "video"); video.SetValue("title", title); video.SetValue("videoThumbnailImageURL", thumbnailUrl); video.SetValue("videoLinkURL", videoUrl); _contentService.SaveAndPublish(video); }
/// <summary> /// Given a parent id which could be a GUID, UDI or an INT, this will resolve the INT /// </summary> /// <param name="parentId"></param> /// <param name="validatePermissions"> /// If true, this will check if the current user has access to the resolved integer parent id /// and if that check fails an unauthorized exception will occur /// </param> /// <returns></returns> private int GetParentIdAsInt(string parentId, bool validatePermissions) { int intParentId; GuidUdi parentUdi; // test for udi if (GuidUdi.TryParse(parentId, out parentUdi)) { parentId = parentUdi.Guid.ToString(); } //if it's not an INT then we'll check for GUID if (int.TryParse(parentId, out intParentId) == false) { // if a guid then try to look up the entity Guid idGuid; if (Guid.TryParse(parentId, out idGuid)) { var entity = Services.EntityService.Get(idGuid); if (entity != null) { intParentId = entity.Id; } else { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, "The passed id doesn't exist")); } } else { throw new HttpResponseException( Request.CreateValidationErrorResponse("The request was not formatted correctly, the parentId is not an integer, Guid or UDI")); } } //ensure the user has access to this folder by parent id! if (validatePermissions && CheckPermissions( new Dictionary <string, object>(), Security.CurrentUser, Services.MediaService, Services.EntityService, AppCaches, intParentId) == false) { throw new HttpResponseException(Request.CreateResponse( HttpStatusCode.Forbidden, new SimpleNotificationModel(new Notification( Services.TextService.Localize("speechBubbles/operationFailedHeader"), Services.TextService.Localize("speechBubbles/invalidUserPermissionsText"), NotificationStyle.Warning)))); } return(intParentId); }
public IEnumerable <int> GetAndEnsureNodeIdsForTags(string currentNodeId, string tags, string containerId, string documentTypeAlias) { var udi = GuidUdi.Parse(containerId); var entitiy = Services.EntityService.Get(udi.Guid); var cs = Services.ContentService; if (string.IsNullOrWhiteSpace(tags)) { return(new List <int>()); } // put posted tags in an array var postedTags = tags.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); // get the current node var node = cs.GetById(int.Parse(currentNodeId)); // get all existing tag nodes in container var tagContainer = cs.GetById(entitiy.Id); var allTagNodes = cs.GetPagedChildren(tagContainer.Id, 0, int.MaxValue, out var count).Where(x => x.ContentType.Alias == documentTypeAlias); bool hasNewTags = false; foreach (string postedTag in postedTags) { // get tag names which do not already exist in the tag container bool found = allTagNodes.Any(x => x.Name == postedTag); if (!found) { // tag node doesnt exist so create new node var dic = new Dictionary <string, object>() { { documentTypeAlias, postedTag } }; var newTag = cs.CreateContent(postedTag, tagContainer.GetUdi(), documentTypeAlias); cs.SaveAndPublish(newTag); hasNewTags = true; } } // re-get container because new nodes might have been added. tagContainer = cs.GetById(entitiy.Id); if (hasNewTags) { // new tag so sort! cs.Sort(cs.GetPagedChildren(tagContainer.Id, 0, int.MaxValue, out var count1).OrderBy(x => x.Name)); } // get all tag ids, and return var tagIds = cs.GetPagedChildren(tagContainer.Id, 0, int.MaxValue, out var count2).Where(x => postedTags.Contains(x.Name)).Select(x => x.Id); return(tagIds); }
public HttpResponseMessage CheckDescendants(string udi) { var result = false; GuidUdi guidUdi; if (GuidUdi.TryParse(udi, out guidUdi)) { result = this.entityRelationService.CheckLinksInDescendants(guidUdi); } return(this.Request.CreateResponse(HttpStatusCode.OK, result)); }
public string GetValue(Property property, ICollection <ArtifactDependency> dependencies) { var value = property.Value as string; if (string.IsNullOrWhiteSpace(value)) { return(null); } if (value.DetectIsJson() == false) { return(null); } var relatedLinks = JsonConvert.DeserializeObject <JArray>(value); if (relatedLinks == null) { return(string.Empty); } foreach (var relatedLink in relatedLinks) { //Get the value from the JSON object var isInternal = Convert.ToBoolean(relatedLink["isInternal"]); //We are only concerned about internal links if (!isInternal) { continue; } var linkIntId = Convert.ToInt32(relatedLink["link"]); //get the guid corresponding to the id //it *can* fail if eg the id points to a deleted content, //and then we use an empty guid var guidAttempt = _entityService.GetKeyForId(linkIntId, UmbracoObjectTypes.Document); if (guidAttempt.Success) { // replace the picked content id by the corresponding Udi as a dependancy var udi = new GuidUdi(Constants.UdiEntityType.Document, guidAttempt.Result); dependencies.Add(new ArtifactDependency(udi, false, ArtifactDependencyMode.Exist)); //Set the current relatedlink 'internal' & 'link' properties to UDIs & not int's relatedLink["link"] = udi.ToString(); relatedLink["internal"] = udi.ToString(); } } //Serialise the new updated object with UDIs in it to JSON to transfer across the wire return(JsonConvert.SerializeObject(relatedLinks)); }
/// <summary> /// Follows internal redirections through the <c>umbracoInternalRedirectId</c> document property. /// </summary> /// <returns>A value indicating whether redirection took place and led to a new published document.</returns> /// <remarks> /// <para>Redirecting to a different site root and/or culture will not pick the new site root nor the new culture.</para> /// <para>As per legacy, if the redirect does not work, we just ignore it.</para> /// </remarks> private bool FollowInternalRedirects(PublishedRequest request) { if (request.PublishedContent == null) { throw new InvalidOperationException("There is no PublishedContent."); } // don't try to find a redirect if the property doesn't exist if (request.PublishedContent.HasProperty(Constants.Conventions.Content.InternalRedirectId) == false) { return(false); } var internalRedirectId = request.PublishedContent.Value(Constants.Conventions.Content.InternalRedirectId)?.ToString(); if (internalRedirectId == null) { // no value stored, just return, no need to log return(false); } if (int.TryParse(internalRedirectId, out var internalRedirectIdAsInt) && internalRedirectIdAsInt == request.PublishedContent.Id) { // redirect to self _logger.Debug <PublishedRouter>("FollowInternalRedirects: Redirecting to self, ignore"); return(false); } IPublishedContent internalRedirectNode = null; if (internalRedirectIdAsInt > 0) { // try and get the redirect node from a legacy integer ID internalRedirectNode = request.UmbracoContext.Content.GetById(internalRedirectIdAsInt); } else if (GuidUdi.TryParse(internalRedirectId, out var internalRedirectIdAsUdi)) { // try and get the redirect node from a UDI Guid internalRedirectNode = request.UmbracoContext.Content.GetById(internalRedirectIdAsUdi.Guid); } if (internalRedirectNode == null) { _logger.Debug <PublishedRouter, object>("FollowInternalRedirects: Failed to redirect to id={InternalRedirectId}: no such published document.", request.PublishedContent.GetProperty(Constants.Conventions.Content.InternalRedirectId).GetSourceValue()); return(false); } request.SetInternalRedirectPublishedContent(internalRedirectNode); // don't use .PublishedContent here _logger.Debug <PublishedRouter, int>("FollowInternalRedirects: Redirecting to id={InternalRedirectId}", internalRedirectIdAsInt); return(true); }
public IEnumerable <DataListItem> GetItems(Dictionary <string, object> config) { var preview = true; var parentNode = config.GetValueAs("parentNode", string.Empty); var startNode = default(IPublishedContent); if (parentNode.InvariantStartsWith("umb://document/") == false) { var nodeContextId = default(int?); var umbracoContext = _umbracoContextAccessor.UmbracoContext; // NOTE: First we check for "id" (if on a content page), then "parentId" (if editing an element). if (int.TryParse(umbracoContext.HttpContext.Request.QueryString.Get("id"), out var currentId) == true) { nodeContextId = currentId; } else if (int.TryParse(umbracoContext.HttpContext.Request.QueryString.Get("parentId"), out var parentId) == true) { nodeContextId = parentId; } if (nodeContextId == -20) { // TODO: [UP-FOR-GRABS] If the ID = -20, then we can assume that it's come from Nested Content. What to do? ¯\_(ツ)_/¯ } IEnumerable <string> getPath(int id) => umbracoContext.Content.GetById(preview, id)?.Path.ToDelimitedList().Reverse(); bool publishedContentExists(int id) => umbracoContext.Content.GetById(preview, id) != null; var parsed = UmbracoXPathPathSyntaxParser.ParseXPathQuery(parentNode, nodeContextId, getPath, publishedContentExists); if (string.IsNullOrWhiteSpace(parsed) == false && parsed.StartsWith("$") == false) { startNode = umbracoContext.Content.GetSingleByXPath(preview, parsed); } } else if (GuidUdi.TryParse(parentNode, out var udi) == true && udi.Guid != Guid.Empty) { startNode = _umbracoContextAccessor.UmbracoContext.Content.GetById(preview, udi.Guid); } if (startNode != null) { return(startNode.Children.Select(x => new DataListItem { // TODO: [LK:2020-12-03] If multi-lingual is enabled, should the `.Name` take the culture into account? Name = x.Name, Value = Udi.Create(UmbConstants.UdiEntityType.Document, x.Key).ToString(), Icon = ContentTypeCacheHelper.TryGetIcon(x.ContentType.Alias, out var icon, _contentTypeService) == true ? icon : UmbConstants.Icons.Content, Description = x.TemplateId > 0 ? x.Url() : string.Empty, Disabled = x.IsPublished() == false, }));
protected uSyncDependency CreateDependency(GuidUdi udi, DependencyFlags flags) { var entity = GetElement(udi); return(new uSyncDependency() { Name = entity == null?udi.ToString() : entity.Name, Udi = udi, Flags = flags, Order = DependencyOrders.OrderFromEntityType(udi.EntityType), Level = entity == null ? 0 : entity.Level }); }
public string getImageURLFromUDI(string imageUDI) { try { var umbracoHelper = new Umbraco.Web.UmbracoHelper(Umbraco.Web.UmbracoContext.Current); var imageGuidUdi = GuidUdi.Parse(imageUDI); var imageNodeID = ApplicationContext.Current.Services.EntityService.GetIdForKey(imageGuidUdi.Guid, (UmbracoObjectTypes)Enum.Parse(typeof(UmbracoObjectTypes), imageGuidUdi.EntityType, true)); var imageNode = umbracoHelper.TypedMedia(imageNodeID.Result); return(imageNode.Url); } catch { return(""); } }
public static string Url(this MeganavV8Item item, string culture = null, UrlMode mode = UrlMode.Default) { var umbracoContext = Umbraco.Web.Composing.Current.UmbracoContext; if (umbracoContext == null) { throw new InvalidOperationException("Cannot resolve a Url when Current.UmbracoContext is null."); } if (umbracoContext.UrlProvider == null) { throw new InvalidOperationException( "Cannot resolve a Url when Current.UmbracoContext.UrlProvider is null."); } if (item.Udi != null) { var contentItem = GuidUdi.TryParse(item.Udi.ToString(), out var udi) ? Current.UmbracoContext.Content.GetById(item.Udi) : Current.UmbracoContext.Content.GetById(item.Id); if (contentItem != null) { switch (contentItem.ContentType.ItemType) { case PublishedItemType.Content: string url; if (!string.IsNullOrEmpty(item.Anchor)) { url = umbracoContext.UrlProvider.GetUrl(contentItem, mode, culture) + item.Anchor; } else { url = umbracoContext.UrlProvider.GetUrl(contentItem, mode, culture); } return(url); case PublishedItemType.Media: return(umbracoContext.UrlProvider.GetMediaUrl(contentItem, mode, culture, Umbraco.Core.Constants.Conventions.Media.File)); default: throw new NotSupportedException(); } } } return(item.Url); }
public Exercise GetExercise(int id) { IContentService cs = Services.ContentService; var exercise = cs.GetById(id); Exercise e = new Exercise(); e.Id = exercise.Id; e.Name = exercise.Name; e.Title = exercise.GetValue <string>("Title"); if (exercise.GetValue <string>("ImageLinks") != null) { var imageString = exercise.GetValue <string>("ImageLinks"); var imageGuidUdi = GuidUdi.Parse(imageString); var imageNodeId = ApplicationContext.Current.Services.EntityService.GetIdForKey(imageGuidUdi.Guid, (UmbracoObjectTypes)Enum.Parse(typeof(UmbracoObjectTypes), imageGuidUdi.EntityType, true)); var imageNode = Umbraco.TypedMedia(imageNodeId.Result); e.ImageLinks = apiUrl + imageNode.Url; } else { e.ImageLinks = null; } e.Description = exercise.GetValue <string>("Description"); e.Repetition = exercise.GetValue <string>("Repetition"); if (exercise.GetValue <string>("Breaks") != null) { e.Breaks = exercise.GetValue <string>("Breaks"); } else { e.Breaks = null; } if (exercise.GetValue <string>("Focus") != null) { e.Focus = exercise.GetValue <string>("Focus"); } else { e.Breaks = null; } e.ExerciseID = exercise.GetValue <int>("ExerciseID"); e.UserGroupID = exercise.GetValue <int>("UserGroupID"); e.ApiExerciseID = exercise.GetValue <string>("ApiExerciseID"); return(e); }
public ActionResult HandleFormSubmit(ContactForm model) { if (!ModelState.IsValid) { return(CurrentUmbracoPage()); } MailMessage message = new MailMessage(); //The recipient's email message.To.Add("*****@*****.**"); message.Subject = model.Subject; message.From = new MailAddress(model.Email, model.Name); message.Body = model.Message; using (SmtpClient smtp = new SmtpClient()) { smtp.DeliveryMethod = SmtpDeliveryMethod.Network; smtp.UseDefaultCredentials = false; smtp.EnableSsl = true; smtp.Host = "smtp.gmail.com"; smtp.Port = 587; //Add your own credentials here, otherwise the form won't work //Those are the credentials for the account that sends the email smtp.Credentials = new System.Net.NetworkCredential("gmail", "app.password"); // send mail smtp.Send(message); TempData["success"] = true; } //Get the GuidUdi of the current page GuidUdi currentPageUdi = new GuidUdi(CurrentPage.ContentType.ItemType.ToString(), CurrentPage.Key); // Create the new content type IContent msg = Services.ContentService.CreateContent(model.Subject, currentPageUdi, "message"); msg.SetValue("messageName", model.Name); msg.SetValue("email", model.Email); msg.SetValue("subject", model.Subject); msg.SetValue("messageContent", model.Message); msg.SetValue("umbracoNaviHide", true); //Save Services.ContentService.Save(msg); return(RedirectToCurrentUmbracoPage()); }
public void SetValue(IContentBase content, string alias, string value) { if (string.IsNullOrWhiteSpace(value)) { content.SetValue(alias, value); return; } var relatedLinks = JsonConvert.DeserializeObject <JArray>(value); foreach (var relatedLink in relatedLinks) { //Get the value from the JSON object var isInternal = Convert.ToBoolean(relatedLink["isInternal"]); //We are only concerned about internal links if (!isInternal) { continue; } var relatedLinkValue = relatedLink["link"].ToString(); //Check if related links is stored as an int if (int.TryParse(relatedLinkValue, out var relatedLinkInt)) { //Update the JSON back to the int ids on this env relatedLink["link"] = relatedLinkInt; relatedLink["internal"] = relatedLinkInt; } else { //Get the UDI value in the JSON var pickedUdi = GuidUdi.Parse(relatedLinkValue); //Lets use entitiy sevice to get the int ID for this item on the new environment //Get the Id corresponding to the Guid //it *should* succeed when deploying, due to dependencies management //nevertheless, assume it can fail, and then create an invalid localLink var idAttempt = _entityService.GetIdForKey(pickedUdi.Guid, UmbracoObjectTypes.Document); //Update the JSON back to the int ids on this env relatedLink["link"] = idAttempt.Success ? idAttempt.Result : 0; relatedLink["internal"] = idAttempt.Success ? idAttempt.Result : 0; } } //Save the updated JSON with replaced UDIs for int IDs content.SetValue(alias, JsonConvert.SerializeObject(relatedLinks)); }
public ActionResult HandleFormSubmit(ContactForm model) { if (!ModelState.IsValid) { return(CurrentUmbracoPage()); } //Send email message //The method data receives the data as an object of type ContactForm MailMessage message = new MailMessage(); message.To.Add("*****@*****.**"); message.Subject = model.Subject; message.From = new MailAddress(model.Email, model.Name); message.Body = model.Message; //Send the message as an email using (SmtpClient smtp = new SmtpClient()) { smtp.DeliveryMethod = SmtpDeliveryMethod.Network; smtp.UseDefaultCredentials = false; smtp.EnableSsl = true; smtp.Host = "smtp.gmail.com"; smtp.Port = 587; //Removed Network credentials smtp.Credentials = new System.Net.NetworkCredential("", ""); // send mail smtp.Send(message); } //Display a message to the user in case of success TempData["success"] = true; //Get the GuildUdi of the current page GuidUdi currentPageUdi = new GuidUdi(CurrentPage.ContentType.ItemType.ToString(), CurrentPage.Key); //Create the new content type with parameters: string name, Udi parentId , string contentTypeAlias IContent msg = Services.ContentService.CreateContent(model.Subject, currentPageUdi, "message"); msg.SetValue("messageName", model.Name); msg.SetValue("email", model.Email); msg.SetValue("subject", model.Subject); msg.SetValue("messageContent", model.Message); msg.SetValue("umbracoNaviHide", true); //Save Services.ContentService.Save(msg); //declare a method that receives form input and send the page back to the client return(RedirectToCurrentUmbracoPage()); }
public ActionResult HandleFormSubmit(ContactForm model) { if (!ModelState.IsValid) { return(CurrentUmbracoPage()); } TempData["success"] = true; MailMessage message = new MailMessage(); message.To.Add("*****@*****.**"); message.Subject = model.Subject; message.From = new MailAddress(model.Email, model.Name); message.Body = model.Message; //ensure there is no errors, otherwise display errors if there is using (SmtpClient smtp = new SmtpClient()) { smtp.DeliveryMethod = SmtpDeliveryMethod.Network; smtp.UseDefaultCredentials = false; smtp.EnableSsl = true; smtp.Host = "smtp.gmail.com"; smtp.Port = 587; smtp.Credentials = new System.Net.NetworkCredential("*****@*****.**", "nxjhkegvwxunkvmo"); // send mail smtp.Send(message); } //Get the GuildUdi of the current page GuidUdi currentPageUdi = new GuidUdi(CurrentPage.ContentType.ItemType.ToString(), CurrentPage.Key); //Create the new content type IContent msg = Services.ContentService.CreateContent(model.Subject, currentPageUdi, "message"); msg.SetValue("messageName", model.Name); msg.SetValue("email", model.Email); msg.SetValue("subject", model.Subject); msg.SetValue("messageContent", model.Message); msg.SetValue("umbracoNaviHide", true); //Save Services.ContentService.Save(msg); return(RedirectToCurrentUmbracoPage()); }
protected IEnumerable <uSyncDependency> GetItemDependency(JObject itemValue, DependencyFlags flags) { if (itemValue == null) { return(Enumerable.Empty <uSyncDependency>()); } if (itemValue.ContainsKey("contentData")) { // nested content mode. var contentData = itemValue.Value <JObject>("contentData"); var docTypeAlias = contentData.Value <string>(this.docTypeAliasValue); if (contentData == null || docTypeAlias == null) { return(Enumerable.Empty <uSyncDependency>()); } var docType = GetDocType(docTypeAlias); if (docType == null) { return(Enumerable.Empty <uSyncDependency>()); } List <uSyncDependency> dependencies = new List <uSyncDependency>(); var docTypeDependency = CreateDocTypeDependency(docType, flags); dependencies.AddNotNull(docTypeDependency); dependencies.AddRange(GetPropertyDependencies(contentData, docType, flags)); return(dependencies); } else { // linked content mode var key = itemValue.Value <Guid>("key"); if (key != null) { // we need to include the ancestors of any included // bento items, to ensure we get the library structure // of the bento items as part of the sync. var bentoFlags = flags | DependencyFlags.IncludeAncestors; var udi = GuidUdi.Create(Constants.UdiEntityType.Document, key); return(CreateDependency(udi as GuidUdi, bentoFlags).AsEnumerableOfOne()); } } return(Enumerable.Empty <uSyncDependency>()); }
public IEnumerable <string> GetTags(int currentNodeId, string containerId, string documentTypeAlias) { //var udi = Udi.Parse(containerId); var udi = GuidUdi.Parse(containerId); var entitiy = Services.EntityService.Get(udi.Guid); var cs = Services.ContentService; /* Get the tags container */ var tagContainer = cs.GetById(entitiy.Id); /* Compile a list of all tag pages that exist as children of the tags container */ var tags = cs.GetPagedChildren(tagContainer.Id, 0, int.MaxValue, out var count).Where(x => x.ContentType.Alias == documentTypeAlias).Select(x => x.Name); return(tags); }
public void CanSerialize() { var udi = new GuidUdi("test", Guid.Parse("3382d5433b5749d08919bc9961422a1f")); var artifact = new TestArtifact(udi, new List <ArtifactDependency>()) { Name = "Test Name", Alias = "testAlias", }; var serialized = JsonConvert.SerializeObject(artifact); var expected = "{\"Udi\":\"umb://test/3382d5433b5749d08919bc9961422a1f\",\"Dependencies\":[],\"Name\":\"Test Name\",\"Alias\":\"testAlias\"}"; Assert.AreEqual(expected, serialized); }
protected override void AddSingleValue(Document doc, object value) { if (value is string valueString) { var ids = valueString.Split(new[] { Separator }, StringSplitOptions.RemoveEmptyEntries); foreach (var id in ids) { if (GuidUdi.TryParse(id, out GuidUdi udi) == true) { doc.Add(new Field(FieldName, udi.Guid.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED)); } } } }
public static void Converting_Boxed_Udi_To_A_Udi_Returns_Original_Udi_Value() { // Arrange UdiParser.ResetUdiTypes(); Udi sample = new GuidUdi(Constants.UdiEntityType.AnyGuid, Guid.NewGuid()); // Act bool success = UmbracoHelper.ConvertIdObjectToUdi( sample, out Udi result ); // Assert Assert.IsTrue(success); Assert.That(result, Is.EqualTo(sample)); }
public RedirectUrlSearchResult RedirectUrlsForContentItem(string contentUdi) { var redirectsResult = new RedirectUrlSearchResult(); if (GuidUdi.TryParse(contentUdi, out var guidIdi)) { var redirectUrlService = Services.RedirectUrlService; var redirects = redirectUrlService.GetContentRedirectUrls(guidIdi.Guid); redirectsResult.SearchResults = Mapper.Map <IEnumerable <ContentRedirectUrl> >(redirects).ToArray(); //not doing paging 'yet' redirectsResult.TotalCount = redirects.Count(); redirectsResult.CurrentPage = 1; redirectsResult.PageCount = 1; } return(redirectsResult); }
public IEnumerable <UmbracoEntityReference> GetReferences(object value) { var rawJson = value == null ? string.Empty : value is string str ? str : value.ToString(); if (rawJson.IsNullOrWhiteSpace()) { yield break; } var mediaWithCropsDtos = JsonConvert.DeserializeObject <MediaPickerWithCropsValueConverter.MediaWithCropsDto[]>(rawJson); foreach (var mediaWithCropsDto in mediaWithCropsDtos) { yield return(new UmbracoEntityReference(GuidUdi.Create(Constants.UdiEntityType.Media, mediaWithCropsDto.MediaKey))); } }
private void MapOldToNewUdis(Dictionary <Udi, Udi> oldToNew, IEnumerable <BlockItemData> blockData, Func <Guid> createGuid) { foreach (var data in blockData) { // This should never happen since a FormatException will be thrown if one is empty but we'll keep this here if (data.Udi == null) { throw new InvalidOperationException("Block data cannot contain a null UDI"); } // replace the UDIs var newUdi = GuidUdi.Create(Constants.UdiEntityType.Element, createGuid()); oldToNew[data.Udi] = newUdi; data.Udi = newUdi; } }
public HttpResponseMessage CheckLinkedItems([FromBody] string[] udis) { var listUdis = new List <Udi>(); foreach (var stringUdi in udis) { GuidUdi guidUdi; if (GuidUdi.TryParse(stringUdi, out guidUdi)) { listUdis.Add(guidUdi); } } return(this.Request.CreateResponse(HttpStatusCode.OK, this.entityRelationService.GetUsedItemsFromList(listUdis))); }