internal AutopackageModel(PackageSource source, AtomFeed feed)
 {
     Source = source;
     DestinationDirectoryFiles = Enumerable.Empty<FileEntry>();
     Assemblies = new List<PackageAssembly>();
     foreach( var sheet in Source.PropertySheets ) {
         sheet.GetMacroValue += GetMacroValue;
     }
     AtomFeed = feed;
 }
Exemple #2
0
        public static async Task<AtomFeed> ReadFeed(string path)
        {
            using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                var reader = XmlReader.Create(stream, TestAtomFeed.XmlReaderSettings);
                var feed = new AtomFeed();
                await feed.ReadXmlAsync(reader);

                return feed;
            }
        }
 internal AtomPackageFeed(Uri location)
     : base(location.AbsoluteUri)
 {
     _remoteLocation = location;
     var tsk = _transferManager[_remoteLocation].Get();
     tsk.ContinueWithParent(antecedent => {
         if( _transferManager[_remoteLocation].LastStatus == HttpStatusCode.OK ) {
             _feed = AtomFeed.Load(_transferManager[_remoteLocation].LocalFullPath);
         }
     });
 }
        public void verify_can_handle_AtomFeed_response_for_create_entry()
        {
            var mock = new Mock<ISDataResponse>(MockBehavior.Strict);
            var feed = new AtomFeed();
            feed.AddEntry(new AtomEntry());

            mock.SetupGet(r => r.Content).Returns(feed);
            mock.SetupGet(r => r.ETag).Returns(String.Empty);

            var service = new MockService(mock);
            var result = service.CreateEntry(new SDataServiceOperationRequest(service) { OperationName = "computePrice" }, new AtomEntry());
            Expect(result, Is.InstanceOf<AtomEntry>());
        }
        /// <summary>
        /// constructor. takes the async data blob
        /// </summary>
        /// <param name="data">async data to constructor</param>
        internal AsyncOperationCompletedEventArgs(AsyncData data)
            : base(data.Exception, false, data.UserData)
        {
            feedObject = data.Feed;
            stream = data.DataStream;
  
            AsyncSendData sData = data as AsyncSendData;
            if (sData != null)
            {
                entryObject = sData.Entry;
            }

        }
Exemple #6
0
        public void SetUp()
        {
            this.feed = new AtomFeed("http://myfeed.xml/");
            this.expectedEntries = new List<FeedEntry>
                                       {
                                           new FeedEntry { Title = "Test 1" },
                                           new FeedEntry { Title = "Test 2" },
                                           new FeedEntry { Title = "Test 3" }
                                       };

            this.readerMock = new Mock<IFeedReader>();
            this.readerMock.Setup(r => r.GetEntries(It.IsAny<string>())).Returns(this.expectedEntries);
            this.feed.Reader = this.readerMock.Object;
        }
Exemple #7
0
 public static async Task DefaultCollections()
 {
     var path = Path.Combine(Directory, "AtomFeed.DefaultCollection.xml");
     using(var stream = new FileStream(path, FileMode.Open, FileAccess.Read))
     {
         var reader = XmlReader.Create(stream, TestAtomFeed.XmlReaderSettings);
         var feed = new AtomFeed();
         await feed.ReadXmlAsync(reader);
        
         Assert.Equal(new ReadOnlyCollection<AtomEntry>(new List<AtomEntry>()), feed.Entries);
         Assert.Equal(new ReadOnlyDictionary<string, Uri>(new Dictionary<string, Uri>()), feed.Links);
         Assert.Equal(new ReadOnlyCollection<Message>(new List<Message>()), feed.Messages);
     }   
 }
Exemple #8
0
 public AtomSource(AtomFeed sourceFeed)
     : base(sourceFeed.XmlBase, sourceFeed.XmlLang)
 {
     _id           = sourceFeed.ID;
       _title        = sourceFeed.Title;
       _subtitle     = sourceFeed.Subtitle;
       _updated      = sourceFeed.Updated;
       _authors      = sourceFeed.Authors;
       _contributors = sourceFeed.Contributors;
       _links        = sourceFeed.Links;
       _categories   = sourceFeed.Categories;
       _generator    = sourceFeed.Generator;
       _icon         = sourceFeed.Icon;
       _rights       = sourceFeed.Rights;
 }
Exemple #9
0
        public AtomFeed Create()
        {
            AtomFeed feed = new AtomFeed(GetFeedID(), GetFeedTitle(), DateTime.MinValue);

              foreach (AtomPersonConstruct author in GetFeedAuthors()) {
            feed.AddAuthor(author);
              }

              foreach (AtomCategory category in GetFeedCategories()) {
            feed.AddCategory(category);
              }

              foreach (AtomPersonConstruct contributor in GetFeedContributors()) {
            feed.AddContributor(contributor);
              }

              feed.Generator = GetFeedGenerator();

              feed.Icon = GetFeedIcon();

              foreach (AtomLink link in GetFeedLinks()) {
            feed.AddLink(link);
              }

              feed.Logo = GetFeedLogo();

              feed.Rights = GetFeedRights();

              feed.Subtitle = GetFeedSubtitle();

              foreach (AtomEntry entry in GetFeedEntries()) {
            feed.Entries.Add(entry);
            if (entry.Updated > feed.Updated) {
              feed.Updated = entry.Updated;
            }
              }

              if (feed.Entries.Count == 0) {
            feed.Updated = GetFeedUpdated();
              }

              return feed;
        }
        /////////////////////////////////////////////////////////////////////////////


        //////////////////////////////////////////////////////////////////////
        /// <summary>creates a number or rows and delets them again</summary>
        //////////////////////////////////////////////////////////////////////
        [Test] public void DefaultHostExtensionTest()
        {
            Tracing.TraceMsg("Entering DefaultHostExtensionTest");

            if (this.strRemoteHost != null)
            {
                FeedQuery query   = new FeedQuery();
                Service   service = new Service();

                service.NewAtomEntry        += new FeedParserEventHandler(this.OnParsedNewEntry);
                service.NewExtensionElement += new ExtensionElementEventHandler(this.OnNewExtensionElement);


                service.RequestFactory = (IGDataRequestFactory) new GDataLoggingRequestFactory(this.ServiceName, this.ApplicationName);

                query.Uri = new Uri(this.strRemoteHost);

                AtomFeed returnFeed = service.Query(query);

                ObjectModelHelper.DumpAtomObject(returnFeed, CreateDumpFileName("ExtensionFeed"));
            }
        }
Exemple #11
0
        /// <summary>
        /// Writes the Atom feed body.
        /// </summary>
        private void WriteFeed(AtomFeed feed)
        {
            if (this._writer == null)
            {
                throw new InvalidOperationException("AtomWriter has been closed, and can not be written to.");
            }


            this.WriteHeader();

            if (feed == null)
            {
                throw new RequiredElementNotFoundException("AtomFeed cannot be null.");
            }

            this._writer.WriteRaw(feed.ToString());

            // finalize the writer
            this._writer.Flush();
            this._writer.Close();
            this._writer = null;
        }
        public void updateScores(int roundNumber, int[,] scores, Boolean debug = false)
        {
            if (numMatches != scores.GetUpperBound(0) + 1)
            {
                throw new ArgumentOutOfRangeException("Number of Rows in scores object should be same as number of matches!!!");
            }
            if (6 != scores.GetUpperBound(1) + 1)
            {
                throw new ArgumentOutOfRangeException("Number of Columns in scores object should be 6!!!");
            }
            WorksheetEntry entry        = (WorksheetEntry)worksheets["Scores"];
            AtomLink       cellFeedLink = entry.Links.FindService(GDataSpreadsheetsNameTable.CellRel, null);

            CellQuery query = new CellQuery(cellFeedLink.HRef.ToString());

            query.ReturnEmpty   = ReturnEmptyCells.yes;
            query.MinimumColumn = 3;
            query.MaximumColumn = 8;
            query.MinimumRow    = (uint)(2 + (roundNumber - 1) * numMatches);
            query.MaximumRow    = (uint)(1 + (roundNumber) * numMatches);

            CellFeed feed      = service.Query(query);
            AtomFeed batchFeed = new AtomFeed(feed);

            for (uint i = 0; i <= scores.GetUpperBound(0); ++i)
            {
                for (uint j = 0; j <= scores.GetUpperBound(1); ++j)
                {
                    int       index     = (int)(i * (scores.GetUpperBound(1) + 1) + j);
                    CellEntry cellEntry = (CellEntry)feed.Entries[index];
                    cellEntry.Cell.InputValue = "" + scores[i, j];
                    cellEntry.BatchData       = new GDataBatchEntryData("" + index, GDataBatchOperationType.update);
                    batchFeed.Entries.Add(cellEntry);
                }
            }
            CellFeed batchResultFeed = (CellFeed)service.Batch(batchFeed, new Uri(feed.Batch));

            updateUpdateProgress(roundNumber, debug);
        }
Exemple #13
0
        //////////////////////////////////////////////////////////////////////
        /// <summary>uses GData batch to batchupdate the cell feed. If the returned
        /// batch result set contained an error, it will throw a GDataRequestBatchException</summary>
        /// <returns> </returns>
        //////////////////////////////////////////////////////////////////////
        public override void Publish()
        {
            if (this.Batch == null)
            {
                throw new InvalidOperationException("This feed has no batch URI");
            }

            AtomFeed batchFeed = CreateBatchFeed(GDataBatchOperationType.update);

            if (batchFeed != null)
            {
                AtomFeed resultFeed = this.Service.Batch(batchFeed, new Uri(this.Batch));
                foreach (AtomEntry resultEntry in resultFeed.Entries)
                {
                    GDataBatchEntryData data = resultEntry.BatchData;
                    if (data.Status.Code != (int)HttpStatusCode.OK)
                    {
                        throw new GDataBatchRequestException(resultFeed);
                    }
                }

                // if we get here, everything is fine. So update the edit URIs in the original feed,
                // because those might have changed.
                foreach (AtomEntry resultEntry in resultFeed.Entries)
                {
                    AtomEntry originalEntry = this.Entries.FindById(resultEntry.Id);
                    if (originalEntry == null)
                    {
                        throw new GDataBatchRequestException(resultFeed);
                    }
                    if (originalEntry != null)
                    {
                        originalEntry.EditUri = resultEntry.EditUri;
                    }
                }
            }
            this.Dirty = false;
        }
Exemple #14
0
        public void ImportStlTag(bool overwrite)
        {
            if (!FileUtils.IsFileExists(_filePath))
            {
                return;
            }
            var feed = AtomFeed.Load(FileUtils.GetFileStreamReadOnly(_filePath));

            foreach (AtomEntry entry in feed.Entries)
            {
                var tagName = ConvertHelper.GetString(AtomUtility.GetDcElementContent(entry.AdditionalElements, "TagName"));

                if (!string.IsNullOrEmpty(tagName))
                {
                    var stlTagInfo = new StlTagInfo
                    {
                        TagName             = tagName,
                        PublishmentSystemID = _publishmentSystemId,
                        TagDescription      = AtomUtility.GetDcElementContent(entry.AdditionalElements, "TagDescription"),
                        TagContent          = AtomUtility.GetDcElementContent(entry.AdditionalElements, "TagContent")
                    };


                    var stlTag = DataProvider.StlTagDao.GetStlTagInfo(_publishmentSystemId, stlTagInfo.TagName);
                    if (stlTag != null)
                    {
                        if (overwrite)
                        {
                            DataProvider.StlTagDao.Update(stlTag);
                        }
                    }
                    else
                    {
                        DataProvider.StlTagDao.Insert(stlTagInfo);
                    }
                }
            }
        }
        public static async Task RunSupreme()
        {
            var proxyHost = ConfigurationManager.AppSettings["Proxy.Host"];
            var proxyPort = ConfigurationManager.AppSettings["Proxy.Port"];
            var proxyUser = ConfigurationManager.AppSettings["Proxy.User"];
            var proxyPass = ConfigurationManager.AppSettings["Proxy.Pass"];

            var client   = new SupremeCourt(proxyHost, Convert.ToInt32(proxyPort), proxyUser, proxyPass);
            var opinions = await client.GetOpinions();

            Console.WriteLine("Got {0} opinions for Supreme.", opinions.Count);

            var items = opinions.Select(x => new AtomFeedItem()
            {
                Id          = Guid.Parse(x.Type == "order" ? Md5(x.Url) : Md5(x.Id)),
                Link        = new Uri(x.Url),
                Summary     = x.Description,
                Title       = x.Title,
                LastUpdated = x.Date,
                AuthorName  = "Supreme Court of South Carolina",
                Category    = x.Type,
            }).ToList();

            var f = new AtomFeed()
            {
                AuthorName  = "Supreme Court of South Carolina",
                Id          = Guid.Parse("062c1964-e9f2-ca37-8c51-6f4ed3e0cee1"),
                LastUpdated = DateTimeOffset.UtcNow,
                Link        = new Uri("http://www.sccourts.org/opinions/indexCOAPub.cfm"),
                //LinkSelf = new Uri("http://www.sccourts.org/opinions/indexCOAPub.cfm"),
                Title = "South Carolina Supreme Court Published Opinions",
                Items = items
            };

            var feed = AtomFeedGenerator.GenerateFeed(f);

            await UploadFile("supreme.xml", feed, "text/xml");
        }
Exemple #16
0
        //============================================================
        //	CLASS SUMMARY
        //============================================================
        /// <summary>
        /// Provides example code for the AtomPersonConstruct class.
        /// </summary>
        public static void ClassExample()
        {
            #region AtomPersonConstruct
            AtomFeed feed = new AtomFeed();

            feed.Id        = new AtomId(new Uri("urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6"));
            feed.Title     = new AtomTextConstruct("Example Feed");
            feed.UpdatedOn = new DateTime(2003, 12, 13, 18, 30, 2);

            feed.Links.Add(new AtomLink(new Uri("http://example.org/")));
            feed.Links.Add(new AtomLink(new Uri("/feed"), "self"));

            //  Identify the author of the feed
            feed.Authors.Add(new AtomPersonConstruct("John Doe"));

            //  Identify the contributors to the feed
            feed.Contributors.Add(new AtomPersonConstruct("Jane Doe"));

            AtomPersonConstruct contributor = new AtomPersonConstruct();
            contributor.EmailAddress = "*****@*****.**";
            contributor.Name         = "Some Person";
            contributor.Uri          = new Uri("http://example.org/somePerson");
            feed.Contributors.Add(contributor);

            AtomEntry entry = new AtomEntry();

            entry.Id        = new AtomId(new Uri("urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a"));
            entry.Title     = new AtomTextConstruct("Atom-Powered Robots Run Amok");
            entry.UpdatedOn = new DateTime(2003, 12, 13, 18, 30, 2);

            entry.Summary = new AtomTextConstruct("Some text.");

            //  Identify the author of the entry
            entry.Authors.Add(new AtomPersonConstruct("Jane Doe"));

            feed.AddEntry(entry);
            #endregion
        }
        public void SutSeemsToBeThreadSafe(
            AtomEventsInMemory sut,
            Generator <AtomFeedBuilder <DataContractTestEventX> > g,
            Mock <ITypeResolver> resolverStub)
        {
            resolverStub
            .Setup(r => r.Resolve("test-event-x", "http://grean.rocks/dc"))
            .Returns(typeof(DataContractTestEventX));
            var feeds = g.Take(500).Select(b => b.Build()).ToArray();

            var tasks = feeds
                        .AsParallel()
                        .Select(f => Task.Factory.StartNew(() =>
            {
                using (var w = sut.CreateFeedWriterFor(f))
                    f.WriteTo(
                        w,
                        new DataContractContentSerializer(
                            resolverStub.Object));
            }))
                        .ToArray();
            var readFeeds = feeds
                            .AsParallel()
                            .Select(f => f.Locate())
                            .Select(uri =>
            {
                using (var r = sut.CreateFeedReaderFor(uri))
                    return(AtomFeed.ReadFrom(
                               r,
                               new DataContractContentSerializer(
                                   resolverStub.Object)));
            })
                            .ToArray();

            Task.WaitAll(tasks);

            Assert.Equal(feeds.Length, readFeeds.Length);
        }
Exemple #18
0
        public static PublishmentSystemInfo GetPublishmentSytemInfo(string filePath)
        {
            var publishmentSystemInfo = new PublishmentSystemInfo();

            if (!FileUtils.IsFileExists(filePath))
            {
                return(publishmentSystemInfo);
            }

            var feed = AtomFeed.Load(FileUtils.GetFileStreamReadOnly(filePath));

            publishmentSystemInfo.PublishmentSystemName = AtomUtility.GetDcElementContent(feed.AdditionalElements, PublishmentSystemAttribute.PublishmentSystemName);
            publishmentSystemInfo.PublishmentSystemDir  = AtomUtility.GetDcElementContent(feed.AdditionalElements, PublishmentSystemAttribute.PublishmentSystemDir);
            if (publishmentSystemInfo.PublishmentSystemDir != null && publishmentSystemInfo.PublishmentSystemDir.IndexOf("\\", StringComparison.Ordinal) != -1)
            {
                publishmentSystemInfo.PublishmentSystemDir = publishmentSystemInfo.PublishmentSystemDir.Substring(publishmentSystemInfo.PublishmentSystemDir.LastIndexOf("\\", StringComparison.Ordinal) + 1);
            }
            //publishmentSystemInfo.IsCheckContentUseLevel = EBooleanUtils.GetEnumType(AtomUtility.GetDcElementContent(feed.AdditionalElements, PublishmentSystemAttribute.IsCheckContentUseLevel));
            //publishmentSystemInfo.CheckContentLevel = TranslateUtils.ToInt(AtomUtility.GetDcElementContent(feed.AdditionalElements, PublishmentSystemAttribute.CheckContentLevel));
            publishmentSystemInfo.SettingsXml = AtomUtility.GetDcElementContent(feed.AdditionalElements, PublishmentSystemAttribute.SettingsXml);
            publishmentSystemInfo.Additional.IsCreateDoubleClick = false;
            return(publishmentSystemInfo);
        }
Exemple #19
0
        public static async Task <Feed> LoadAsync(string url)
        {
            Feed feed     = null;
            var  http     = new HttpClient();
            var  response = await http.GetAsync(url);

            if (response.IsSuccessStatusCode)
            {
                var xml = new XmlDocument();
                xml.LoadXml(await response.Content.ReadAsStringAsync());

                if (xml.DocumentElement.NamespaceURI == AtomFeed.XmlNamespace)
                {
                    feed = new AtomFeed(xml);
                }
                else
                {
                    feed = new RssFeed(xml);
                }
            }

            return(feed);
        }
Exemple #20
0
        public IEnumerable <ProductEntry> GetFeedEntries(Uri uri)
        {
            try
            {
                _logger.DebugFormat("Reading reference data from {0}", uri);
                var response = Client().GetAsync(uri).Result;
                response.EnsureSuccessStatusCode();

                var serializer = new DataContractContentSerializer(DataContractContentSerializer.CreateTypeResolver(typeof(ProductEntry).Assembly));
                var feed       = AtomFeed.Parse(response.Content.ReadAsStringAsync().Result, serializer);
                var reader     = new ReferenceDataFeedReader <ProductEntry>(_lastReadFeedItemDao, feed);
                return(reader);
            }
            catch (AggregateException ae)
            {
                foreach (var exception in ae.Flatten().InnerExceptions)
                {
                    _logger.InfoFormat("Threw exception getting feed from the Server {0}", uri, exception.Message);
                }

                throw new ApplicationException(string.Format("Error retrieving the feed from the server, see log for details"));
            }
        }
        private void btnReaderRead_Click(object sender, EventArgs e)
        {
            try
            {
                _sdataResourceCollectionRequest = new SDataResourceCollectionRequest(Service)
                {
                    ResourceKind = tbCollectionResourceKind.Text,
                    StartIndex   = (int)numStartIndex.Value,
                    Count        = (int)numCount.Value
                };

                _feed   = null;
                _reader = _sdataResourceCollectionRequest.ExecuteReader();

                tbReaderCount.Text = _reader.Count.ToString();

                UpdateReaderGrid();
            }
            catch (SDataClientException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        public static async Task ParseDictionaryAsyncAtomFeed()
        {
            // Test to verify GitHub PR #57 - handling empty key name to "Empty" for <s:key name="">
            var path = Path.Combine(Directory, "AtomFeed.EmptyDictionaryKeyNameAtomFeed.xml");

            using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                var reader = XmlReader.Create(stream, TestAtomFeed.XmlReaderSettings);
                var feed   = new AtomFeed();
                await feed.ReadXmlAsync(reader);

                Assert.Equal(1, feed.Entries.Count);
                AtomEntry entry   = feed.Entries[0];
                dynamic   content = entry.Content;
                Assert.NotNull(content);
                Assert.NotNull(content["Key"]);
                Assert.NotNull(content["Key"]["Empty"]);
                Assert.Equal(1, ((IDictionary <string, object>)content["Key"]["Empty"]).Count);
                Assert.Equal("num", content["Key"]["Empty"]["Type"]);
                Assert.Equal(new ReadOnlyDictionary <string, Uri>(new Dictionary <string, Uri>()), feed.Links);
                Assert.Equal(new ReadOnlyCollection <Message>(new List <Message>()), feed.Messages);
            }
        }
Exemple #23
0
        public void enumerateImages()
        {
            //FIXME make this configurable, it should at least flip between all albuns of the user
            String feed = "http://picasaweb.google.com/data/feed/api/user/kumpera/album/RandomPhotos?kind=photo";

            FeedQuery query   = new FeedQuery();
            Service   service = new Service("picasa", "MoonLight Desklets");

            query.Uri = new Uri(feed);
            AtomFeed picasaFeed = service.Query(query);

            urls = new String [picasaFeed.Entries.Count];

            int i = 0;

            foreach (AtomEntry entry in picasaFeed.Entries)
            {
                urls[i++] = entry.Content.Src.Content;
                Console.WriteLine("content: " + entry.Content.Src.Content);
            }

            Moonlight.Gtk.Desklet.Invoke(delegate { DownloadImage(0); });
        }
        /// <summary>
        /// Provides example code for the AtomFeed class.
        /// </summary>
        public static void ClassExample()
        {
            AtomFeed feed = new AtomFeed();

            feed.Id        = new AtomId(new Uri("urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6"));
            feed.Title     = new AtomTextConstruct("Example Feed");
            feed.UpdatedOn = new DateTime(2003, 12, 13, 18, 30, 2);

            feed.Links.Add(new AtomLink(new Uri("http://example.org/")));
            feed.Links.Add(new AtomLink(new Uri("/feed"), "self"));

            feed.Authors.Add(new AtomPersonConstruct("John Doe"));

            AtomEntry entry = new AtomEntry();

            entry.Id        = new AtomId(new Uri("urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a"));
            entry.Title     = new AtomTextConstruct("Atom-Powered Robots Run Amok");
            entry.UpdatedOn = new DateTime(2003, 12, 13, 18, 30, 2);

            entry.Summary = new AtomTextConstruct("Some text.");

            feed.AddEntry(entry);
        }
Exemple #25
0
        public void ImportPhoto(int contentIdFromFile, int contentId)
        {
            var filePath = PathUtils.Combine(_directoryPath, contentIdFromFile + ".xml");

            if (!FileUtils.IsFileExists(filePath))
            {
                return;
            }

            var feed = AtomFeed.Load(FileUtils.GetFileStreamReadOnly(filePath));

            foreach (AtomEntry entry in feed.Entries)
            {
                var smallUrl    = AtomUtility.GetDcElementContent(entry.AdditionalElements, "SmallUrl");
                var middleUrl   = AtomUtility.GetDcElementContent(entry.AdditionalElements, "MiddleUrl");
                var largeUrl    = AtomUtility.GetDcElementContent(entry.AdditionalElements, "LargeUrl");
                var description = AtomUtility.Decrypt(AtomUtility.GetDcElementContent(entry.AdditionalElements, "Description"));

                var photoInfo = new PhotoInfo(0, _publishmentSystemInfo.PublishmentSystemId, contentId, smallUrl, middleUrl, largeUrl, 0, description);

                DataProvider.PhotoDao.Insert(photoInfo);
            }
        }
Exemple #26
0
        public async Task ImportAsync(AtomFeed feed, int siteId, string guid)
        {
            var contentTags = new List <ContentTag>();

            var tagNames = await _databaseManager.ContentTagRepository.GetTagNamesAsync(siteId);

            foreach (AtomEntry entry in feed.Entries)
            {
                var isContentTag = TranslateUtils.ToBool(AtomUtility.GetDcElementContent(entry.AdditionalElements, "IsContentTag"));
                if (!isContentTag)
                {
                    continue;
                }

                var tagName = AtomUtility.GetDcElementContent(entry.AdditionalElements, nameof(ContentTag.TagName));
                if (string.IsNullOrEmpty(tagName) || ListUtils.Contains(tagNames, tagName))
                {
                    continue;
                }

                var useNum = TranslateUtils.ToInt(AtomUtility.GetDcElementContent(entry.AdditionalElements, nameof(ContentTag.UseNum)));
                var level  = TranslateUtils.ToInt(AtomUtility.GetDcElementContent(entry.AdditionalElements, nameof(ContentTag.Level)));
                contentTags.Add(new ContentTag
                {
                    TagName = tagName,
                    SiteId  = siteId,
                    UseNum  = useNum,
                    Level   = level
                });
            }

            foreach (var contentTag in contentTags)
            {
                _caching.SetProcess(guid, $"导入内容标签: {contentTag.TagName}");
                await _databaseManager.ContentTagRepository.InsertAsync(contentTag);
            }
        }
        //[Test]
        public void CheckEntityListPaginated()
        {
            EntityList <Job> list = new EntityList <Job>(context);

            list.OpenSearchEngine = ose;
            list.Identifier       = "test";

            for (int i = 1; i <= 10; i++)
            {
                list.Include(new Job(context)
                {
                    Name = "" + i
                });
            }

            var      nvc     = new NameValueCollection();
            var      request = (AtomOpenSearchRequest)list.Create(new QuerySettings("application/atom+xml", ose.GetExtensionByExtensionName("atom").ReadNative), nvc);
            AtomFeed feed    = (AtomFeed)request.GetResponse().GetResponseObject();

            Assert.That(feed.Items.First().Title.Text == "1");
            Assert.That(feed.Items.Last().Title.Text == "10");

            nvc.Add("startIndex", "2");
            request = (AtomOpenSearchRequest)list.Create(new QuerySettings("application/atom+xml", ose.GetExtensionByExtensionName("atom").ReadNative), nvc);
            feed    = (AtomFeed)request.GetResponse().GetResponseObject();

            Assert.That(feed.Items.First().Title.Text == "2");
            Assert.That(feed.Items.Last().Title.Text == "10");

            nvc.Remove("startIndex");
            nvc.Add("q", "4");
            request = (AtomOpenSearchRequest)list.Create(new QuerySettings("application/atom+xml", ose.GetExtensionByExtensionName("atom").ReadNative), nvc);
            feed    = (AtomFeed)request.GetResponse().GetResponseObject();

            Assert.That(feed.Items.First().Title.Text == "4");
            Assert.That(feed.Items.Last().Title.Text == "4");
        }
 private void loginButton_Click(object sender, EventArgs e)
 {
     this.rootURL  = siteTextBox.Text;
     this.username = usernameTextBox.Text;
     this.password = passwordTextBox.Text;
     try
     {
         this.service = new SitesService(APP_NAME);
         this.service.setUserCredentials(this.username, this.password);
         this.loginToken = service.QueryClientLoginToken();
     }
     catch (Exception ex)
     {
         this.errorMessage         = ex.ToString();
         this.loginStatus          = false;
         this.authenticationStatus = false;
         this.Close();
         return;
     }
     this.loginStatus = true;
     try
     {
         FeedQuery query = new FeedQuery(this.rootURL);
         AtomFeed  feed  = this.service.Query(query);
     }
     catch (Exception ex)
     {
         this.errorMessage         = ex.ToString();
         this.authenticationStatus = false;
         this.Close();
         return;
     }
     this.authenticationStatus = true;
     this.errorMessage         = null;
     this.DialogResult         = DialogResult.OK;
     this.Close();
 }
        //============================================================
        //	CLASS SUMMARY
        //============================================================
        /// <summary>
        /// Provides example code for the AtomCategory class.
        /// </summary>
        public static void ClassExample()
        {
            #region AtomCategory
            AtomFeed feed = new AtomFeed();

            feed.Id        = new AtomId(new Uri("urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6"));
            feed.Title     = new AtomTextConstruct("Example Feed");
            feed.UpdatedOn = new DateTime(2003, 12, 13, 18, 30, 2);

            feed.Links.Add(new AtomLink(new Uri("http://example.org/")));
            feed.Links.Add(new AtomLink(new Uri("/feed"), "self"));

            feed.Authors.Add(new AtomPersonConstruct("John Doe"));

            // Categorize the feed
            feed.Categories.Add(new AtomCategory("sports"));

            AtomEntry entry = new AtomEntry();

            entry.Id        = new AtomId(new Uri("urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a"));
            entry.Title     = new AtomTextConstruct("Atom-Powered Robots Run Amok");
            entry.UpdatedOn = new DateTime(2003, 12, 13, 18, 30, 2);

            entry.Summary = new AtomTextConstruct("Some text.");

            //  Categorize the feed entry
            AtomCategory entryCategory = new AtomCategory();
            entryCategory.Label  = "Baseball";
            entryCategory.Scheme = new Uri("http://example.org/scheme/category");
            entryCategory.Term   = "baseball";

            entry.Categories.Add(entryCategory);

            feed.AddEntry(entry);
            #endregion
        }
        /// <summary>
        /// Provides example code for the Load(XmlReader) method
        /// </summary>
        public static void LoadXmlReaderExample()
        {
            AtomFeed feed = new AtomFeed();

            using (Stream stream = new FileStream("AtomFeed.xml", FileMode.Open, FileAccess.Read))
            {
                XmlReaderSettings settings = new XmlReaderSettings();
                settings.IgnoreComments   = true;
                settings.IgnoreWhitespace = true;

                using (XmlReader reader = XmlReader.Create(stream, settings))
                {
                    feed.Load(reader);

                    foreach (AtomEntry entry in feed.Entries)
                    {
                        if (entry.PublishedOn >= DateTime.Today)
                        {
                            //  Perform some processing on the feed entry
                        }
                    }
                }
            }
        }
Exemple #31
0
        public void All_Pages_Are_Available()
        {
            Assert.IsTrue(HomePage.IsAt());

            Footer.GoToAbout();
            Assert.IsTrue(AboutPage.IsAt());

            AboutPage.GoToAtomFeed();
            Assert.IsTrue(AtomFeed.IsAt());

            Navigation.GoToRoot();
            Navigation.GoToBlog();
            Assert.IsTrue(HomePage.IsAt());

            Navigation.GoToTrending();
            TrendingPage.IsAt();

            Navigation.GoToArchive();
            Assert.IsTrue(ArchivePage.IsAt());

            Navigation.GoToRoot();
            Navigation.GoToRssFeed();
            Assert.IsTrue(RssFeed.IsAt());
        }
Exemple #32
0
        /** Lists the user's blogs and returns the URI for posting new entries
         * to the blog which the user selected.
         */
        static Uri SelectUserBlog(Service service)
        {
            Console.WriteLine("\nPlease select a blog on which to post.");
            FeedQuery query = new FeedQuery();

            // Retrieving a list of blogs
            query.Uri = new Uri("http://www.blogger.com/feeds/default/blogs");
            AtomFeed feed = service.Query(query);

            // Publishing a blog post
            Uri blogPostUri = null;

            if (feed != null)
            {
                foreach (AtomEntry entry in feed.Entries)
                {
                    // Print out the title of the Blog
                    Console.WriteLine("  Blog name: " + entry.Title.Text);
                    Console.Write("  Post to this blog? (y/n): ");
                    if (Console.ReadLine().Equals("y"))
                    {
                        // find the href in the link with a rel pointing to the blog's feed
                        for (int i = 0; i < entry.Links.Count; i++)
                        {
                            if (entry.Links[i].Rel.Equals("http://schemas.google.com/g/2005#post"))
                            {
                                blogPostUri = new Uri(entry.Links[i].HRef.ToString());
                                Console.WriteLine("  Your new posts will be sent to " + blogPostUri.AbsoluteUri.ToString());
                            }
                        }
                        return(blogPostUri);
                    }
                }
            }
            return(blogPostUri);
        }
Exemple #33
0
        /////////////////////////////////////////////////////////////////////////////



        //////////////////////////////////////////////////////////////////////
        /// <summary>runs an authentication test</summary>
        //////////////////////////////////////////////////////////////////////
        [Test] public void BloggerStressTest()
        {
            Tracing.TraceMsg("Entering Blogger GoogleStressTest");

            FeedQuery      query   = new FeedQuery();
            BloggerService service = new BloggerService(this.ApplicationName);

            if (this.bloggerURI != null)
            {
                if (this.userName != null)
                {
                    service.Credentials = new GDataCredentials(this.userName, this.passWord);
                }

                service.RequestFactory = this.factory;

                query.Uri = new Uri(this.bloggerURI);
                AtomFeed blogFeed = service.Query(query);

                ObjectModelHelper.DumpAtomObject(blogFeed, CreateDumpFileName("AuthenticationTest"));

                if (blogFeed != null)
                {
                    for (int i = 0; i < 30; i++)
                    {
                        AtomEntry entry = ObjectModelHelper.CreateAtomEntry(i);
                        entry.Categories.Clear();
                        entry.Title.Text      = "Title " + i;
                        entry.Content.Content = "Some text...";
                        entry.Content.Type    = "html";

                        blogFeed.Insert(entry);
                    }
                }
            }
        }
        private void SaveFeed( AtomFeed feed )
        {
            feed.Save(_localfeedLocation);
            if (_cloudFileSystem != null) {
                _cloudFileSystem.WriteBlob(_packageStorageFolder, Path.GetFileName(_localfeedLocation).ToLower(), _localfeedLocation, false, (progress) => "{0} => {1}".format(_localfeedLocation, _packageStorageFolder).PrintProgressBar(progress));
                Console.WriteLine();

                _cloudFileSystem.WriteBlob(_packageStorageFolder, Path.GetFileName(_localfeedLocation).ToLower() + ".gz", _localfeedLocation, true, (progress) => "{0} => {1}".format(_localfeedLocation + ".gz", _packageStorageFolder).PrintProgressBar(progress));
                Console.WriteLine();
            }
        }
        private void CreatePackageModel()
        {
            PackageFeed = new AtomFeed();
            PackageModel = new AutopackageModel(PackageSource, PackageFeed);
            PackageFeed.Add(PackageModel);

            PackageModel.ProcessCertificateInformation();

            // find the xml templates that we're going to generate content with
            PackageModel.ProcessPackageTemplates();

            // Run through the file lists and gather in all the files that we're going to include in the package.
            PackageModel.ProcessFileLists();
            // at the end of the step, if there are any errors, let's print them out and exit now.
            FailOnErrors();

            PackageModel.ProcessCosmeticMetadata();
            // at the end of the step, if there are any errors, let's print them out and exit now.
            FailOnErrors();

            // Ensure digital signatures and strong names are all good to go
            // this doesn't commit the files to disk tho' ...
            PackageModel.ProcessDigitalSigning();
            // at the end of the step, if there are any errors, let's print them out and exit now.
            FailOnErrors();

            PackageModel.ProcessApplicationRole();
            // at the end of the step, if there are any errors, let's print them out and exit now.
            FailOnErrors();

            PackageModel.ProcessFauxRoles();
            // at the end of the step, if there are any errors, let's print them out and exit now.
            FailOnErrors();

            PackageModel.ProcessDeveloperLibraryRoles();
            // at the end of the step, if there are any errors, let's print them out and exit now.
            FailOnErrors();

            PackageModel.ProcessServiceRoles();
            // at the end of the step, if there are any errors, let's print them out and exit now.
            FailOnErrors();

            PackageModel.ProcessDriverRoles();
            // at the end of the step, if there are any errors, let's print them out and exit now.
            FailOnErrors();

            PackageModel.ProcessWebApplicationRoles();
            // at the end of the step, if there are any errors, let's print them out and exit now.
            FailOnErrors();

            PackageModel.ProcessSourceCodeRoles();
            // at the end of the step, if there are any errors, let's print them out and exit now.
            FailOnErrors();

            // identify all assemblies to create in the package
            PackageModel.ProcessAssemblyRules();
            // at the end of the step, if there are any errors, let's print them out and exit now.
            FailOnErrors();

            // Validate the basic information of this package
            PackageModel.ProcessBasicPackageInformation();
            // at the end of the step, if there are any errors, let's print them out and exit now.
            FailOnErrors();

            // Gather the dependency information for the package
            PackageModel.ProcessDependencyInformation();
            // at the end of the step, if there are any errors, let's print them out and exit now.
            FailOnErrors();

            // update manifests for things that need them.
            PackageModel.UpdateApplicationManifests();
            // at the end of the step, if there are any errors, let's print them out and exit now.
            FailOnErrors();

            // Build Assembly policy files
            PackageModel.CreateAssemblyPolicies();
            // at the end of the step, if there are any errors, let's print them out and exit now.
            FailOnErrors();

            // persist all the changes to any binaries that we've touched.
            PackageModel.SaveModifiedBinaries();
            // at the end of the step, if there are any errors, let's print them out and exit now.
            FailOnErrors();

               // here

            PackageModel.ProcessCompositionRules();
            // at the end of the step, if there are any errors, let's print them out and exit now.
            FailOnErrors();
        }
 public AutopackageModel(PackageSource source, AtomFeed feed)
     : this()
 {
     Source = source;
     Source.GetMacroValue += GetMacroValue;
     AtomFeed = feed;
 }
Exemple #37
0
        private void Create()
        {
            Feed = new AtomFeed();
            AtomFeed originalFeed = null;

            if (!string.IsNullOrEmpty(_input)) {
                Logger.Message("Loading existing feed.");
                if (_input.IsWebUri()) {
                    var inputFilename = "feed.atom.xml".GenerateTemporaryFilename();

                    var rf = new RemoteFile(_input, inputFilename, (uri) => {
                    },
                        (uri) => {
                            inputFilename.TryHardToDelete();
                        },
                        (uri, progress) => {
                            "Downloading {0}".format(uri).PrintProgressBar(progress);
                        });
                    rf.Get();

                    if (!File.Exists(inputFilename)) {
                        throw new ConsoleException("Failed to get input feed from '{0}' ", _input);
                    }
                    originalFeed = AtomFeed.LoadFile(inputFilename);
                } else {
                    originalFeed = AtomFeed.LoadFile(_input);
                }
            }

            if (originalFeed != null) {
                Feed.Add(originalFeed.Items.Where(each => each is AtomItem).Select(each => each as AtomItem));
            }
            ;

            Logger.Message("Selecting local packages");

            _packageManager.RecognizeFiles(_packageFiles.FindFilesSmarter()).Continue(packages => {
                var names = packages.Select(each => each.CanonicalName); //  .ToArray();

                var feed = _packageManager.GetAtomFeed(names).Result;

                foreach( var i in feed.Items) {
                    var feedItem = i as AtomItem;
                    if (feedItem != null) {
                        var pkg = _packageManager.GetPackage(feedItem.Model.CanonicalName).Result;
                        // first, make sure that the feeds contains the intended feed location.
                        if (feedItem.Model.Feeds == null) {
                            feedItem.Model.Feeds = new XList<Uri>();
                        }

                        if (!feedItem.Model.Feeds.Contains(_feedLocation)) {
                            feedItem.Model.Feeds.Insert(0, _feedLocation);
                        }

                        var location = new Uri(_baseUrl, Path.GetFileName(pkg.LocalPackagePath));

                        if (feedItem.Model.Locations == null) {
                            feedItem.Model.Locations = new XList<Uri>();
                        }

                        if (!feedItem.Model.Locations.Contains(location)) {
                            feedItem.Model.Locations.Insert(0, location);
                        }

                        // add it to our feed.
                        Feed.Add(feedItem);
                    }
                }
            }).Wait();

            Feed.Save(_output);

            // Feed.ToString()
            // PackageFeed.Add(PackageModel);
        }
Exemple #38
0
 internal void Write(AtomFeed feed)
 {
     this.WriteFeed(feed);
 }
 public void AtomFeedText(string atomText)
 {
     _feed = AtomFeed.Load(atomText);
 }
        private void Create()
        {
            Feed = new AtomFeed();
            AtomFeed originalFeed = null;

            if( !string.IsNullOrEmpty(_input) ) {
                Logger.Message("Loading existing feed.");
                if( _input.IsWebUrl()) {
                    var inputFilename = "feed.atom.xml".GenerateTemporaryFilename();

                    RemoteFile.GetRemoteFile(_input, inputFilename).Get(new RemoteFileMessages() {
                        Completed = (uri) => { },
                        Failed = (uri) => { inputFilename.TryHardToDelete(); },
                        Progress = (uri, progress) => { }
                    }).Wait();

                    if( !File.Exists(inputFilename) ) {
                        throw new ConsoleException("Failed to get input feed from '{0}' ", _input);
                    }
                    originalFeed = AtomFeed.LoadFile(inputFilename);
                }
                else {
                    originalFeed = AtomFeed.LoadFile(_input);
                }
            }

            if( originalFeed != null ) {
                Feed.Add(originalFeed.Items.Where(each => each is AtomItem).Select(each => each as AtomItem));
            }

            Logger.Message("Selecting local packages");
            var files = _packages.FindFilesSmarter();

            _pm.GetPackages(files, null, null, false, null, null, null, null, false, null, null, _messages).ContinueWith((antecedent) => {
                var packages = antecedent.Result;

                foreach (var pkg in packages) {
                    _pm.GetPackageDetails(pkg.CanonicalName, _messages).Wait();

                    if (!string.IsNullOrEmpty(pkg.PackageItemText)) {
                        var item = SyndicationItem.Load<AtomItem>(XmlReader.Create(new StringReader(pkg.PackageItemText)));

                        var feedItem = Feed.Add(item);

                        // first, make sure that the feeds contains the intended feed location.
                        if( feedItem.Model.Feeds == null ) {
                            feedItem.Model.Feeds  = new List<Uri>();
                        }

                        if( !feedItem.Model.Feeds.Contains(_feedLocation) ) {
                            feedItem.Model.Feeds.Insert(0, _feedLocation);
                        }

                        var location = new Uri(_baseUrl, Path.GetFileName(pkg.LocalPackagePath));

                        if (feedItem.Model.Locations== null) {
                            feedItem.Model.Locations = new List<Uri>();
                        }

                        if (!feedItem.Model.Locations.Contains(location)) {
                            feedItem.Model.Locations.Insert(0, location);
                        }

                    } else {
                        throw new ConsoleException("Missing ATOM data for '{0}'", pkg.Name);
                    }
                }
            }).Wait();

            Feed.Save(_output);

            // Feed.ToString()
            // PackageFeed.Add(PackageModel);
        }
Exemple #41
0
        /// <summary>Consumes the next chunk of content from the underlying XML reader.</summary>
        /// <returns>
        /// true if another piece of content is available, identified by DataKind.
        /// false if there is no more content.
        /// </returns>
        internal virtual bool Read()
        {
            // When an external caller 'insists', we'll come all the way down (which is the 'most local'
            // scope at which this is known), and unwind as a no-op.
            if (this.DataKind == AtomDataKind.Finished)
            {
                return false;
            }

            while (this.reader.Read())
            {
                if (ShouldIgnoreNode(this.reader))
                {
                    continue;
                }

                Debug.Assert(
                    this.reader.NodeType == XmlNodeType.Element || this.reader.NodeType == XmlNodeType.EndElement,
                    "this.reader.NodeType == XmlNodeType.Element || this.reader.NodeType == XmlNodeType.EndElement -- otherwise we should have ignored or thrown");

                AtomDataKind readerData = ParseStateForReader(this.reader);

                if (this.reader.NodeType == XmlNodeType.EndElement)
                {
                    // The only case in which we expect to see an end-element at the top level
                    // is for a feed. Custom elements and entries should be consumed by
                    // their own parsing methods. However we are tolerant of additional EndElements,
                    // which at this point mean we have nothing else to consume.
                    break;
                }

                switch (readerData)
                {
                    case AtomDataKind.Custom:
                        if (this.DataKind == AtomDataKind.None)
                        {
                            this.kind = AtomDataKind.Custom;
                            return true;
                        }
                        else
                        {
                            CommonUtil.SkipToEndAtDepth(this.reader, this.reader.Depth);
                            continue;
                        }

                    case AtomDataKind.Entry:
                        this.kind = AtomDataKind.Entry;
                        this.ParseCurrentEntry(out this.entry);
                        return true;

                    case AtomDataKind.Feed:
                        if (this.DataKind == AtomDataKind.None)
                        {
                            this.feed = new AtomFeed();
                            this.kind = AtomDataKind.Feed;
                            return true;
                        }

                        throw new InvalidOperationException(Strings.AtomParser_FeedUnexpected);

                    case AtomDataKind.FeedCount:
                        this.ParseCurrentFeedCount();
                        break;

                    case AtomDataKind.PagingLinks:
                        if (this.feed == null)
                        {
                            // paging link outside of feed?
                            throw new InvalidOperationException(Strings.AtomParser_PagingLinkOutsideOfFeed);
                        }

                        this.kind = AtomDataKind.PagingLinks;
                        this.ParseCurrentFeedPagingLinks();

                        // need to take care of both patterns - if the element is empty as
                        // well as when there is an end element specified.
                        CommonUtil.SkipToEndAtDepth(this.reader, this.reader.Depth);
                        return true;

                    default:
                        Debug.Assert(false, "Atom Parser is in a wrong state...Did you add a new AtomDataKind?");
                        break;
                }
            }

            this.kind = AtomDataKind.Finished;
            this.entry = null;
            return false;
        }
Exemple #42
0
 internal AtomPackageFeed(string location)
     : base(location)
 {
     _feed = AtomFeed.Load(location);
 }
        /*
        public override Task Post(HttpListenerResponse response, string relativePath, Toolkit.Pipes.UrlEncodedMessage message) {
            var fileData = message["file"].ToString();
            if( string.IsNullOrEmpty(fileData) ) {
                response.StatusCode = 500;
                response.Close();
                return "".AsResultTask();
            }

            var data = fileData.UrlDecode();
        }
        */
        public override Task Put(HttpListenerResponse response, string relativePath, byte[] data)
        {
            if( data.Length < 1 ) {
                response.StatusCode = 500;
                response.Close();
                return "".AsResultTask();
            }

            var result = Task.Factory.StartNew(
                () => {
                    var filename = "UploadedFile.bin".GenerateTemporaryFilename();
                    File.WriteAllBytes(filename, data);

                    PackageManager.Instance.ConnectAndWait("RepositoryService", null, 5000);

                    // verify that the file is actually a valid package
                    PackageManager.Instance.GetPackages(filename, messages: RepositoryServiceMain._messages).ContinueWith(
                        antecedent => {
                            if( antecedent.IsFaulted ) {
                                Console.WriteLine("Fault occurred after upload: {0}", filename);
                                filename.TryHardToDelete();
                                response.StatusCode = 400;
                                response.Close();
                                return;
                            }

                            if( antecedent.IsCanceled) {
                                Console.WriteLine("Request was cancelled");
                                filename.TryHardToDelete();
                                response.StatusCode = 400;
                                response.Close();
                                return;
                            }

                            var pkg = antecedent.Result.FirstOrDefault();
                            if( pkg == null ) {
                                Console.WriteLine("File uploaded is not recognized as a package: {0}", filename);
                                filename.TryHardToDelete();
                                response.StatusCode = 400;
                                response.Close();
                                return;
                            }

                            var targetFilename = (pkg.CanonicalName + ".msi").ToLower();
                            var location = new Uri(_packagePrefixUrl, targetFilename);
                            PackageManager.Instance.GetPackageDetails(pkg.CanonicalName, RepositoryServiceMain._messages).Wait();

                            //copy the package to the destination
                            if (_cloudFileSystem != null) {
                                // copy file to azure storage
                                _cloudFileSystem.WriteBlob(_packageStorageFolder, targetFilename, filename, false, (progress) => {
                                    ConsoleExtensions.PrintProgressBar("{0} => {1}".format(pkg.CanonicalName, _packageStorageFolder), progress);
                                });

                                if (pkg.Name.Equals("coapp.toolkit", StringComparison.CurrentCultureIgnoreCase) && pkg.PublicKeyToken.Equals("1e373a58e25250cb", StringComparison.CurrentCultureIgnoreCase)) {
                                    // update the default toolkit too
                                    _cloudFileSystem.WriteBlob(_packageStorageFolder, "coapp.toolkit.msi", filename, false, (progress) => {
                                        ConsoleExtensions.PrintProgressBar("{0} => {1}".format(_localfeedLocation, _packageStorageFolder), progress);
                                    });
                                    Console.WriteLine();
                                }

                                if (pkg.Name.Equals("coapp.devtools", StringComparison.CurrentCultureIgnoreCase) && pkg.PublicKeyToken.Equals("1e373a58e25250cb", StringComparison.CurrentCultureIgnoreCase)) {
                                    // update the default toolkit too
                                    _cloudFileSystem.WriteBlob(_packageStorageFolder, "coapp.devtools.msi", filename, false, (progress) => {
                                        ConsoleExtensions.PrintProgressBar("{0} => {1}".format(_localfeedLocation, _packageStorageFolder), progress);
                                    });
                                    Console.WriteLine();
                                }

                                // remove the local file, since we don't need it anymore.
                                filename.TryHardToDelete();

                                Console.WriteLine();
                            } else {
                                var targetLocation = Path.Combine(_packageStorageFolder, targetFilename);
                                if( File.Exists(targetLocation)) {
                                    targetLocation.TryHardToDelete();
                                }

                                File.Copy(filename, targetLocation);
                            }

                            lock(typeof(UploadedFileHandler)) {
                                // update the feed
                                var Feed = new AtomFeed();

                                if (!string.IsNullOrEmpty(_localfeedLocation) && File.Exists(_localfeedLocation)) {
                                    var originalFeed = AtomFeed.LoadFile(_localfeedLocation);
                                    Feed.Add(originalFeed.Items.Where(each => each is AtomItem).Select(each => each as AtomItem));
                                }

                                if (!string.IsNullOrEmpty(pkg.PackageItemText)) {
                                    var item = SyndicationItem.Load<AtomItem>(XmlReader.Create(new StringReader(pkg.PackageItemText)));

                                    var feedItem = Feed.Add(item);

                                    // first, make sure that the feeds contains the intended feed location.
                                    if (feedItem.Model.Feeds == null) {
                                        feedItem.Model.Feeds = new List<Uri>();
                                    }

                                    if (!feedItem.Model.Feeds.Contains(_canonicalFeedUrl)) {
                                        feedItem.Model.Feeds.Insert(0, _canonicalFeedUrl);
                                    }

                                    if (feedItem.Model.Locations == null) {
                                        feedItem.Model.Locations = new List<Uri>();
                                    }

                                    if (!feedItem.Model.Locations.Contains(location)) {
                                        feedItem.Model.Locations.Insert(0, location);
                                    }
                                }

                                Feed.Save(_localfeedLocation);
                                if (_cloudFileSystem != null) {
                                    _cloudFileSystem.WriteBlob(_packageStorageFolder, Path.GetFileName(_localfeedLocation).ToLower() , _localfeedLocation, false, (progress) => {
                                        ConsoleExtensions.PrintProgressBar("{0} => {1}".format(_localfeedLocation, _packageStorageFolder), progress);
                                    });
                                    Console.WriteLine();

                                    _cloudFileSystem.WriteBlob(_packageStorageFolder, Path.GetFileName(_localfeedLocation).ToLower()+".gz", _localfeedLocation, true, (progress) => {
                                        ConsoleExtensions.PrintProgressBar("{0} => {1}".format(_localfeedLocation+".gz", _packageStorageFolder), progress);
                                    });
                                    Console.WriteLine();

                                }
                            }

                            // Advertise the package on twitter
                            if (_tweeter != null) {
                                // pkg.Name
                                Bitly.Shorten(location.AbsoluteUri).ContinueWith(
                                    (x) => {
                                        var name = "[{0}-{1}-{2}]".format(pkg.Name, pkg.Version, pkg.Architecture);

                                        var summary = pkg.Summary;
                                        var l1 = 138 - (name.Length + x.Result.Length);
                                        if( summary.Length > l1 ) {
                                            summary = summary.Substring(0, l1 - 1) + "\u2026";
                                        }
                                        var text = "{0} {1} {2}".format(name, summary, x.Result);
                                        Console.WriteLine("Tweet: {0}",text);
                                        _tweeter.Tweet(text);
                                    });
                            }

                            response.StatusCode = 200;
                            response.Close();
                        }, TaskContinuationOptions.AttachedToParent);

                });

            result.ContinueWith(
                antecedent => {
                    if (result.IsFaulted) {
                        var e = antecedent.Exception.InnerException;
                        Console.WriteLine("Error handling uploaded package: {0} -- {1}\r\n{2}", e.GetType(), e.Message, e.StackTrace);
                        response.StatusCode = 500;
                        response.Close();
                    }
                }, TaskContinuationOptions.OnlyOnFaulted);

            return result;
        }
Exemple #44
0
 public Task GetAtomFeed(IEnumerable<CanonicalName> canonicalNames)
 {
     var response = Event<GetResponseInterface>.RaiseFirst();
     var feed = new AtomFeed();
     var pkgs = canonicalNames.Select(each => SearchForPackages(each).FirstOrDefault()).Where(each => null != each);
     feed.Add(pkgs);
     response.AtomFeedText(feed.ToString());
     return FinishedSynchronously;
 }
Exemple #45
0
        public void DownloadCab()
        {
            if (!AtomTestSettings.EnableWinQualCabDownloadTests)
            {
                return;
            }

            DateTime startTime = DateTime.Now.AddDays(-89);

            AtomFeed atomFeed = new AtomFeed(null, 1, 100000, false, true, null, 11);

            Assert.AreEqual(true, atomFeed.Login(TestSettings.WinQualUserName, TestSettings.WinQualPassword));

            try
            {
                // ATOM GetProducts.
                AtomProductCollection atomProducts = atomFeed.GetProducts();

                bool foundCab = false;

                foreach (AtomProduct atomProduct in atomProducts)
                {
                    AtomFileCollection atomFiles = atomFeed.GetFiles(atomProduct);

                    foreach (AtomFile atomFile in atomFiles)
                    {
                        AtomEventCollection atomEvents = atomFeed.GetEvents(atomFile, startTime);

                        foreach (AtomEvent atomEvent in atomEvents)
                        {
                            AtomCabCollection atomCabs = atomFeed.GetCabs(atomEvent);

                            foreach (AtomCab atomCab in atomCabs)
                            {
                                Assert.AreEqual(true, atomCab.Cab.DateCreatedLocal < DateTime.Now);

                                String tempFolder = Path.GetTempPath();

                                String fileName = atomFeed.DownloadCab(atomCab, true, tempFolder);

                                try
                                {
                                    Assert.AreEqual(true, File.Exists(fileName));
                                    FileInfo fileInfo = new FileInfo(fileName);

                                    Assert.AreEqual(atomCab.Cab.SizeInBytes, fileInfo.Length);
                                }
                                finally
                                {
                                    if (File.Exists(fileName))
                                    {
                                        File.Delete(fileName);
                                    }
                                }

                                foundCab = true;
                            }

                            if (foundCab)
                            {
                                return;
                            }
                        }
                    }
                }

                Assert.AreEqual(true, false); // Should get here.
            }
            finally
            {
                try { atomFeed.LogOut(); }
                catch { }
            }
        }
        private void InsertIntoFeed(CanonicalName pkgCanonicalName, FourPartVersion pkgVersion,  Uri location , AtomItem item = null)
        {
            lock (typeof(UploadedFileHandler)) {
                // update the feed
                var feed = new AtomFeed();

                //load the feed from the _canonicalFeedUrl if we can
                try {
                    var originalFeed = LoadFeed();

                    foreach (AtomItem i in originalFeed.Items.Where(each => each is AtomItem)) {
                        if (_feedName == "current") {
                            // if an older version of this package is in the current feed,
                            if (i.Model.CanonicalName.DiffersOnlyByVersion(pkgCanonicalName) && i.Model.CanonicalName.Version < pkgVersion) {
                                // push it to the archive feed.
                                FeedHandlers["archive"].InsertIntoFeed(i.Model.CanonicalName, i.Model.Version, i.Model.Locations[0]);
                                // and skip it
                                continue;
                            }
                        }
                        feed.Add(i);
                    }
                } catch {

                }
                item = item ?? _packageManager.GetAtomItem(pkgCanonicalName).Result;

                if (item != null) {
                    // first, make sure that the feeds contains the intended feed location.

                    item.Model.Feeds = item.Model.Feeds  ??new XList<Uri>();
                    if (!item.Model.Feeds.Contains(_canonicalFeedUrl)) {
                        item.Model.Feeds.Insert(0, _canonicalFeedUrl);
                    }

                    item.Model.Locations = item.Model.Locations  ?? new XList<Uri>();
                    if (!item.Model.Locations.Contains(location)) {
                        item.Model.Locations.Insert(0, location);
                    }

                    // drop dead urls
                    item.Model.Feeds = item.Model.Feeds.Distinct().Where(Peek).ToXList();
                    item.Model.Locations = item.Model.Locations.Distinct().Where(Peek).ToXList();
                    foreach( var l in item.Links.ToArray().Where( each => !Peek(each.Uri) ) ) {
                        item.Links.Remove(l);
                    }

                    if (item.Model.Locations.Any()) {
                        // if we've got at least one valid location, add the item to the feed.
                        feed.Add(item);
                    }
                }
                SaveFeed( feed);
            }
        }
Exemple #47
0
 internal AtomPackageFeed(Uri remoteLocation, string location)
     : base(location)
 {
     _remoteLocation = remoteLocation;
     _feed = AtomFeed.Load(location);
 }
        public object GetExamples()
        {
            AtomFeed <AllocationModel> feeds = JsonConvert.DeserializeObject <AtomFeed <AllocationModel> >(Properties.Resources.V1_Sample_Allocation_Feeds);

            return(feeds);
        }
Exemple #49
0
 internal AutopackageModel(PackageSource source, AtomFeed feed)
     : this()
 {
     Source = source;
     foreach( var sheet in Source.PropertySheets ) {
         sheet.GetMacroValue += GetMacroValue;
     }
     AtomFeed = feed;
 }
Exemple #50
0
        public void DownloadSingleCab()
        {
            if (!AtomTestSettings.EnableWinQualCabDownloadTests)
            {
                return;
            }

            AtomFeed atomFeed = new AtomFeed(null, 1, 100000, false, false, null, 11);

            // ATOM LOGIN.
            Assert.AreEqual(true, atomFeed.Login(TestSettings.WinQualUserName, TestSettings.WinQualPassword));

            // ATOM GetProducts.
            AtomProductCollection atomProducts = atomFeed.GetProducts();


            // WERAPI Login.
            Login login = new Login(TestSettings.WinQualUserName, TestSettings.WinQualPassword);

            login.Validate();

            foreach (AtomProduct atomProduct in atomProducts)
            {
                Console.WriteLine("Processing product " + atomProduct.Product.Name + " " + atomProduct.Product.Id.ToString());

                // ATOM GetFiles.
                AtomFileCollection atomFiles = atomFeed.GetFiles(atomProduct);

                foreach (AtomFile atomFile in atomFiles)
                {
                    Console.WriteLine("Processing file " + atomFile.File.Name + " " + atomFile.File.Id.ToString());
                    // ATOM GetEvents.
                    AtomEventCollection atomEvents = atomFeed.GetEvents(atomFile);

                    foreach (AtomEvent atomEvent in atomEvents)
                    {
                        Console.WriteLine("Processing event " + atomEvent.Event.Id.ToString());

                        // ATOM GetCabs.
                        AtomCabCollection atomCabs = atomFeed.GetCabs(atomEvent);

                        if (atomCabs.Count != 0)
                        {
                            StackHashCab cab = atomCabs[0].Cab;

                            // Convert back to an AtomCab.
                            AtomCab newCab = new AtomCab(cab, AtomCab.MakeLink(atomEvent.Event.EventTypeName, atomEvent.Event.Id, cab.Id, cab.SizeInBytes));

                            Console.WriteLine("Downloading cab " + cab.Id.ToString());

                            String tempFolder = Path.GetTempPath();

                            String fileName = atomFeed.DownloadCab(newCab, true, tempFolder);

                            try
                            {
                                Assert.AreEqual(true, File.Exists(fileName));
                                FileInfo fileInfo = new FileInfo(fileName);

                                Assert.AreEqual(cab.SizeInBytes, fileInfo.Length);
                            }
                            finally
                            {
                                if (File.Exists(fileName))
                                {
                                    File.Delete(fileName);
                                }
                            }

                            // 1 is enough.
                            return;
                        }
                    }
                }
            }
        }
 public XmlWriter CreateFeedWriterFor(AtomFeed atomFeed)
 {
     this.observedArguments.Add(atomFeed);
     return this.store.CreateFeedWriterFor(atomFeed);
 }
Exemple #52
0
 public AtomFeed Parse(string xml)
 {
     return(AtomFeed.Parse(xml, this.serializer));
 }
 private Task<int> Validate()
 {
     return Task.Factory.StartNew(() => {
         var feed = new AtomFeed();
         //load the feed from the _canonicalFeedUrl if we can
         try {
             var originalFeed = LoadFeed();
             foreach (AtomItem i in originalFeed.Items.Where(each => each is AtomItem)) {
                 // drop dead urls
                 i.Model.Feeds = i.Model.Feeds.Distinct().Where(Peek).ToXList();
                 i.Model.Locations = i.Model.Locations.Distinct().Where(Peek).ToXList();
                 foreach (var l in i.Links.ToArray().Where(each => !Peek(each.Uri))) {
                     i.Links.Remove(l);
                 }
                 if (i.Model.Locations.Any()) {
                     feed.Add(i);
                 }
             }
             SaveFeed(feed);
         } catch {
             return 500;
         }
         return 200;
     });
 }
Exemple #54
0
 internal WixDocument(PackageSource source, AutopackageModel model, AtomFeed feed)
 {
     Source = source;
     Model = model;
     Feed = feed;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="ApplicationSetupInfo"/>
 /// class.
 /// </summary>
 /// <param name="feed">
 /// An object representing a Splunk atom feed response.
 /// </param>
 internal ApplicationSetupInfo(AtomFeed feed)
 {
     this.Initialize(feed);
 }
Exemple #56
0
        /// <summary>
        /// Instantiates a <see cref="ISyndicationResource"/> that conforms to the specified <see cref="SyndicationContentFormat"/> using the supplied <see cref="Stream"/>.
        /// </summary>
        /// <param name="stream">The <see cref="Stream"/> used to load the syndication resource.</param>
        /// <param name="format">A <see cref="SyndicationContentFormat"/> enumeration value that indicates the type syndication resource the <paramref name="stream"/> represents.</param>
        /// <returns>
        ///     An <see cref="ISyndicationResource"/> object that conforms to the specified <paramref name="format"/>, initialized using the supplied <paramref name="stream"/>.
        ///     If the <paramref name="format"/> is not supported by the provider, returns a <b>null</b> reference.
        /// </returns>
        /// <exception cref="ArgumentNullException">The <paramref name="stream"/> is a null reference (Nothing in Visual Basic).</exception>
        private static ISyndicationResource BuildResource(SyndicationContentFormat format, Stream stream)
        {
            Guard.ArgumentNotNull(stream, "stream");

            if (format == SyndicationContentFormat.Apml)
            {
                ApmlDocument document = new ApmlDocument();
                document.Load(stream);
                return(document);
            }
            else if (format == SyndicationContentFormat.Atom)
            {
                XPathDocument  document  = new XPathDocument(stream);
                XPathNavigator navigator = document.CreateNavigator();
                navigator.MoveToRoot();
                navigator.MoveToChild(XPathNodeType.Element);

                if (String.Compare(navigator.LocalName, "entry", StringComparison.OrdinalIgnoreCase) == 0)
                {
                    AtomEntry entry = new AtomEntry();
                    entry.Load(navigator);
                    return(entry);
                }
                else if (String.Compare(navigator.LocalName, "feed", StringComparison.OrdinalIgnoreCase) == 0)
                {
                    AtomFeed feed = new AtomFeed();
                    feed.Load(navigator);
                    return(feed);
                }
                else
                {
                    return(null);
                }
            }
            else if (format == SyndicationContentFormat.BlogML)
            {
                BlogMLDocument document = new BlogMLDocument();
                document.Load(stream);
                return(document);
            }
            else if (format == SyndicationContentFormat.Opml)
            {
                OpmlDocument document = new OpmlDocument();
                document.Load(stream);
                return(document);
            }
            else if (format == SyndicationContentFormat.Rsd)
            {
                RsdDocument document = new RsdDocument();
                document.Load(stream);
                return(document);
            }
            else if (format == SyndicationContentFormat.Rss)
            {
                RssFeed feed = new RssFeed();
                feed.Load(stream);
                return(feed);
            }
            else
            {
                return(null);
            }
        }
Exemple #57
0
        internal void GenerateAtomFeed(string outputFilename, string packageSource, bool recursive,  string rootUrl, string packageUrl, string actualUrl = null, string title = null)
        {
            outputFilename = Path.GetFullPath(outputFilename);
            PackageFeed.GetPackageFeedFromLocation(packageSource, recursive).ContinueWith(antecedent => {
                var packageFeed = antecedent.Result;

                var generatedFeed = new AtomFeed(outputFilename, rootUrl, packageUrl, actualUrl, title);

                foreach (var pkg in packageFeed.FindPackages("*")) {
                    generatedFeed.AddPackage(pkg, packageFeed.Location.RelativePathTo(pkg.LocalPackagePath));
                }
                generatedFeed.Save(outputFilename);

            }, TaskContinuationOptions.AttachedToParent ).Wait();
        }