public static async Task <GenerationReturn> Validate(LinkContent linkContent) { var rootDirectoryCheck = UserSettingsUtilities.ValidateLocalSiteRootDirectory(); if (!rootDirectoryCheck.Item1) { return(await GenerationReturn.Error($"Problem with Root Directory: {rootDirectoryCheck.Item2}", linkContent.ContentId)); } if (linkContent == null) { return(await GenerationReturn.Error("Link Content is Null?")); } var(createdUpdatedValid, createdUpdatedValidationMessage) = CommonContentValidation.ValidateCreatedAndUpdatedBy(linkContent, linkContent.Id < 1); if (!createdUpdatedValid) { return(await GenerationReturn.Error(createdUpdatedValidationMessage, linkContent.ContentId)); } var urlValidation = await CommonContentValidation.ValidateLinkContentLinkUrl(linkContent.Url, linkContent.ContentId); if (!urlValidation.isValid) { return(await GenerationReturn.Error(urlValidation.explanation, linkContent.ContentId)); } return(await GenerationReturn.Success("Link Content Validation Successful")); }
public static async Task <(GenerationReturn generationReturn, LinkContent linkContent)> SaveAndGenerateHtml( LinkContent toSave, DateTime?generationVersion, IProgress <string> progress) { var validationReturn = await Validate(toSave); if (validationReturn.HasError) { return(validationReturn, null); } Db.DefaultPropertyCleanup(toSave); toSave.Tags = Db.TagListCleanup(toSave.Tags); await Db.SaveLinkContent(toSave); await SaveLinkToPinboard(toSave, progress); GenerateHtmlAndJson(generationVersion, progress); DataNotifications.PublishDataNotification("Link Generator", DataNotificationContentType.Link, DataNotificationUpdateType.LocalContent, new List <Guid> { toSave.ContentId }); return( await GenerationReturn.Success($"Saved and Generated Content And Html for Links to Add {toSave.Title}"), toSave); }
/// <summary> /// Инициализирует новую команду. /// </summary> /// <param name="linkAddress">SC-адрес ссылки</param> /// <param name="content">данные устанавливаемого содержимого</param> public SetLinkContentCommand(ScAddress linkAddress, LinkContent content) : base(CommandCode.SetLinkContent) { Arguments.Add(this.linkAddress = linkAddress); Arguments.Add(new LinkContent(content.Data.Length));//это число байт контента Arguments.Add(this.content = content); }
public void TestLinkContent() { LinkContent stringLink = new LinkContent("test и тест"); Assert.AreEqual("test и тест", LinkContent.ToString(stringLink.Data)); LinkContent DoubleLink = new LinkContent(123.321d); Assert.AreEqual(123.321d, LinkContent.ToDouble(DoubleLink.Data)); }
public async Task <IActionResult> Add(Guid widgetId, [FromBody] LinkContent model) { await _widgetContentService.InsertAsync(new LinkModel() { Title = model.Title, Url = model.Url, WidgetId = widgetId, }); return(Ok()); }
public LinkMessage(string openId, string title, string description, string url, string picUrl) { ToUser = openId; Link = new LinkContent { Title = title, Description = description, Url = url, PicUrl = picUrl }; }
/// <summary> /// Получение ссылки по содержимому. /// </summary> /// <param name="linkContent">содержимое</param> /// <returns>список SC-адресов</returns> public List <ScAddress> GetLinksByContent(LinkContent linkContent) { var result = new List <ScAddress>(); if (knowledgeBase.IsAvaible) { var command = new FindLinksCommand(linkContent); var response = (FindLinksResponse)knowledgeBase.ExecuteCommand(command); result = response.Addresses; } return(result); }
/// <summary> /// Задание содержимого для ссылки. /// </summary> /// <param name="linkAddress">SC-адрес ссылки</param> /// <param name="content">содержимое для ссылки</param> /// <returns><b>true</b>, если контент задан</returns> public bool SetLinkContent(ScAddress linkAddress, LinkContent content) { bool isSet = false; if (knowledgeBase.IsAvaible) { var command = new SetLinkContentCommand(linkAddress, content); var response = (SetLinkContentResponse)knowledgeBase.ExecuteCommand(command); isSet = response.ContentIsSet; } return(isSet); }
private static string TypeToFilterTag(object content) { return(content switch { NoteContent _ => "post", PostContent _ => "post", ImageContent _ => "image", PhotoContent _ => "image", FileContent _ => "file", LinkContent _ => "link", _ => "other" });
public override int GetHashCode() { //Get hash code for the Name field if it is not null. int hashLinkContent = LinkContent == null ? 0 : LinkContent.GetHashCode(); //Get hash code for the Code field. //int hashProductCode = Code.GetHashCode(); //Calculate the hash code for the product. //return hashProductName ^ hashProductCode; return(hashLinkContent); }
/// <summary> /// Получение содержимого ссылки по известному адресу. /// </summary> /// <param name="scAddress">SC-адрес ссылки</param> /// <returns>содержимое ссылки</returns> public LinkContent GetLinkContent(ScAddress scAddress) { LinkContent content = LinkContent.Invalid; if (knowledgeBase.IsAvaible) { var command = new GetLinkContentCommand(scAddress); var response = (GetLinkContentResponse)knowledgeBase.ExecuteCommand(command); content = new LinkContent(response.LinkContent); } return(content); }
/// <summary> /// Генерирация уникального системного идентификатора для узла на основе адреса узла и префикса. /// </summary> /// <param name="nodeAddress">SC-адрес узла</param> /// <param name="preffix">префикс для узла</param> /// <returns>уникальный идентификатор для узла</returns> public Identifier GenerateUniqueSysIdentifier(ScAddress nodeAddress, string preffix) { Identifier identifier = Identifier.Invalid; Identifier probablyIdentifier = string.Format("{0}_{1}_{2}", preffix, UnixDateTime.FromDateTime(DateTime.Now).GetHashCode(), nodeAddress.GetHashCode()); var content = new LinkContent(probablyIdentifier.Value); var command = new FindLinksCommand(content); var response = (FindLinksResponse)knowledgeBase.ExecuteCommand(command); if (response.Addresses.Count == 0) { identifier = probablyIdentifier; } return(identifier); }
public LinkContentEditorWindow(LinkContent toLoad, bool extractDataFromLink = false) { InitializeComponent(); StatusContext = new StatusControlContext(); StatusContext.RunFireAndForgetBlockingTaskWithUiMessageReturn(async() => { EditorContent = await LinkContentEditorContext.CreateInstance(StatusContext, toLoad, extractDataFromLink); EditorContent.RequestContentEditorWindowClose += (_, _) => { Dispatcher?.Invoke(Close); }; AccidentalCloserHelper = new WindowAccidentalClosureHelper(this, StatusContext, EditorContent); await ThreadSwitcher.ResumeForegroundAsync(); DataContext = this; }); }
/// <summary> /// Получение произвольного идентификатора. узла /// </summary> /// <param name="scAddress">SC-адрес узла</param> /// <param name="identifierType">тип идентификатора</param> /// <returns>идентификатор</returns> public Identifier GetNodeIdentifier(ScAddress scAddress, Identifier identifierType) { Identifier identifier = Identifier.Invalid; if (knowledgeBase.IsAvaible) { var template = new ConstructionTemplate(scAddress, ElementType.ConstantCommonArc_c, ElementType.Link_a, ElementType.PositiveConstantPermanentAccessArc_c, GetNodeAddress(identifierType)); var command = new IterateElementsCommand(template); var response = (IterateElementsResponse)knowledgeBase.ExecuteCommand(command); if (response.Constructions.Count == 1) { ScAddress link = response.Constructions[0][2]; var commandGetLink = new GetLinkContentCommand(link); var responseGetLink = (GetLinkContentResponse)knowledgeBase.ExecuteCommand(commandGetLink); if (responseGetLink.Header.ReturnCode == ReturnCode.Successfull) { identifier = LinkContent.ToString(responseGetLink.LinkContent); } } } return(identifier); }
/// <summary> /// Функция для поиска значения ссылки по отношению, например в констукции bittersweet_apple => nrel_price:[5,5]; /// </summary> /// <param name="node">это адрес узла, например, bittersweet_apple у которого есть ссылка, например [5,5]</param> /// <param name="predicate">это отношение, например nrel_price, которое поясняет, что это за ссылка</param> /// <returns></returns> private double FindValueByPredicate(ScAddress node, ScAddress predicate) { double value = double.NaN; //итерируем конструкцию var template = new ConstructionTemplate(node, ElementType.ConstantCommonArc, ElementType.Link, ElementType.PositiveConstantPermanentAccessArc, predicate); var cmdIterateElements = new IterateElementsCommand(template); var rspIterateElements = (IterateElementsResponse)client.Send(cmdIterateElements); //если число конструкций равно 1, то ищем значение ссылки if (rspIterateElements.Constructions.Count() == 1) { var cmdGetValue = new GetLinkContentCommand(rspIterateElements.Constructions[0][2]); var rspGetValue = (GetLinkContentResponse)client.Send(cmdGetValue); value = LinkContent.ToDouble(rspGetValue.LinkContent); } if (predicate.Offset == 2087) { int i = 0; i = 1; } return(value); }
public static HtmlTag FromLinkContent(LinkContent content) { if (content == null) { return(HtmlTag.Empty()); } var compactContentContainerDiv = new DivTag().AddClass("content-compact-container"); var compactContentMainTextContentDiv = new DivTag().AddClass("link-compact-text-content-container"); var compactContentMainTextTitleTextDiv = new DivTag().AddClass("content-compact-text-content-title-container"); var compactContentMainTextTitleLink = new LinkTag(string.IsNullOrWhiteSpace(content.Title) ? content.Url : content.Title, content.Url) .AddClass("content-compact-text-content-title-link"); compactContentMainTextTitleTextDiv.Children.Add(compactContentMainTextTitleLink); var compactContentSummaryTextDiv = new DivTag().AddClass("link-compact-text-content-summary"); var itemsPartOne = new List <string>(); if (!string.IsNullOrWhiteSpace(content.Author)) { itemsPartOne.Add(content.Author); } if (content.LinkDate != null) { itemsPartOne.Add(content.LinkDate.Value.ToString("M/d/yyyy")); } if (content.LinkDate == null) { itemsPartOne.Add($"Saved {content.CreatedOn:M/d/yyyy}"); } if (itemsPartOne.Any()) { var textPartOneDiv = new DivTag().AddClass("content-compact-text-content-link-summary") .Text(string.Join(" - ", itemsPartOne)); compactContentSummaryTextDiv.Children.Add(textPartOneDiv); } if (!string.IsNullOrWhiteSpace(content.Description)) { var textPartThreeDiv = new DivTag().AddClass("content-compact-text-content-link-summary") .Text(content.Description); compactContentSummaryTextDiv.Children.Add(textPartThreeDiv); } if (!string.IsNullOrWhiteSpace(content.Comments)) { var textPartTwoDiv = new DivTag().AddClass("content-compact-text-content-link-summary") .Text(content.Comments); compactContentSummaryTextDiv.Children.Add(textPartTwoDiv); } compactContentMainTextContentDiv.Children.Add(compactContentMainTextTitleTextDiv); compactContentMainTextContentDiv.Children.Add(compactContentSummaryTextDiv); compactContentContainerDiv.Children.Add(compactContentMainTextContentDiv); return(compactContentContainerDiv); }
/// <summary> /// Handle the contents under the link element /// </summary> /// <param name="link">syndication link element</param> /// <param name="parentResource">parent resource which contains the link.</param> /// <param name="parentResourceSet">resource set of the parent resource</param> /// <param name="parentResourceType">resource type of the parent resource</param> /// <param name="property">property representing the link.</param> /// <param name="typeParameterValue">type parameter value as specified in the type attribute.</param> /// <param name="propertyName">name of the property that this link represents.</param> /// <returns>returns whether there are child elements under link element.</returns> private LinkContent HandleLinkContent( SyndicationLink link, object parentResource, ResourceSetWrapper parentResourceSet, ResourceType parentResourceType, ResourceProperty property, string typeParameterValue, string propertyName) { Debug.Assert(parentResource != null, "parent resource cannot be null"); Debug.Assert(property != null, "property != null"); Debug.Assert(link != null, "link != null"); LinkContent linkContent = LinkContent.NoInlineElementSpecified; foreach (var e in link.ElementExtensions) { // link can contain other elements apart from the inline elements. if (e.OuterNamespace != XmlConstants.DataWebMetadataNamespace || e.OuterName != XmlConstants.AtomInlineElementName) { continue; } // Deep payload cannot be specified for update if (this.Update) { throw DataServiceException.CreateBadRequestError(Strings.BadRequest_DeepUpdateNotSupported); } linkContent = LinkContent.EmptyInlineElementSpecified; using (XmlReader linkReader = e.GetReader()) { while (linkReader.Read()) { if (linkReader.NodeType == XmlNodeType.Element) { string elementName = linkReader.LocalName; string namespaceUri = linkReader.NamespaceURI; if (namespaceUri != XmlConstants.AtomNamespace) { throw DataServiceException.CreateBadRequestError( Strings.BadRequest_InlineElementMustContainValidElement( elementName, XmlConstants.AtomInlineElementName, XmlConstants.AtomFeedElementName, XmlConstants.AtomEntryElementName)); } ResourceSetWrapper targetSet = this.Service.Provider.GetContainer(parentResourceSet, parentResourceType, property); if (targetSet == null) { throw DataServiceException.CreateBadRequestError(Strings.BadRequest_InvalidPropertyNameSpecified(propertyName, parentResourceType.FullName)); } // FeatureVersion needs to be 2.0 if any of the property in the types contained in the resource set has KeepInContent false this.RequestDescription.UpdateAndCheckEpmFeatureVersion(targetSet, this.Service); linkContent = LinkContent.InlineElementContainsData; if (elementName == XmlConstants.AtomEntryElementName) { if (property.Kind != ResourcePropertyKind.ResourceReference) { throw DataServiceException.CreateBadRequestError(Strings.Syndication_EntryElementForReferenceProperties(e.OuterName, propertyName)); } // Make sure if the media type is specified. If its specified, it should better be link SyndicationItem propertyItem; propertyItem = ReadSyndicationItem(this.factory.CreateSyndicationItemFormatter(), linkReader); SegmentInfo propertySegment = CreateSegment(property, propertyName, targetSet, true /* singleResult */); Debug.Assert(propertySegment.TargetKind != RequestTargetKind.OpenProperty, "Open navigation properties are not supported on OpenTypes."); object propertyValue = this.CreateObject(propertySegment, false /* topLevel */, propertyItem); this.Updatable.SetReference(parentResource, propertyName, propertyValue); } else if (elementName == XmlConstants.AtomFeedElementName) { if (property.Kind != ResourcePropertyKind.ResourceSetReference) { throw DataServiceException.CreateBadRequestError(Strings.Syndication_FeedElementForCollections(e.OuterName, propertyName)); } SyndicationFeed propertyFeed; propertyFeed = ReadSyndicationFeed(this.factory.CreateSyndicationFeedFormatter(), linkReader); SegmentInfo propertySegment = CreateSegment(property, propertyName, targetSet, false /* singleResult */); Debug.Assert(propertySegment.TargetKind != RequestTargetKind.OpenProperty, "Open navigation properties are not supported on OpenTypes."); foreach (SyndicationItem item in propertyFeed.Items) { object propertyValue = this.CreateObject(propertySegment, false /* topLevel */, item); if (propertyValue == null) { if (propertySegment.ProjectedProperty != null && propertySegment.ProjectedProperty.Kind == ResourcePropertyKind.ResourceSetReference) { throw DataServiceException.CreateBadRequestError( Strings.BadRequest_CannotSetCollectionsToNull(propertyName)); } } Debug.Assert( propertySegment.TargetSource == RequestTargetSource.Property && propertySegment.TargetKind == RequestTargetKind.Resource && propertySegment.SingleResult == false, "Must be navigation set property."); this.Updatable.AddReferenceToCollection(parentResource, propertyName, propertyValue); } } else { throw DataServiceException.CreateBadRequestError( Strings.BadRequest_InlineElementMustContainValidElement( elementName, XmlConstants.AtomInlineElementName, XmlConstants.AtomFeedElementName, XmlConstants.AtomEntryElementName)); } } } } } return(linkContent); }
private Link(LinkContent linkContent) : base(ElementType.Link_a) { this.linkContent = linkContent; }
public void ApplyLink(Side side, LinkContent content) { _links.Apply(side, content); }
/// <summary> /// Инициализирует новую команду. /// </summary> /// <param name="content">содержимое для поиска</param> public FindLinksCommand(LinkContent content) : base(CommandCode.FindLinks) { Arguments.Add(new LinkContent(content.Data.Length));//это число байт контента Arguments.Add(this.content = content); }
/// <summary> /// Поиск ссылок по содержанию. /// </summary> /// <param name="linkCollection">коллекция</param> /// <param name="linkContent"содержимое></param> /// <returns>список найденных</returns> public static ElementCollection <Link> GetLinksByContent(this ElementCollection <Link> linkCollection, LinkContent linkContent) { List <ScAddress> linkAddresses = linkCollection.KnowledgeBase.Commands.GetLinksByContent(linkContent); var foundedCollection = new ElementCollection <Link>(linkCollection.KnowledgeBase); foreach (var address in linkAddresses) { foundedCollection.Add(linkCollection[address]); } return(foundedCollection); }
public void Run() { Console.WriteLine(LinkContent.ToString(new LinkContent("product").GetBytes())); }
public static async Task <GenerationReturn> SaveLinkToPinboard(LinkContent toSave, IProgress <string> progress) { if (string.IsNullOrWhiteSpace(UserSettingsSingleton.CurrentSettings().PinboardApiToken)) { return(await GenerationReturn.Success("No PinboardApiToken - skipping save to Pinboard", toSave.ContentId)); } var descriptionFragments = new List <string>(); if (!string.IsNullOrWhiteSpace(toSave.Site)) { descriptionFragments.Add($"Site: {toSave.Site}"); } if (toSave.LinkDate != null) { descriptionFragments.Add($"Date: {toSave.LinkDate.Value:g}"); } if (!string.IsNullOrWhiteSpace(toSave.Description)) { descriptionFragments.Add($"Description: {toSave.Description}"); } if (!string.IsNullOrWhiteSpace(toSave.Comments)) { descriptionFragments.Add($"Comments: {toSave.Comments}"); } if (!string.IsNullOrWhiteSpace(toSave.Author)) { descriptionFragments.Add($"Author: {toSave.Author}"); } var tagList = Db.TagListParse(toSave.Tags); tagList.Add(UserSettingsSingleton.CurrentSettings().SiteName); tagList = tagList.Select(x => x.Replace(" ", "-")).ToList(); progress?.Report("Setting up Pinboard"); var bookmark = new Bookmark { Url = toSave.Url, Description = toSave.Title, Extended = string.Join(" ;; ", descriptionFragments), Tags = tagList, CreatedDate = DateTime.Now, Shared = true, ToRead = false, Replace = true }; try { using var pb = new PinboardAPI(UserSettingsSingleton.CurrentSettings().PinboardApiToken); progress?.Report("Adding Pinboard Bookmark"); await pb.Posts.Add(bookmark); } catch (Exception e) { return(await GenerationReturn.Error("Trouble Saving to Pinboard", toSave.ContentId, e)); } progress?.Report("Pinboard Bookmark Complete"); return(await GenerationReturn.Success("Saved to Pinboard", toSave.ContentId)); }
/// <summary>Applies the information from a link to the specified resource.</summary> /// <param name='link'>LinkDescriptor with information to apply.</param> /// <param name="resourceSet">Set for the target resource.</param> /// <param name='resourceType'>Type for the target resource.</param> /// <param name='resource'>Target resource to which information will be applied.</param> /// <param name="propertyName">Name of the property that this link represents.</param> private void ApplyLink(SyndicationLink link, ResourceSetWrapper resourceSet, ResourceType resourceType, object resource, string propertyName) { Debug.Assert(link != null, "link != null"); Debug.Assert(resourceType != null, "resourceType != null"); Debug.Assert(resource != null, "resource != null"); ResourceProperty property = resourceType.TryResolvePropertyName(propertyName); if (property == null) { // Open navigation properties are not supported on OpenTypes throw DataServiceException.CreateBadRequestError(Strings.OpenNavigationPropertiesNotSupportedOnOpenTypes(propertyName)); } if (property.TypeKind != ResourceTypeKind.EntityType) { throw DataServiceException.CreateBadRequestError(Strings.BadRequest_InvalidNavigationPropertyName(propertyName, resourceType.FullName)); } string typeParameterValue = ValidateTypeParameterForNonOpenTypeProperties(link.MediaType, property); LinkContent linkContent = this.HandleLinkContent(link, resource, resourceSet, resourceType, property, typeParameterValue, propertyName); #region Handle bind/unbind operation // If the href was specified empty or an empty inline element was specified, then we will set the // reference to null - this helps in overrriding if there was a default non-value for this property // else if only link element was specified, and then href points to a single result, then we will // perform a bind operation if ((linkContent == LinkContent.NoInlineElementSpecified && link.Uri != null && String.IsNullOrEmpty(link.Uri.OriginalString)) || linkContent == LinkContent.EmptyInlineElementSpecified) { // update the object count when you are performing a bind operation this.CheckAndIncrementObjectCount(); if (property != null && property.Kind == ResourcePropertyKind.ResourceSetReference) { throw DataServiceException.CreateBadRequestError(Strings.BadRequest_CannotSetCollectionsToNull(propertyName)); } // For open properties, we will assume that this is a reference property and set it to null this.Updatable.SetReference(resource, propertyName, null); } else if (linkContent == LinkContent.NoInlineElementSpecified && link.Uri != null && !String.IsNullOrEmpty(link.Uri.OriginalString)) { // update the object count when you are performing a bind operation this.CheckAndIncrementObjectCount(); // If the link points to a reference navigation property, then update the link Uri referencedUri = RequestUriProcessor.GetAbsoluteUriFromReference(link.Uri.OriginalString, this.Service.OperationContext); RequestDescription description = RequestUriProcessor.ProcessRequestUri(referencedUri, this.Service); if (!description.IsSingleResult) { if (property != null && property.Kind == ResourcePropertyKind.ResourceReference) { throw DataServiceException.CreateBadRequestError(Strings.BadRequest_LinkHrefMustReferToSingleResource(propertyName)); } return; } // no need to check for null. For collection properties, they can never be null and that // check has been added below. For reference properties, if they are null, it means unbind // and hence no need to check for null. // Get the resource object targetResource = this.Service.GetResource(description, description.SegmentInfos.Length - 1, null); if (property.Kind == ResourcePropertyKind.ResourceReference) { this.Updatable.SetReference(resource, propertyName, targetResource); } else { WebUtil.CheckResourceExists(targetResource != null, description.LastSegmentInfo.Identifier); this.Updatable.AddReferenceToCollection(resource, propertyName, targetResource); } } #endregion Handle bind/unbind operation }