示例#1
0
        //###############################################################################

        public void SaveFeedEntry(FeedEntry item)
        {
            //Datensatz erstellen
            string read = DatabaseHelper.BOOL_FALSE;

            if (item.MarkedRead)
            {
                read = DatabaseHelper.BOOL_TRUE;
            }

            ContentValues values = new ContentValues();

            values.Put(DatabaseHelper.FEED_TABLE_COL_KEY, item.Key);
            values.Put(DatabaseHelper.FEED_TABLE_COL_TITLE, item.Title);
            values.Put(DatabaseHelper.FEED_TABLE_COL_DATE, TBL.EncodeDateToString(item.Date));
            values.Put(DatabaseHelper.FEED_TABLE_COL_AUTHOR, item.Author);
            values.Put(DatabaseHelper.FEED_TABLE_COL_BODY, item.BodyText);
            values.Put(DatabaseHelper.FEED_TABLE_COL_READ, read);

            //Datenbank aktualisieren
            //Neuen Eintrag anlegen
            int ID = (int)database.Insert(DatabaseHelper.FEED_TABLE, null, values);

            item.ID = ID;

            //Feed-Anhänge aktualisieren
            foreach (var attachment in item.Attachments)
            {
                SaveAttachment(attachment, DatabaseHelper.OWNER_FEED, item.ID, false);
            }
        }
        private string SerializeFeedEntryToXml(FeedEntry obj, FeedSerializer serializer)
        {
            if (null == obj)
            {
                return(null);
            }

            try
            {
                String       xml          = null;
                MemoryStream memoryStream = new MemoryStream();

                XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);

                serializer.SaveToStream(obj, memoryStream, null);

                xml = UTF8ByteArrayToString(memoryStream.ToArray());
                return(xml);
            }
            catch
            {
                //Debug.WriteLine(e);
                return(null);
            }
        }
        private string GetFilename(FeedEntry feedEntry, ContractEvent item)
        {
            // Filename format : [Entry.Updated]_[ContractNumber]_v[ContractVersion]_[Entry.BookmarkId].xml
            string filename = $"{feedEntry.Updated:yyyyMMddHHmmss}_{item.ContractNumber}_v{item.ContractVersion}_{item.BookmarkId}.xml";

            return(filename);
        }
示例#4
0
        public Feed GetByGenres(string genre)
        {
            genre = Uri.UnescapeDataString(genre ?? "");

            var feed = new Feed();

            feed.Id    = "tag:root:genres" + (genre == "" ? "" : $":{genre}");
            feed.Title = genre == "" ? T._("Books by genres") : T._("Books in the genre of {0}", GenreExtensions.GetDisplayName(genre));
            AddNavigation($"{Prefix}/genres/{Uri.EscapeDataString(genre)}", feed);

            var searcher = new LuceneIndexStorage();
            var genres   = searcher.GetAllGenres(genre);

            foreach (var k in genres)
            {
                var tag   = k.Value.Item2 ? "genre" : "genres";
                var url   = k.Value.Item1;
                var entry = new FeedEntry();
                entry.Id    = $"tag:root:{tag}:{url}";
                entry.Title = k.Key;
                entry.Links.Add(new FeedLink {
                    Type = FeedLinkType.AtomAcquisition, Href = $"{Prefix}/{tag}/{Uri.EscapeDataString(url)}"
                });
                entry.Content = new FeedEntryContent {
                    Text = T._("Books in the genre of {0}", k.Key)
                };
                feed.Entries.Add(entry);
            }

            return(feed);
        }
示例#5
0
        // RSS Feed conversion. RSS has no summary
        private FeedEntry CreateFeedEntry(ISyndicationItem entry, Feed feed)
        {
            var link = GetLinkFromFeedEntry(entry.Links);

            var feedEntry = new FeedEntry()
            {
                FeedTitle   = feed.Name,
                Id          = entry.Id,
                Title       = entry.Title,
                Summary     = null,
                Description = entry.Description,
                LastUpdated = entry.LastUpdated,
                Published   = entry.Published,
                Link        = link
            };

            if (feedEntry.Id == null)
            {
                feedEntry.Id = CreateIdFromFeedEntry(feedEntry);
            }

            //TODO: This could be better
            if (entry.Categories != null)
            {
                foreach (var category in entry.Categories)
                {
                    feedEntry.Tags.Add(category.Name);
                }
            }

            return(feedEntry);
        }
示例#6
0
        // Sometimes no id is given.
        private string CreateIdFromFeedEntry(FeedEntry entry)
        {
            using (log.BeginScope($"{ nameof(FeedService) }->{ nameof(CreateIdFromFeedEntry) }" + " with entry: {Entry}", entry))
            {
                // Check if there is an id
                if (entry.Id != null)
                {
                    return(entry.Id);
                }

                // Create a new Id
                var key = $"{entry.FeedTitle}-{entry.Title}-{entry.Link}";

                var mySHA256 = SHA256Managed.Create();
                var hash     = mySHA256.ComputeHash(Encoding.UTF8.GetBytes(key));

                var id = new System.Text.StringBuilder();

                foreach (byte theByte in hash)
                {
                    id.Append(theByte.ToString("x2"));
                }

                log.LogDebug("Created id: {Id} from key: {Key}", id, key);

                return(id.ToString());
            }
        }
示例#7
0
        public override SdataTransactionResult Update(FeedEntry payload)
        {
            //Transform account
            Document        document        = GetTransformedDocument(payload);
            AccountDocument accountDocument = (AccountDocument)_entity.GetDocumentTemplate();

            accountDocument.Id    = document.Id;
            accountDocument.CrmId = GetTradingAccountUuid(document.Id);
            accountDocument.people.documents.Add(document);
            // Update Document

            List <TransactionResult> transactionResults = new List <TransactionResult>();

            _entity.Update(accountDocument, _context.Config, ref transactionResults);
            SdataTransactionResult sdTrResult = GetSdataTransactionResult(transactionResults,
                                                                          _context.OriginEndPoint, SupportedResourceKinds.tradingAccounts);

            if (sdTrResult != null)
            {
                sdTrResult.ResourceKind = _resourceKind;

                sdTrResult.HttpMessage = "PUT";
            }
            return(sdTrResult);
        }
        private SyndicationItem BuildSyndicationItem(FeedEntry u)
        {
            var item = new SyndicationItem
            {
                Title           = new TextSyndicationContent(u.Title),
                BaseUri         = null,
                LastUpdatedTime = u.Updated,
                Content         = new UrlSyndicationContent(new Uri(u.Content.Src, UriKind.Absolute), "octet/stream")
            };

            item.Categories.Add(new SyndicationCategory(u.Category));
            item.Summary = new TextSyndicationContent(u.Summary);
            item.Authors.Add(new SyndicationPerson {
                Name = u.Author.Name
            });
            item.PublishDate = u.Published;
            if (!string.IsNullOrEmpty(u.MoreInfo))
            {
                item.Links.Add(SyndicationLink.CreateAlternateLink(new Uri(u.MoreInfo), "More Information"));
            }
            item.ElementExtensions.Add(new XElement(XName.Get("Vsix", VsixNamespace),
                                                    new XElement(XName.Get("Id", VsixNamespace), u.Vsix.Id),
                                                    new XElement(XName.Get("Version", VsixNamespace), u.Vsix.Version)).
                                       CreateReader());
            return(item);
        }
示例#9
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="obj">must be of type <see cref="PayloaContainer"/>.</param>
        /// <returns></returns>

        public string Serialize(object obj)
        {
            // if obj == null -> append null value and return
            if (null == obj)
            {
                return(NULL);
            }

            FeedEntry payloadObj = obj as FeedEntry;

            if (null == payloadObj)
            {
                throw new ArgumentException(string.Format("The object given must implement {0}.", typeof(FeedEntry).FullName), "obj");
            }


#warning WORKAROUND: Problems with enum types
            try
            {
                //object compositeObj = this.GetPayloadObject(payloadObj);

                // serialize the composite payload object
                return(this.SerializeCompositeObject(payloadObj));
            }
            catch
            {
                return("");
            }
        }
示例#10
0
        /// <inheritdoc/>
        /// <exception cref="ArgumentNullException">Raised if <paramref name="feedEntry"/> is null.</exception>
        /// <exception cref="ArgumentException">Raised if the content property of <param name="feedEntry"/> is null or empty.</exception>
        /// <exception cref="Azure.RequestFailedException">Raised if the XML contents cannot be saved to azure storage.</exception>
        public async Task <IList <ContractProcessResult> > ProcessEventsAsync(FeedEntry feedEntry)
        {
            if (feedEntry is null)
            {
                throw new ArgumentNullException(nameof(feedEntry));
            }

            if (string.IsNullOrWhiteSpace(feedEntry.Content))
            {
                throw new ArgumentException(nameof(feedEntry));
            }

            _loggerAdapter.LogInformation($"[{nameof(ProcessEventsAsync)}] - [Bookmark:{feedEntry.Id}] - Parsing xml string to object.");

            // XML is compatiable with the schema, so, it should deserialise.
            var contractEvents = await _deserilizationService.DeserializeAsync(feedEntry.Content);

            var resultsGroup = contractEvents
                               .GroupBy(c => c.Result)
                               .Select(g => $"{g.Key}:{g.Count()}");

            _loggerAdapter.LogInformation($"[{nameof(ProcessEventsAsync)}] - [Bookmark:{feedEntry.Id}] - XML parsing completed with results [{string.Join(",", resultsGroup)}].");

            try
            {
                foreach (var item in contractEvents)
                {
                    item.ContractEvent.BookmarkId = feedEntry.Id;

                    if (item.Result == ContractProcessResultType.Successful)
                    {
                        _loggerAdapter.LogInformation($"[{nameof(ProcessEventsAsync)}] - [Bookmark:{feedEntry.Id}] - Saving XML to azure strorage.");

                        // Save xml to blob
                        // Filename format : [Entry.Updated]_[ContractNumber]_v[ContractVersion]_[Entry.BookmarkId].xml
                        string filename = $"{feedEntry.Updated:yyyyMMddHHmmss}_{item.ContractEvent.ContractNumber}_v{item.ContractEvent.ContractVersion}_{item.ContractEvent.BookmarkId}.xml";

                        // Saved XML needs to be in lowercase to be compatible with the exisitng code on the monolith
                        var lowerCaseXmlString = ConvertToLowerCaseXml(item);

                        await _blobStorageService.UploadAsync(filename, Encoding.UTF8.GetBytes(lowerCaseXmlString));

                        item.ContractEvent.ContractEventXml = filename;

                        _loggerAdapter.LogInformation($"[{nameof(ProcessEventsAsync)}] - [Bookmark:{feedEntry.Id}] - Saving XML completed.");
                    }
                    else
                    {
                        _loggerAdapter.LogWarning($"[{nameof(ProcessEventsAsync)}] - [Bookmark:{feedEntry.Id}] - Ignoring filesave - Result is unsuccessful [{item.Result}].");
                    }
                }
            }
            catch (Exception ex)
            {
                _loggerAdapter.LogError(ex, $"Failed to save XML file for Bookmark [{feedEntry.Id}].");
                throw;
            }

            return(contractEvents);
        }
示例#11
0
        public void Create(FeedEntry entry)
        {
            if (IsValid(entry))
            {
                IFeedEntryEntityWrapper cWrapper = FeedEntryWrapperFactory.Create(_context.ResourceKind, _context);
                SdataTransactionResult trResult = cWrapper.Add(entry);
                if (trResult.HttpStatus == System.Net.HttpStatusCode.Created ||
                    trResult.HttpStatus == System.Net.HttpStatusCode.OK)
                {

                    if(string.IsNullOrEmpty(entry.Id))
                        entry.Id = trResult.Location;

                    _request.Response.FeedEntry = entry;
                    _request.Response.Protocol.SendKnownResponseHeader(System.Net.HttpResponseHeader.Location, entry.Id);
                }
                else
                {
                    _request.Response.StatusCode = trResult.HttpStatus;
                    _request.Response.Diagnoses = new Diagnoses();
                    _request.Response.Diagnoses.Add(GetDiagnosis(trResult));
                    //throw new InvalidDataException(trResult.HttpStatus + ": " + trResult.HttpMessage);
                }
            }
            else
            {
                throw new RequestException("Please use valid single resource url");
            }
        }
示例#12
0
        public void MarkReadFeedEntry(FeedEntry item)
        {
            string read = DatabaseHelper.BOOL_FALSE;

            if (item.MarkedRead)
            {
                read = DatabaseHelper.BOOL_TRUE;
            }

            ContentValues values = new ContentValues();

            values.Put(DatabaseHelper.FEED_TABLE_COL_READ, read);

            //Neuen Eintrag erstellen
            if (item.ID < 0)
            {
                SaveFeedEntry(item);
            }

            //Bestehenden Eintrag aktualisieren
            else
            {
                string id_filter = DatabaseHelper.FEED_TABLE_COL_ID + "='" + item.ID + "'";
                database.Update(DatabaseHelper.FEED_TABLE, values, id_filter, null);
            }
        }
        public virtual FeedEntry GetSyncTargetFeedEntry(SdataTransactionResult transactionResult)
        {
            FeedEntry result;

            if (!String.IsNullOrEmpty(transactionResult.LocalId))
            {
                result = GetFeedEntry(transactionResult.LocalId);
            }
            else
            //result = PayloadFactory.CreateResourcePayload(this._resourceKind);
#warning The Feed Entry should have a type...
            {
                result = new FeedEntry();
            }

            if (!String.IsNullOrEmpty(transactionResult.Uuid))
            {
                result.UUID = new Guid(transactionResult.Uuid);
            }

            if (transactionResult.HttpMethod == HttpMethod.DELETE)
            {
                result.IsDeleted = true;
            }

            return(result);
        }
示例#14
0
        public void Update(FeedEntry entry, string id)
        {
            string resource = TrimApostophes(id);

            if (!string.IsNullOrEmpty(resource) && string.IsNullOrEmpty(entry.Key))
            {
                entry.Key = resource;
            }

            if (IsValid(entry))
            {
                SdataTransactionResult trResult = _wrapper.Update(entry);
                if (trResult.HttpStatus == System.Net.HttpStatusCode.OK)
                {
                    Read(resource);
                }
                else
                {
                    _request.Response.StatusCode = trResult.HttpStatus;
                    _request.Response.Diagnoses  = new Diagnoses();
                    _request.Response.Diagnoses.Add(GetDiagnosis(trResult));
                }
            }
            else
            {
                throw new RequestException("Please use valid single resource url");
            }
        }
示例#15
0
        private void saveFeedItems(FeedSource channel)
        {
            RssItemList posts = channel.RssChannel.RssItems;

            for (int i = posts.Count - 1; i >= 0; i--)
            {
                RssItem   post  = posts[i];
                FeedEntry entry = new FeedEntry();

                entry.FeedSource = channel;

                entry.Author   = post.Author;
                entry.Category = post.Category;

                entry.Description = post.Description;
                entry.Link        = post.Link;
                entry.PubDate     = post.PubDate;
                if (entry.PubDate == null || entry.PubDate < new DateTime(1900, 1, 1))
                {
                    entry.PubDate = DateTime.Now;
                }
                entry.Title   = post.Title;
                entry.Created = DateTime.Now;

                FeedEntry savedEntry = entryService.GetByLink(entry.Link);
                if (savedEntry == null)
                {
                    db.insert(entry);
                }
            }
        }
            private FeedEntry BuildFeedEntry(CorrelatedResSyncInfo correlation, IFeedEntryEntityWrapper wrapper)
            {
                // create a new empty Feed Entry
                //ISyncSourceResourceFeedEntry feedEntry = FeedComponentFactory.Create<ISyncSourceResourceFeedEntry>();
                // get resource payload container from data store
                FeedEntry feedEntry = wrapper.GetSyncSourceFeedEntry(correlation);


                // create and set SyncState
                feedEntry.SyncState          = new SyncState();
                feedEntry.SyncState.EndPoint = correlation.ResSyncInfo.EndPoint;
                feedEntry.SyncState.Tick     = (correlation.ResSyncInfo.Tick > 0) ? correlation.ResSyncInfo.Tick : 1;
                feedEntry.SyncState.Stamp    = correlation.ResSyncInfo.ModifiedStamp;

                // set the id tag
                feedEntry.Id = feedEntry.Uri;
                // set the title tag
                feedEntry.Title = String.Format("{0}: {1}", _parentPerformer._requestContext.ResourceKind.ToString(), feedEntry.Key);
                // set the updated tag
                feedEntry.Updated = correlation.ResSyncInfo.ModifiedStamp.ToLocalTime();

                // set resource dependent  links (self, edit, schema, template, post, service)
                feedEntry.Links.AddRange(LinkFactory.CreateEntryLinks(_parentPerformer._requestContext, feedEntry));


                return(feedEntry);
            }
示例#17
0
        public void Create(FeedEntry entry)
        {
            if (IsValid(entry))
            {
                IFeedEntryEntityWrapper cWrapper = FeedEntryWrapperFactory.Create(_context.ResourceKind, _context);
                SdataTransactionResult  trResult = cWrapper.Add(entry);
                if (trResult.HttpStatus == System.Net.HttpStatusCode.Created ||
                    trResult.HttpStatus == System.Net.HttpStatusCode.OK)
                {
                    if (string.IsNullOrEmpty(entry.Id))
                    {
                        entry.Id = trResult.Location;
                    }

                    _request.Response.FeedEntry = entry;
                    _request.Response.Protocol.SendKnownResponseHeader(System.Net.HttpResponseHeader.Location, entry.Id);
                }
                else
                {
                    _request.Response.StatusCode = trResult.HttpStatus;
                    _request.Response.Diagnoses  = new Diagnoses();
                    _request.Response.Diagnoses.Add(GetDiagnosis(trResult));
                    //throw new InvalidDataException(trResult.HttpStatus + ": " + trResult.HttpMessage);
                }
            }
            else
            {
                throw new RequestException("Please use valid single resource url");
            }
        }
示例#18
0
        private static void GetFeed(string feed)
        {
            var xml = new XmlDocument();

            using (var httpClient = new HttpClient())
            {
                var result = httpClient.GetStreamAsync(feed);

                xml.Load(result.Result);

                var channel   = xml.GetElementsByTagName("channel").Item(0);
                var feedTitle = channel.SelectSingleNode("title").InnerText;
                var url       = channel.SelectSingleNode("url").InnerText;

                var feedId = StorePodcastFeed(feedTitle, url);

                var items = xml.GetElementsByTagName("item");

                foreach (XmlNode item in items)
                {
                    var entry = new FeedEntry()
                    {
                        FeedId        = feedId,
                        Title         = item.SelectSingleNode("title").InnerText,
                        DatePublished = DateTime.ParseExact(item.SelectSingleNode("pubDate").InnerText, "ddd, dd MMM yyyy HH:mm:ss EDT", null),
                        Description   = item.SelectSingleNode("description").InnerText,
                        SourceUrl     = item.SelectSingleNode("source").Attributes["url"].InnerText
                    };

                    StorePodcastEntry(entry);
                }
            }
        }
示例#19
0
        private FeedEntry DeserializeManifestV2(VsixPackagePartNode part, string fileName, string category)
        {
            var entry = new FeedEntry(fileName, category);

            using (var stream = part.Part.GetStream(FileMode.Open))
            {
                using (var sr = new StreamReader(stream))
                {
                    var manifest = PackageManifest.Deserialize(sr.ReadToEnd());

                    entry.Id     = manifest.Metadata.Identity.Id;
                    entry.Title  = manifest.Metadata.DisplayName;
                    entry.Author = new FeedEntryAuthor {
                        Name = manifest.Metadata.Identity.Publisher
                    };
                    entry.Content = new FeedEntryContent {
                        Src = BuildUri(category, fileName), Type = "octet/stream"
                    };
                    entry.Vsix = new FeedEntryVsix
                    {
                        Id      = manifest.Metadata.Identity.Id,
                        Version = manifest.Metadata.Identity.Version
                    };
                    entry.Summary  = manifest.Metadata.Description;
                    entry.MoreInfo = manifest.Metadata.MoreInfo;
                }
            }
            return(entry);
        }
示例#20
0
        private FeedEntry DeserializeManifest(VsixPackagePartNode part, string fileName, string category)
        {
            var entry = new FeedEntry(fileName, category);

            using (var stream = part.Part.GetStream(FileMode.Open))
            {
                var vsixSerializer = new VsixSerializer();
                var vsix           = vsixSerializer.Deserialize(stream) as Vsix;
                if (vsix == null)
                {
                    throw new Exception("Could not deserialize VSIX manifest from " + fileName);
                }
                entry.Title  = vsix.Identifier.Name;
                entry.Id     = vsix.Identifier.Id;
                entry.Author = new FeedEntryAuthor {
                    Name = vsix.Identifier.Author
                };
                entry.Content = new FeedEntryContent {
                    Src = BuildUri(category, fileName), Type = "octet/stream"
                };
                entry.Vsix = new FeedEntryVsix {
                    Id = vsix.Identifier.Id, Version = vsix.Identifier.Version
                };
                entry.MoreInfo = vsix.References.Any() ? vsix.References.First().MoreInfoUrl : string.Empty;
                entry.Summary  = vsix.Identifier.Description;
            }
            return(entry);
        }
示例#21
0
        private FeedEntry GetStoredFeedEntry(ICursor c, Dictionary <string, Dictionary <int, SortedList <int, EntryAttachment> > > dictAttachments)
        {
            int ID_sql_id = c.GetColumnIndex(DatabaseHelper.FEED_TABLE_COL_ID);
            int ID_key    = c.GetColumnIndex(DatabaseHelper.FEED_TABLE_COL_KEY);
            int ID_title  = c.GetColumnIndex(DatabaseHelper.FEED_TABLE_COL_TITLE);
            int ID_date   = c.GetColumnIndex(DatabaseHelper.FEED_TABLE_COL_DATE);
            int ID_author = c.GetColumnIndex(DatabaseHelper.FEED_TABLE_COL_AUTHOR);
            int ID_body   = c.GetColumnIndex(DatabaseHelper.FEED_TABLE_COL_BODY);
            int ID_read   = c.GetColumnIndex(DatabaseHelper.FEED_TABLE_COL_READ);

            int    sql_id = c.GetInt(ID_sql_id);
            string key    = c.GetString(ID_key);
            string title  = c.GetString(ID_title);

            DateTime date = TBL.DecodeStringToDate(c.GetString(ID_date), DateTime.Now.AddMonths(-TBL.PREF_FEED_AUTOREMOVE));

            string author = c.GetString(ID_author);
            string body   = c.GetString(ID_body);

            string read = c.GetString(ID_read);

            var listAttachments = new SortedList <int, EntryAttachment>();

            if (dictAttachments.ContainsKey(DatabaseHelper.OWNER_FEED) && dictAttachments[DatabaseHelper.OWNER_FEED].ContainsKey(sql_id))
            {
                listAttachments = dictAttachments[DatabaseHelper.OWNER_FEED][sql_id];
            }

            FeedEntry result = new FeedEntry(key, title, date, author, body, listAttachments.Values.ToList())
            {
                MarkedRead = (read == DatabaseHelper.BOOL_TRUE), ID = sql_id
            };

            return(result);
        }
        public async Task <bool> TootFeedEntry(FeedEntry feedEntry, string template = null, StatusVisibilityEnum?visibility = null)
        {
            using (log.BeginScope($"{ nameof(MastodonInstanceService) }->{ nameof(Toot) } " + " with feedEntry: {feedEntry}, template: {template}, visibility: {visibility}",
                                  feedEntry,
                                  template,
                                  visibility
                                  ))
            {
                var tootTemplate   = template ?? cfg.Application.Toot.Template;
                var tootVisibility = visibility ?? cfg.Application.Toot.Visibiliy;

                log.LogDebug("Used template: {tootTemplate} and {tootVisibility}", tootTemplate, tootVisibility);

                var sb = new StringBuilder(tootTemplate);

                sb.Replace("{feedname}", feedEntry.FeedTitle);
                sb.Replace("{id}", feedEntry.Id);
                sb.Replace("{title}", feedEntry.Title);
                sb.Replace("{summary}", feedEntry.Summary);
                sb.Replace("{description}", feedEntry.Description);
                sb.Replace("{link}", feedEntry.Link);
                sb.Replace("{published}", feedEntry.Published.ToString(cfg.Application.Toot.DateFormatString));
                sb.Replace("{lastUpdated}", feedEntry.LastUpdated.ToString(cfg.Application.Toot.DateFormatString));

                foreach (var tag in feedEntry.Tags)
                {
                    sb.Append($" #{Regex.Replace(tag, "[^\\w]", "").ToLower()}");
                }

                log.LogDebug("Final message: {status}", sb);
                return(await Toot(sb.ToString(), tootVisibility));
            }
        }
示例#23
0
 public FeedEntryViewModel(FeedEntry feedEntry)
 {
     Title       = feedEntry.Title;
     FeedUri     = feedEntry.FeedUri;
     Summary     = feedEntry.Summary;
     PublishedOn = feedEntry.PublishedOn;
     UpdatedOn   = feedEntry.UpdatedOn;
 }
示例#24
0
        public void Read(string id)
        {
            Feed <FeedEntry> result = new Feed <FeedEntry>();

            //result.Updated = GetRandomDate();
            result.Url         = _request.Uri.ToString();
            result.Author.Name = "Northwind Adapter";


            string resource = TrimApostophes(id);

            if (resource != null)
            {
                _request.Response.FeedEntry = _wrapper.GetFeedEntry(resource);
                if (_request.Response.FeedEntry != null && !_request.Response.FeedEntry.IsDeleted && isActive(_request.Response.FeedEntry))
                {
                    _request.Response.FeedEntry.Title = _request.Response.FeedEntry.ToString();
                }

                else
                {
                    throw new DiagnosesException(Severity.Error, resource + " not found", DiagnosisCode.DatasetNotFound);
                }
            }
            else
            {
                result.Category.Scheme = "http://schemas.sage.com/sdata/categories";
                result.Category.Term   = "collection";
                result.Category.Label  = "Resource Collection";

                string[] ids        = _wrapper.GetFeed();
                long     start      = Math.Max(0, _request.Uri.StartIndex - 1); //Startindex is 1-based
                long     max        = _request.Uri.Count == null ? ids.Length : Math.Min((long)_request.Uri.Count + start, (long)ids.Length);
                long     entryCount = _request.Uri.Count == null ? DEFAULT_COUNT : (long)_request.Uri.Count;
                _request.Uri.Count = entryCount;
                for (long i = start; result.Entries.Count < entryCount && i < ids.Length; i++)
                {
                    string    entryId = ids[i];
                    FeedEntry entry   = _wrapper.GetFeedEntry(entryId);
                    if (entry != null)
                    {
                        entry.Title = entry.ToString();
                        entry.Links.AddRange(LinkFactory.CreateEntryLinks(_context, entry));
                        entry.Updated = DateTime.Now;
                        result.Entries.Add(entry);
                    }
                }

                result.Title = result.Entries.Count + " " + _context.ResourceKind.ToString();
                HandlePaging(_request, result, ids);
                //FeedLink link = new FeedLink(_request.Uri.AppendPath("$schema").ToString(), LinkType.Schema, MediaType.Xml, "Schema");
                FeedLink[] links = LinkFactory.CreateFeedLinks(_context, _request.Uri.ToString());
                result.Links.AddRange(links);
                result.Updated         = DateTime.Now;
                _request.Response.Feed = result;
            }
        }
示例#25
0
            //####################################################################################

            public ListFeedAttachmentAdapter(Context context, LinearLayout parent, FeedEntry entry)
            {
                _context = context;
                _entry   = entry;

                _thisPreview      = null;
                _thisPreviewRatio = -1;

                Inflate(parent);
            }
 private static string GetRelationshipUri(RequestContext request, FeedEntry entry, string suffix)
 {
     if (request.SdataUri.HasCollectionPredicate)
     {
         return(new SDataUri(request.SdataUri).AppendPath(new UriPathSegment(suffix)).ToString());
     }
     else
     {
         return(entry.Id + suffix);
     }
 }
示例#27
0
        private void bindItem( FeedEntry item )
        {
            set( "item.Title", item.Title );
            set( "item.Hits", item.Hits );
            set( "item.Link", item.Link );
            set( "item.PubDate", item.PubDate );
            set( "item.Description", item.Description );

            set( "item.FeedAuthor", item.FeedSource.Title );
            set( "item.FeedLink", item.FeedSource.Link );
        }
示例#28
0
        private void bindItem(FeedEntry item)
        {
            set("item.Title", item.Title);
            set("item.Hits", item.Hits);
            set("item.Link", item.Link);
            set("item.PubDate", item.PubDate);
            set("item.Description", item.Description);

            set("item.FeedAuthor", item.FeedSource.Title);
            set("item.FeedLink", item.FeedSource.Link);
        }
            private FeedEntry BuildFeedEntry(SdataTransactionResult transactionResult, IFeedEntryEntityWrapper wrapper)
            {
                // Create result feed entry
                FeedEntry feedEntry;

                if (null != transactionResult.Diagnosis)
                {
                    /* set diagnosis */
                    feedEntry           = new FeedEntry();
                    feedEntry.Diagnoses = new Diagnoses();
                    feedEntry.Diagnoses.Add(transactionResult.Diagnosis);
                }
                else
                {
                    /* get and the resource payload */

                    // Get resource data
                    feedEntry = wrapper.GetSyncTargetFeedEntry(transactionResult);

                    // set id tag
                    feedEntry.Id = feedEntry.Uri;

                    // set title tag
                    feedEntry.Title = String.Format("{0}: {1}", _parentPerformer._requestContext.ResourceKind.ToString(), feedEntry.Key);

                    // set resource dependent  links (self, edit, schema, template, post, service)
                    feedEntry.Links.AddRange(LinkFactory.CreateEntryLinks(_parentPerformer._requestContext, feedEntry));
                }


                // set updated
                feedEntry.Updated = DateTime.Now.ToLocalTime();


                feedEntry.HttpStatusCode = transactionResult.HttpStatus;
                feedEntry.HttpMessage    = transactionResult.HttpMessage;;
                if (transactionResult.HttpMethod == HttpMethod.PUT)
                {
                    feedEntry.HttpMethod = "PUT";
                }
                else if (transactionResult.HttpMethod == HttpMethod.POST)
                {
                    feedEntry.HttpMethod = "POST";
                }
                else
                {
                    feedEntry.HttpMethod = "DELETE";
                }

                feedEntry.HttpLocation = transactionResult.Location;


                return(feedEntry);
            }
示例#30
0
        public virtual void Show(long id)
        {
            FeedEntry item = entryService.GetById(id);

            if (item == null)
            {
                echoRedirect("feed item is not exists");
            }

            entryService.AddHits(item);
            bindItem(item);
        }
示例#31
0
        private bool isActive(FeedEntry feedEntry)
        {
            PropertyInfo propInfo = feedEntry.GetType().GetProperty("active");

            if (propInfo == null)
            {
                return(true);
            }
            bool prop = (bool)propInfo.GetValue(feedEntry, null);

            return(prop);
        }
示例#32
0
        public async Task <FeedEntry> GetAsync(string id)
        {
            //Create Query
            var queryString = new ArticleClientModel
            {
                from    = 0,
                size    = 1,
                _source = new[] { "uuid", "title", "article_type", "body", "excerpt", "timestamp_publish", "url", "image_url", "lang" },
                filter  = new Filter
                {
                    term = new Term
                    {
                        _id = id
                    }
                }
            };
            string content = JsonConvert.SerializeObject(queryString, Formatting.Indented);

            try
            {
                var response = await WebRequest(content);

                //Convert to JObject to bypass Response/HitData classes, then convert to List
                var json = await response.Content.ReadAsStringAsync();

                JObject           httpResponse     = JObject.Parse(json);
                IList <JToken>    httpResponseData = httpResponse["hits"]["hits"].Children().ToList();
                var               hits             = JsonConvert.SerializeObject(httpResponseData);
                JArray            hitsArray        = JArray.Parse(hits);
                IList <FeedEntry> entries          = hitsArray.Select(e => new FeedEntry
                {
                    Id          = (string)e["_id"],
                    Title       = (string)e["_source"]["title"],
                    ArticleType = (string)e["_source"]["article_type"],
                    Date        = (DateTime)e["_source"]["timestamp_publish"],
                    Body        = (string)e["_source"]["body"],
                    Excerpt     = (string)e["_source"]["excerpt"],
                    Url         = (string)e["_source"]["url"],
                    ImageUrl    = (string)e["_source"]["image_url"],
                    Language    = (string)e["_source"]["lang"]
                }).ToList();

                FeedEntry entry = entries.FirstOrDefault();

                return(entry);
            }
            catch (HttpRequestException e)
            {
                var error = e.Message;
                throw;
            }
        }
示例#33
0
        public virtual SdataTransactionResult Add(FeedEntry payload)
        {
            Document document = GetTransformedDocument(payload);
            List<TransactionResult> transactionResults = new List<TransactionResult>();

            _entity.Add(document, _context.Config, ref transactionResults);

            SdataTransactionResult sdTrResult = GetSdataTransactionResult(transactionResults,
                _context.OriginEndPoint, _resourceKind);
            if (sdTrResult != null)
                sdTrResult.HttpMethod = HttpMethod.POST;
            return sdTrResult;
        }
示例#34
0
        private string SerializeFeedEntryToXml(FeedEntry obj, FeedSerializer serializer)
        {
            if (null == obj)
                return null;

            try
            {
                String xml = null;
                MemoryStream memoryStream = new MemoryStream();

                XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);

                serializer.SaveToStream(obj, memoryStream, null);

                xml = UTF8ByteArrayToString(memoryStream.ToArray());
                return xml;

            }
            catch
            {
                //Debug.WriteLine(e);
                return null;
            }
        }
示例#35
0
 /// <summary>
 /// Helper Method, because the Framework handles emtpy entry elements (<entry/>) as...well...empty entries (and not null)
 /// </summary>
 /// <param name="newEntry"></param>
 /// <returns></returns>
 private bool IsValid(FeedEntry newEntry)
 {
     return newEntry.ContainsPayload;
 }
        public override FeedEntry GetFeedEntry(string resource)
        {
            Identity id = new Identity(_entity.EntityName, resource);

            AccountDocument accountDocument = (AccountDocument)_entity.GetDocument(id, _emptyToken, _context.Config);
            if (accountDocument.LogState == LogState.Deleted)
            {
                FeedEntry e = new FeedEntry();
                e.IsDeleted = true;
                return e;
            }
            return GetTransformedPayload(accountDocument);
        }
示例#37
0
 /// <summary>
 /// Gets the etag value of a feed entry.
 /// </summary>
 /// <param name="feedEntry">The FeedEntry to compute the etag for.</param>
 /// <param name="recursive">Should the etag contain values of complex types?</param>
 /// <returns>A string representing the etag.</returns>
 public static string ComputeEtag(FeedEntry payload, bool recursive)
 {
     return (recursive) ? stat_etagSevices._deepEtagBuilder.Compute(payload) : stat_etagSevices._simpleEtagBuilder.Compute(payload);
 }
示例#38
0
        public virtual FeedEntry GetSyncTargetFeedEntry(SdataTransactionResult transactionResult)
        {
            FeedEntry result;

            if (!String.IsNullOrEmpty(transactionResult.LocalId))
                result = GetFeedEntry(transactionResult.LocalId);
            else
                //result = PayloadFactory.CreateResourcePayload(this._resourceKind);
            #warning The Feed Entry should have a type...
                result = new FeedEntry();

            if (!String.IsNullOrEmpty(transactionResult.Uuid))
                result.UUID = new Guid(transactionResult.Uuid);

            if (transactionResult.HttpMethod == HttpMethod.DELETE)
                result.IsDeleted = true;

            return result;
        }
示例#39
0
        protected FeedEntry BuildFeedEntryForCorrelation(CorrelatedResSyncInfo corrResSyncInfo, IFeedEntryEntityWrapper wrapper)
        {
            FeedEntry feedEntry;

            #region Payload

            if (null != wrapper)
            {
                // Get resource data
                feedEntry = wrapper.GetFeedEntry(corrResSyncInfo.LocalId);
            }
            else
            {
                // Create an empty payload container
                feedEntry = new FeedEntry();
                feedEntry.IsDeleted = false;

                feedEntry.Key = corrResSyncInfo.LocalId;
            }
            if (feedEntry != null)
            {
                // modify url and set uuid as we are requesting linked resources here.
                feedEntry.Uri = string.Format("{0}{1}('{2}')", _requestContext.DatasetLink, _requestContext.ResourceKind.ToString() , corrResSyncInfo.LocalId);
                feedEntry.UUID = corrResSyncInfo.ResSyncInfo.Uuid;

            #endregion

                // set id tag
                feedEntry.Id = feedEntry.Uri;

                // set title tag
                feedEntry.Title = string.Format("{0}('{1}') : {2}", _requestContext.ResourceKind.ToString(), corrResSyncInfo.LocalId, corrResSyncInfo.ResSyncInfo.Uuid);
                feedEntry.Updated = corrResSyncInfo.ResSyncInfo.ModifiedStamp.ToLocalTime();

                // set resource dependent  links (self, edit, schema, template, post, service)
                feedEntry.Links.AddRange(LinkFactory.CreateEntryLinks(_requestContext, feedEntry));

            }
            return feedEntry;
        }
示例#40
0
        public void Update(FeedEntry entry)
        {
            // only atom entry supported!!!
            if (_request.ContentType != Sage.Common.Syndication.MediaType.AtomEntry)
                throw new RequestException("Atom entry content type expected");

            // resource key must exist in url
            if (string.IsNullOrEmpty(_requestContext.ResourceKey))
                throw new RequestException("ResourceKey missing in requested url.");

            string requestEndPointUrl;
            RequestContext entryResourceAsRequestContext;

            string url;             // The url that references an existing resource
            string localId;         // will be parsed from urlAttrValue and set to the key attribute of the result resource payload
            Guid uuid;              // the new uuid

            // retrieve the feed entry
            //entry = FeedComponentFactory.Create<ILinkingResourceFeedEntry>(request.Stream);

            // Get the uuid from query
            uuid = (Guid)TypeDescriptor.GetConverter(typeof(Guid)).ConvertFrom(_requestContext.ResourceKey);

            if (null == entry)
                throw new RequestException("sdata payload element missing");

            // the consumer MUST provide an sdata:url attribute that references an existing resource.
            url = entry.Uri;
            if (string.IsNullOrEmpty(url))
                throw new RequestException("sdata url attribute missing for resource payload element.");

            // Parse the url of thew url attribute to get the local id.
            // Additionally we check for equality of the urls of the request url and
            // in the linked element up to the resourceKind.
            requestEndPointUrl = _requestContext.OriginEndPoint;
            entryResourceAsRequestContext = new RequestContext(new Sage.Common.Syndication.SDataUri(url));    // TODO: not really nice here.
            string linkedResourceUrl = entryResourceAsRequestContext.OriginEndPoint;

            if (!string.Equals(requestEndPointUrl, linkedResourceUrl, StringComparison.InvariantCultureIgnoreCase))
                throw new RequestException("Request url and linked entry resource not matching.");

            string resourceKindName = _requestContext.ResourceKind.ToString();
            localId = entryResourceAsRequestContext.ResourceKey;

            // The correlation store
            ICorrelatedResSyncInfoStore correlatedResSyncInfoStore = NorthwindAdapter.StoreLocator.GetCorrelatedResSyncStore(_requestContext.SdataContext);

            // update the correlation entry in the sync store.
            // if uuid is not in use -> throw exception
            // if resource is already linked -> remove existing link, reassign link
            // if resource is not yet linked -> reassign link
            CorrelatedResSyncInfo[] correlations;
            CorrelatedResSyncInfo correlationToModify = null;

            // retrieve the correlation we want to reassign by given uuid
            correlations = correlatedResSyncInfoStore.GetByUuid(resourceKindName, new Guid[] { uuid });
            if (correlations.Length > 0)
                correlationToModify = correlations[0];
            else
                throw new RequestException("Uuid not in use");

            //remember the old Correlation for the new localId, will be deleted after the update.
            CorrelatedResSyncInfo[] oldCorrelations = correlatedResSyncInfoStore.GetByLocalId(resourceKindName, new string[] { localId });

            // change the local ID to link to the new resource.
            // change the modification stamp and reset the tick
            correlationToModify.LocalId = localId;
            correlationToModify.ResSyncInfo.ModifiedStamp = DateTime.Now;
            correlationToModify.ResSyncInfo.Tick = 1;

            // update the correlation
            correlatedResSyncInfoStore.Update(resourceKindName, correlationToModify);

            //If updating went OK, delete the old correlation for the new localId (should be only 1, for-loop just to be sure to catch em all)
            foreach (CorrelatedResSyncInfo oldCorrelation in oldCorrelations)
            {
                correlatedResSyncInfoStore.Delete(resourceKindName, oldCorrelation.ResSyncInfo.Uuid);
            }

            // If the service consumer only needs to retrieve the URL, not the actual payload,
            // it may do so by adding an empty select parameter to its request:
            // a) select parameter not exist -> return deep resource payload
            // b) select exists and empty -> return no resource payload
            // c) select exists and not empty -> return deep resource payload as we do not yet support payload filtering
            //    with select parameter.
            string tmpValue;
            // ?select
            bool includeResourcePayloads = true;    // default value, but check for select parameter now
            if (_requestContext.SdataUri.QueryArgs.TryGetValue("select", out tmpValue))
                if (string.IsNullOrEmpty(_requestContext.SdataUri.QueryArgs["select"]))
                    includeResourcePayloads = false;

            // Create an entity wrapper if resource data should be requested. Otherwise
            // leave wrapper null.
            IFeedEntryEntityWrapper wrapper = null;
            //if (includeResourcePayloads) //TODO: Comment this in as soon as there is a possibility to send empty payload objects
                wrapper = FeedEntryWrapperFactory.Create(_requestContext.ResourceKind, _requestContext);

            /* Create the response entry */
            _request.Response.FeedEntry = (FeedEntry)this.BuildFeedEntryForCorrelation(correlationToModify, wrapper);
            _request.Response.ContentType = MediaType.AtomEntry;
        }
        public override SdataTransactionResult Update(FeedEntry payload)
        {
            //Transform account
            Document document = GetTransformedDocument(payload);
            AccountDocument accountDocument = (AccountDocument)_entity.GetDocumentTemplate();
            accountDocument.Id = document.Id;
            accountDocument.CrmId = GetTradingAccountUuid(document.Id);
            accountDocument.people.documents.Add(document);
            // Update Document

            List<TransactionResult> transactionResults = new List<TransactionResult>();
            _entity.Update(accountDocument, _context.Config, ref transactionResults);
            SdataTransactionResult sdTrResult = GetSdataTransactionResult(transactionResults,
               _context.OriginEndPoint, SupportedResourceKinds.tradingAccounts);
            if (sdTrResult != null)
            {
                sdTrResult.ResourceKind = _resourceKind;

                sdTrResult.HttpMessage = "PUT";
            }
            return sdTrResult;
        }
示例#42
0
        /// <summary>
        /// Creates and returns an array of feed entrylinks.
        /// </summary>
        /// <param name="resourcePayloadContainer"></param>
        /// <returns></returns>
        public static FeedLink[] CreateEntryLinks(RequestContext context, FeedEntry resourcePayloadContainer)
        {
            List<FeedLink> links = new List<FeedLink>();
            #warning TODO!!!

            #region self link

            links.Add(new FeedLink(resourcePayloadContainer.Uri, LinkType.Self, MediaType.AtomEntry, "Refresh"));

            #endregion

            #region edit link

            switch(resourcePayloadContainer.GetType().Name)
            {
                case "":
                case "a":

                    break;
            }

            #endregion

            #region schema link

            links.Add(new FeedLink(String.Format("{0}{1}/$schema", context.DatasetLink, context.ResourceKind.ToString()), LinkType.Schema, MediaType.Xml));

            #endregion

            #region template link

            //switch(resourcePayloadContainer.GetType().Name)
            //{
            //    case "":
            //    case "a":

            //        break;
            //}

            links.Add(new FeedLink(String.Format("{0}{1}/$template", context.DatasetLink, context.ResourceKind.ToString()), LinkType.Template, MediaType.AtomEntry));

            #endregion

            #region service link

            switch(resourcePayloadContainer.GetType().Name)
            {
                case "":
                case "a":

                    break;
            }

            #endregion

            #region related links

            switch(resourcePayloadContainer.GetType().Name)
            {
                case "":
                case "a":

                    break;
            }

            #endregion

            return links.ToArray();
        }
示例#43
0
 public FeedShare( FeedEntry entry )
 {
     post = entry;
 }
示例#44
0
        public void Update(FeedEntry entry, string id)
        {
            string resource = TrimApostophes(id);
            if (!string.IsNullOrEmpty(resource) && string.IsNullOrEmpty(entry.Key))
                entry.Key = resource;

            if (IsValid(entry))
            {
                SdataTransactionResult trResult = _wrapper.Update(entry);
                if (trResult.HttpStatus == System.Net.HttpStatusCode.OK)
                {
                    Read(resource);
                }
                else
                {
                    _request.Response.StatusCode = trResult.HttpStatus;
                    _request.Response.Diagnoses = new Diagnoses();
                    _request.Response.Diagnoses.Add(GetDiagnosis(trResult));
                }
            }
            else
            {
                throw new RequestException("Please use valid single resource url");
            }
        }
示例#45
0
        public virtual FeedEntry Merge(FeedEntry sourceEntry)
        {
            FeedEntry targetEntry = GetFeedEntry(sourceEntry.Key);

            string[] changedProperties = sourceEntry.GetChangedProperties();
            foreach (string propName in changedProperties)
            {
                PropertyInfo propInfo = targetEntry.GetType().GetProperty(propName);
                if(propInfo != null && propInfo.CanWrite)
                {
                    object value = propInfo.GetValue(sourceEntry, null);
                    propInfo.SetValue(targetEntry, value, null);
                }
            }
            return targetEntry;
        }
示例#46
0
 public abstract Document GetTransformedDocument(FeedEntry payload);
示例#47
0
        public void Create(FeedEntry entry)
        {
            // only atom entry supported!!!

            if (_request.ContentType != Sage.Common.Syndication.MediaType.AtomEntry)
                throw new RequestException("Atom entry content type expected");

            string requestEndPointUrl;
            RequestContext entryResourceAsRequestContext;

            string url;             // The url that references an existing resource
            string localId;         // will be parsed from urlAttrValue and set to the key attribute of the result resource payload
            Guid uuid;              // the new uuid

            if (null == entry)
                throw new RequestException("sdata payload element missing");

            // the consumer MUST provide an sdata:url attribute that references an existing resource.
            url = entry.Uri;
            if (string.IsNullOrEmpty(url))
                throw new RequestException("sdata url attribute missing for resource payload element.");

            // Parse the url of thew url attribute to get the local id.
            // Additionally we check for equality of the urls of the request url and
            // in the linked element up to the resourceKind.
            requestEndPointUrl = _requestContext.OriginEndPoint;
            entryResourceAsRequestContext = new RequestContext(new Sage.Common.Syndication.SDataUri(url));    // TODO: not really nice here.
            string linkedResourceUrl = entryResourceAsRequestContext.OriginEndPoint;

            if (!string.Equals(requestEndPointUrl, linkedResourceUrl, StringComparison.InvariantCultureIgnoreCase))
                throw new RequestException("Request url and linked entry resource not matching.");

            string resourceKindName = _requestContext.ResourceKind.ToString();
            localId = entryResourceAsRequestContext.ResourceKey;

            ICorrelatedResSyncInfoStore correlatedResSyncInfoStore = NorthwindAdapter.StoreLocator.GetCorrelatedResSyncStore(_requestContext.SdataContext);

            CheckExisting(correlatedResSyncInfoStore, localId);

            // try to get the new uuid from uuid attribute
            // if this attribute is not set a new one is created
            if (null == entry.UUID || entry.UUID == Guid.Empty)
                uuid = Guid.NewGuid();
            else
                uuid = entry.UUID;

            // store a new correlation entry to the sync store
            ResSyncInfo newResSyncInfo = new ResSyncInfo(uuid, requestEndPointUrl, 0, string.Empty, DateTime.Now);
            CorrelatedResSyncInfo newInfo = new CorrelatedResSyncInfo(localId, newResSyncInfo);
            correlatedResSyncInfoStore.Add(resourceKindName, newInfo);

            // If the service consumer only needs to retrieve the URL, not the actual payload,
            // it may do so by adding an empty select parameter to its request:
            // a) select parameter not exist -> return deep resource payload
            // b) select exists and empty -> return no resource payload
            // c) select exists and not empty -> return deep resource payload as we do not yet support payload filtering
            //    with select parameter.
            string tmpValue;
            // ?select
            bool includeResourcePayloads = true;    // default value, but check for select parameter now
            if (_requestContext.SdataUri.QueryArgs.TryGetValue("select", out tmpValue))
                if (string.IsNullOrEmpty(_requestContext.SdataUri.QueryArgs["select"]))
                    includeResourcePayloads = false;

            // Create an entity wrapper if resource data should be requested. Otherwise
            // leave wrapper null.
            IFeedEntryEntityWrapper wrapper = null;
            //if (includeResourcePayloads) //TODO: Comment this in as soon as there is a possibility to send empty payload objects
                wrapper = FeedEntryWrapperFactory.Create(_requestContext.ResourceKind, _requestContext);

            /* Create the response entry */
            _request.Response.FeedEntry = (FeedEntry)this.BuildFeedEntryForCorrelation(newInfo, wrapper);
            _request.Response.ContentType = MediaType.AtomEntry;

            _request.Response.StatusCode = System.Net.HttpStatusCode.Created;
            _request.Response.Protocol.SendUnknownResponseHeader("location", FeedMetadataHelpers.BuildLinkedEntryUrl(_requestContext, uuid));
        }
示例#48
0
        private void saveFeedItems( FeedSource channel )
        {
            RssItemList posts = channel.RssChannel.RssItems;
            for (int i = posts.Count - 1; i >= 0; i--) {

                RssItem post = posts[i];
                FeedEntry entry = new FeedEntry();

                entry.FeedSource = channel;

                entry.Author = post.Author;
                entry.Category = post.Category;

                entry.Description = post.Description;
                entry.Link = post.Link;
                entry.PubDate = post.PubDate;
                if (entry.PubDate == null || entry.PubDate < new DateTime( 1900, 1, 1 ))
                    entry.PubDate = DateTime.Now;
                entry.Title = post.Title;
                entry.Created = DateTime.Now;

                FeedEntry savedEntry = entryService.GetByLink( entry.Link );
                if (savedEntry == null) {
                    db.insert( entry );
                }

            }
        }
 private void SetCommonProperties(string idString, FeedEntry entry, SupportedResourceKinds resKind)
 {
     entry.Id = GetSDataId(idString, resKind);
     entry.Key = idString;
 }
            private FeedEntry BuildFeedEntry(SdataTransactionResult transactionResult, IFeedEntryEntityWrapper wrapper)
            {
                // Create result feed entry
                FeedEntry feedEntry;

                if (null != transactionResult.Diagnosis)
                {
                    /* set diagnosis */
                    feedEntry = new FeedEntry();
                    feedEntry.Diagnoses = new Diagnoses();
                    feedEntry.Diagnoses.Add(transactionResult.Diagnosis);
                }
                else
                {
                    /* get and the resource payload */

                    // Get resource data
                    feedEntry = wrapper.GetSyncTargetFeedEntry(transactionResult);

                    // set id tag
                    feedEntry.Id = feedEntry.Uri;

                    // set title tag
                    feedEntry.Title = String.Format("{0}: {1}", _parentPerformer._requestContext.ResourceKind.ToString(), feedEntry.Key);

                    // set resource dependent  links (self, edit, schema, template, post, service)
                    feedEntry.Links.AddRange(LinkFactory.CreateEntryLinks(_parentPerformer._requestContext, feedEntry));
                }

                // set updated
                feedEntry.Updated = DateTime.Now.ToLocalTime();

                feedEntry.HttpStatusCode = transactionResult.HttpStatus;
                feedEntry.HttpMessage = transactionResult.HttpMessage; ;
                if (transactionResult.HttpMethod == HttpMethod.PUT)
                    feedEntry.HttpMethod = "PUT";
                else if (transactionResult.HttpMethod == HttpMethod.POST)
                    feedEntry.HttpMethod = "POST";
                else
                    feedEntry.HttpMethod = "DELETE";

                feedEntry.HttpLocation = transactionResult.Location;

                return feedEntry;
            }
示例#51
0
 public void AddHits( FeedEntry item )
 {
     HitsJob.Add( item );
 }
 public override Document GetTransformedDocument(FeedEntry payload)
 {
     return _transformer.GetTransformedDocument(payload as ContactFeedEntry);
 }
示例#53
0
        private bool isActive(FeedEntry feedEntry)
        {
            PropertyInfo propInfo = feedEntry.GetType().GetProperty("active");
            if (propInfo == null)
                return true;
            bool prop = (bool)propInfo.GetValue(feedEntry, null);

            return prop;
        }
        public override SdataTransactionResult Add(FeedEntry entry)
        {
            string accountUuid = string.Empty;
            SdataTransactionResult sdTrResult;
            ContactFeedEntry contactEntry = entry as ContactFeedEntry;

            if (contactEntry.primacyIndicator)
            {
                // is primary
            }
            else
            {
                sdTrResult = new SdataTransactionResult();
                sdTrResult.HttpMessage = "Only primary contacts supported";
                sdTrResult.HttpMethod = HttpMethod.POST;
                sdTrResult.HttpStatus = System.Net.HttpStatusCode.Forbidden;
                sdTrResult.ResourceKind = SupportedResourceKinds.contacts;
                sdTrResult.Uuid = contactEntry.UUID.ToString();

                AttachDiagnosis(sdTrResult);
                return sdTrResult;

            }

            if(contactEntry.tradingAccount != null)
                accountUuid = contactEntry.tradingAccount.UUID.ToString();

            if (String.IsNullOrEmpty(accountUuid) || Guid.Empty.ToString() == accountUuid)
            {
                sdTrResult = new SdataTransactionResult();
                sdTrResult.HttpMessage = "Trading Account UUID was missing";
                sdTrResult.HttpMethod = HttpMethod.POST;
                sdTrResult.HttpStatus = System.Net.HttpStatusCode.Forbidden;
                sdTrResult.ResourceKind = _resourceKind;
                sdTrResult.Uuid = contactEntry.UUID.ToString();

                AttachDiagnosis(sdTrResult);
                return sdTrResult;
            }

            string accountId = GetTradingAccountLocalId(accountUuid);

            if (String.IsNullOrEmpty(accountId))
            {
                sdTrResult = new SdataTransactionResult();
                sdTrResult.HttpMessage = String.Format("Trading Account UUID {0} was not linked", accountUuid);
                sdTrResult.HttpMethod = HttpMethod.POST;
                sdTrResult.HttpStatus = System.Net.HttpStatusCode.Forbidden;
                sdTrResult.ResourceKind = _resourceKind;
                sdTrResult.Uuid = contactEntry.UUID.ToString();

                AttachDiagnosis(sdTrResult);
                return sdTrResult;
            }

            Account account = new Account();
            Identity accIdentity = new Identity(account.EntityName, accountId);
            AccountDocument accountDocument = account.GetDocument(
                accIdentity, _emptyToken, _context.Config) as AccountDocument;
            accountDocument.CrmId = accountUuid;

            Document document = null;
            bool doAdd = false;

            document = GetTransformedDocument(entry);
            if (accountDocument.people.documents.Count == 0)
            {
                accountDocument.people.documents.Add(document);
                doAdd = true;
            }
            else
            {
                PersonDocument personDocument = accountDocument.people.documents[0] as PersonDocument;
                if (personDocument.firstname.IsNull &&
                    personDocument.lastname.IsNull)
                {
                    accountDocument.people.documents[0] = document;
                    doAdd = true;
                }

            }
            if (!doAdd)
            {
                sdTrResult = new SdataTransactionResult();
                sdTrResult.HttpMessage = "Trading Account has already a primary contact";
                sdTrResult.HttpMethod = HttpMethod.POST;
                sdTrResult.HttpStatus = System.Net.HttpStatusCode.Forbidden;
                sdTrResult.ResourceKind = _resourceKind;
                sdTrResult.Uuid = contactEntry.UUID.ToString();

                AttachDiagnosis(sdTrResult);
                return sdTrResult;
            }

            List<TransactionResult> transactionResults = new List<TransactionResult>();
            account.Update(accountDocument, _context.Config, ref transactionResults);
            sdTrResult = GetSdataTransactionResult(transactionResults,
                _context.OriginEndPoint, SupportedResourceKinds.tradingAccounts);
            if (sdTrResult != null)
            {
                sdTrResult.ResourceKind = _resourceKind;
                sdTrResult.HttpMessage = "POST";
            }
            return sdTrResult;
        }
 public void PutLinked(IRequest request, FeedEntry entry)
 {
     LinkingCRUD performer = new LinkingCRUD(request);
     performer.Update(entry);
 }