示例#1
0
 public void Copy(Model.Campeonatos.Grupo entry)
 {
     _nome            = entry._nome;
     _descricao       = entry._descricao;
     _campeonato      = entry._campeonato;
     _timesCollection = entry._timesCollection;
 }
示例#2
0
        /// <summary>
        /// Logs an error to the application memory.
        /// </summary>
        /// <remarks>
        /// If the log is full then the oldest error entry is removed.
        /// </remarks>

        public override void Log(Error error)
        {
            if (error == null)
            {
                throw new ArgumentNullException("error");
            }

            //
            // Make a copy of the error to log since the source is mutable.
            // Assign a new GUID and create an entry for the error.
            //

            error = (Error)((ICloneable)error).Clone();
            error.ApplicationName = this.ApplicationName;
            Guid          newId = Guid.NewGuid();
            ErrorLogEntry entry = new ErrorLogEntry(this, newId.ToString(), error);

            _lock.AcquireWriterLock(Timeout.Infinite);

            try
            {
                if (_entries == null)
                {
                    _entries = new EntryCollection(_size);
                }

                _entries.Add(newId, entry);
            }
            finally
            {
                _lock.ReleaseWriterLock();
            }
        }
        public static CategoryListViewModel Create(EntryCollection entries, IDasBlogSettings dasBlogSettings, string categoryName = "")
        {
            var viewModel = new CategoryListViewModel();

            foreach (var entry in entries)
            {
                string[] categories = null;
                if (categoryName == string.Empty)
                {
                    categories = entry.GetSplitCategories();
                }
                else
                {
                    categories = new string[] { categoryName };
                }

                foreach (var category in categories)
                {
                    var archiveItem = CategoryPostItem.CreateFromEntry(entry, dasBlogSettings);
                    archiveItem.Category = category;
                    if (viewModel.Categories.ContainsKey(category))
                    {
                        viewModel.Categories[category].Add(archiveItem);
                        continue;
                    }

                    viewModel.Categories[category] = new List <CategoryPostItem> {
                        archiveItem
                    };
                }
            }

            return(viewModel);
        }
示例#4
0
 public Entry(Guid id, TableOfContentsModel toc, SlideModel slide) : base(toc)
 {
     this.m_Id       = id;
     this.m_Children = new EntryCollection(this, "Entries");
     this.m_TOC      = toc;
     this.m_Slide    = slide;
 }
示例#5
0
        public void ResponseObjectExpirationTest(int world_id, int map_id, Guid?event_id, bool ignoreCache, int expiresAfter, int nowOffset)
        {
            EntryCollection <EventEntry> expected = GwApi.GetEvents(world_id, map_id, event_id, true);

            expected.CacheStrategy = new AgeCacheStrategy(TimeSpan.FromMilliseconds(expiresAfter));
            expected.LastUpdated   = expected.LastUpdated.Subtract(TimeSpan.FromMilliseconds(nowOffset));
            ResponseCache.Cache.Add(expected);
            Assert.IsFalse(expected.FromCache);

            var actual = GwApi.GetEvents(world_id, map_id, event_id, ignoreCache);

            if (ignoreCache || nowOffset >= expiresAfter)
            {
                // forced update, or has expired
                Assert.LessOrEqual(expected.LastUpdated, actual.LastUpdated);
                Assert.Greater(expected.Age, actual.Age);
                Assert.IsFalse(actual.Expired);   // If it was just updated, it shouldn't expire so soon
                Assert.IsFalse(actual.FromCache); // must always be false if cache was ignored
            }
            else
            {
                // Not expired and therefore from cache
                Assert.AreEqual(expected.LastUpdated, actual.LastUpdated);
                Assert.AreEqual(expected.Age, actual.Age);
                Assert.IsFalse(actual.Expired);
                Assert.IsTrue(actual.FromCache);
            }
        }
        public void EntryCollections_FilteringPublicEntries_CountsShouldDifferAfterFiltering()
        {
            var entry1 = CreateEntry("public 2007", true, new DateTime(2007, 2, 2));
            var entry2 = CreateEntry("public 2006", true, new DateTime(2006, 2, 2));
            var entry3 = CreateEntry("not public 2006", false, new DateTime(2006, 2, 2));

            var collection = new EntryCollection(new Entry[] { entry1, entry2, entry3 });

            Predicate <Entry> filter = null;

            Predicate <Entry> isPublic = delegate(Entry e)
            {
                return(e.IsPublic);
            };

            filter += isPublic;

            Predicate <Entry> is2006Published = delegate(Entry e)
            {
                return(e.CreatedLocalTime.Year == 2006);
            };

            filter += is2006Published;

            var classic = EntryCollectionFilter.FindAll(collection, filter);
            var generic = collection.FindAll(filter);

            Assert.NotEqual(classic.Count, generic.Count);
        }
示例#7
0
        public EntryCollection GetCategoryEntries(string categoryName)
        {
            CategoryCache cache = new CategoryCache();

            cache.Ensure(data);

            EntryCollection entryList = new EntryCollection();

            foreach (CategoryCacheEntry catEntry in cache.Entries)
            {
                if (catEntry.Name.ToUpper() == categoryName)
                {
                    foreach (CategoryCacheEntryDetail detail in catEntry.EntryDetails)
                    {
                        foreach (DayEntry day in data.Days)
                        {
                            if (day.Date == detail.DayDate)
                            {
                                day.Load();
                                foreach (Entry entry in day.Entries)
                                {
                                    if (entry.EntryId == detail.EntryId)
                                    {
                                        entryList.Add(entry);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            entryList.Sort(new EntrySorter());
            return(entryList);
        }
示例#8
0
        protected void Page_Init(object sender, EventArgs e)
        {
            resmgr = ApplicationResourceTable.Get();

            requestPage = Page as SharedBasePage;

            if (Request.QueryString["q"] != null && Page.IsPostBack == false)
            {
                string          searchQuery = System.Web.HttpUtility.UrlDecode(Request.QueryString["q"]);
                EntryCollection entries     = SearchEntries(searchQuery);

                requestPage.WeblogEntries.AddRange(entries);

                foreach (Entry entry in requestPage.WeblogEntries)
                {
                    requestPage.ProcessItemTemplate(entry, contentPlaceHolder);
                }
            }
            else
            {
                requestPage.WeblogEntries.AddRange(new EntryCollection());
            }

            labelSearchQuery.Text = String.Format("{0}: {1}", resmgr.GetString("text_search_query_title"), Request.QueryString["q"]);

            DataBind();
        }
示例#9
0
            public void RegisterEntry(EntryCollection entries, int insertIndex, bool overrideRegistry, out bool activated)
            {
                if (IsEmpty)
                {
                    if (overrideRegistry)
                    {
                        Entry e = entries[insertIndex];
                        e.PreviousUsedIndexInBucket = -1;
                        e.NextUsedIndexInBucket     = -1;
                    }

                    OldestUsedEntryIndex = insertIndex;
                    LatestUsedEntryIndex = insertIndex;
                    activated            = true;
                }
                else
                {
                    entries[LatestUsedEntryIndex].NextUsedIndexInBucket = insertIndex;
                    Entry e = entries[insertIndex];
                    e.PreviousUsedIndexInBucket = LatestUsedEntryIndex;
                    if (overrideRegistry)
                    {
                        e.NextUsedIndexInBucket = -1;
                    }
                    LatestUsedEntryIndex = insertIndex;
                    activated            = false;
                }

                UsedCount++;
            }
示例#10
0
        private static EntryCollection <ItemDefence> LoadArmors()
        {
            try
            {
                String inputPath = DataResources.Items.ArmorsFile;
                if (!File.Exists(inputPath))
                {
                    throw new FileNotFoundException($"[ff9armor] Cannot load armors because a file does not exist: [{inputPath}].", inputPath);
                }

                ItemDefence[] items = CsvReader.Read <ItemDefence>(inputPath);
                if (items.Length < 136)
                {
                    throw new NotSupportedException($"You must set at least 136 armors, but there {items.Length}. Any number of items will be available after a game stabilization.");
                }

                return(EntryCollection.CreateWithDefaultElement(items, i => i.Id));
            }
            catch (Exception ex)
            {
                Log.Error(ex, "[ff9armor] Load armors failed.");
                UIManager.Input.ConfirmQuit();
                return(null);
            }
        }
示例#11
0
        public MoveableType.PostTitle[] mt_getRecentPostTitles(string blogid, string username, string password, int numberOfPosts)
        {
            if (!_dasBlogSettings.SiteConfiguration.EnableBloggerApi)
            {
                throw new ServiceDisabledException();
            }
            UserToken token = _siteSecurity.Login(username, password);

            if (token == null)
            {
                throw new SecurityException();
            }
            EntryCollection entries = _dataService.GetEntriesForDay(DateTime.Now.ToUniversalTime(), TimeZone.CurrentTimeZone, null,
                                                                    _dasBlogSettings.SiteConfiguration.RssDayCount, numberOfPosts, null);
            List <MoveableType.PostTitle> arrayList = new List <MoveableType.PostTitle>();

            foreach (Entry entry in entries)
            {
                MoveableType.PostTitle post = new MoveableType.PostTitle();
                post.title       = NoNull(entry.Title);
                post.dateCreated = entry.CreatedUtc;
                post.postid      = NoNull(entry.EntryId);
                post.userid      = username;
                arrayList.Add(post);
            }
            return(arrayList.ToArray());
        }
        public void GetEntriesForDay()
        {
            IBlogDataService dataService = BlogDataServiceFactory.GetService(createEntries.FullName, null);

            // this will create an entry for each hour of the day in local time
            for (int i = 0; i < 24; i++)
            {
                Entry entry = TestEntry.CreateEntry(String.Format("Test Entry {0}", i), 5, 2);
                entry.CreatedUtc = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, i, 0, 0).ToUniversalTime();
                dataService.SaveEntry(entry, null);
            }

            EntryCollection entries = dataService.GetEntriesForDay(DateTime.Now, TimeZone.CurrentTimeZone, String.Empty, int.MaxValue, int.MaxValue, String.Empty);

            Assert.AreEqual(24, entries.Count);

            foreach (Entry entry in entries)
            {
                // this test will make sure that the entries are all in the right day
                Entry lookup = dataService.GetEntry(entry.EntryId);
                Assert.IsNotNull(lookup);
                Assert.AreEqual(0, lookup.CompareTo(entry));
                Assert.AreEqual(DateTime.Now.Date, entry.CreatedLocalTime.Date);
            }
        }
示例#13
0
        public Blogger.Post[] blogger_getRecentPosts(string appKey, string blogid, string username, string password, int numberOfPosts)
        {
            if (!_dasBlogSettings.SiteConfiguration.EnableBloggerApi)
            {
                throw new ServiceDisabledException();
            }
            UserToken token = _siteSecurity.Login(username, password);

            if (token == null)
            {
                throw new SecurityException();
            }

            EntryCollection entries = _dataService.GetEntriesForDay(DateTime.Now.ToUniversalTime(), _dasBlogSettings.GetConfiguredTimeZone(),
                                                                    null, _dasBlogSettings.SiteConfiguration.RssDayCount, numberOfPosts, null);
            List <Blogger.Post> arrayList = new List <Blogger.Post>();

            foreach (Entry entry in entries)
            {
                Blogger.Post post = new Blogger.Post();
                FillBloggerPostFromEntry(entry, ref post);
                arrayList.Add(post);
            }
            return(arrayList.ToArray());
        }
示例#14
0
        public void ProcessRequest(HttpContext context)
        {
            ILoggingDataService logService = LoggingDataServiceFactory.GetService(SiteConfig.GetLogPathFromCurrentContext());

            try
            {
                IBlogDataService dataService = BlogDataServiceFactory.GetService(SiteConfig.GetContentPathFromCurrentContext(), logService);
                SiteConfig       siteConfig  = SiteConfig.GetSiteConfig();

                string languageFilter = context.Request.Headers["Accept-Language"];
                if (SiteSecurity.IsInRole("admin"))
                {
                    languageFilter = "";
                }

                EntryCollection entries = dataService.GetEntriesForDay(DateTime.UtcNow, siteConfig.GetConfiguredTimeZone(), languageFilter, 1, 1, String.Empty);

                if (entries != null && entries.Count > 0)
                {
                    Entry e = entries[0];
                    context.Response.Write(e.Title);
                }
            }
            catch (Exception ex)
            {
                logService.AddEvent(new EventDataItem(EventCodes.Error, "Error generating Microsummary: " + ex.ToString(), String.Empty));
            }
        }
示例#15
0
        private static EntryCollection <ItemStats> LoadStats()
        {
            try
            {
                String inputPath = DataResources.Items.StatsFile;
                if (!File.Exists(inputPath))
                {
                    throw new FileNotFoundException($"[{nameof(ff9equip)}] Cannot load items stats because a file does not exist: [{inputPath}].", inputPath);
                }

                ItemStats[] items = CsvReader.Read <ItemStats>(inputPath);
                if (items.Length < 88)
                {
                    throw new NotSupportedException($"[{nameof(ff9equip)}] You must set at least 176 item stats, but there {items.Length}. Any number of items will be available after a game stabilization.");
                }

                return(EntryCollection.CreateWithDefaultElement(items, i => i.Id));
            }
            catch (Exception ex)
            {
                Log.Error(ex, $"[{nameof(ff9equip)}] Load weapons failed.");
                UIManager.Input.ConfirmQuit();
                return(null);
            }
        }
        public void FilterTest()
        {
            Entry entry1 = CreateEntry("public 2007", true, new DateTime(2007, 2, 2));
            Entry entry2 = CreateEntry("public 2006", true, new DateTime(2006, 2, 2));
            Entry entry3 = CreateEntry("not public 2006", false, new DateTime(2006, 2, 2));

            EntryCollection collection = new EntryCollection(new Entry[] { entry1, entry2, entry3 });

            Predicate <Entry> filter = null;

            Predicate <Entry> isPublic = delegate(Entry e)
            {
                return(e.IsPublic);
            };

            filter += isPublic;

            Predicate <Entry> is2006Published = delegate(Entry e)
            {
                return(e.CreatedLocalTime.Year == 2006);
            };

            filter += is2006Published;

            EntryCollection classic = EntryCollectionFilter.FindAll(collection, filter);
            List <Entry>    generic = collection.FindAll(filter);

            Assert.AreNotEqual(classic.Count, generic.Count, "Number of items doesn't match.");
        }
示例#17
0
            public void UnregisterEntry(EntryCollection entries, int index, out bool deactivated)
            {
                Entry e = entries[index];

                if (e.PreviousUsedIndexInBucket != -1)
                {
                    entries[e.PreviousUsedIndexInBucket].NextUsedIndexInBucket = e.NextUsedIndexInBucket;
                }

                if (e.NextUsedIndexInBucket != -1)
                {
                    entries[e.NextUsedIndexInBucket].PreviousUsedIndexInBucket = e.PreviousUsedIndexInBucket;
                }

                UsedCount--;

                if (index == LatestUsedEntryIndex)
                {
                    LatestUsedEntryIndex = e.PreviousUsedIndexInBucket;
                }

                if (IsEmpty)
                {
                    deactivated = true;
                }

                else
                {
                    deactivated = false;
                }
            }
示例#18
0
        /// <summary>
        /// Logs an error to the application memory.
        /// </summary>
        /// <remarks>
        /// If the log is full then the oldest error entry is removed.
        /// </remarks>

        public override string Log(Error error)
        {
            if (error == null)
            {
                throw new ArgumentNullException("error");
            }

            //
            // Make a copy of the error to log since the source is mutable.
            // Assign a new GUID and create an entry for the error.
            //

            error = error.CloneObject();
            error.ApplicationName = ApplicationName;
            var newId = Guid.NewGuid();
            var entry = new ErrorLogEntry(this, newId.ToString(), error);

            _lock.EnterWriteLock();

            try
            {
                var entries = _entries ?? (_entries = new EntryCollection(_size));
                entries.Add(entry);
            }
            finally
            {
                _lock.ExitWriteLock();
            }

            return(newId.ToString());
        }
示例#19
0
        protected override EntryCollection LoadEntries()
        {
            if (WeblogEntryId.Length == 0)
            {
                Response.StatusCode      = 404;
                Response.SuppressContent = true;
                Response.End();
                return(null);                //save us all the time
            }


            EntryCollection     entryCollection = new EntryCollection();
            Entry               entry           = DataService.GetEntry(WeblogEntryId);
            ILoggingDataService logService      = this.LoggingService;

            if (entry != null)
            {
                entryCollection.Add(entry);

                if (NotModified(entryCollection))
                {
                    Response.End();
                    return(null);
                }
            }

            return(entryCollection);
        }
示例#20
0
		public void TestTrackbackCreation()
		{
			EntryCollection entries = new EntryCollection();

			entries = blogService.GetEntriesForDay(DateTime.MaxValue.AddDays(-2), TimeZone.CurrentTimeZone, String.Empty, int.MaxValue, int.MaxValue, String.Empty);

			int numberOfTrackings = 3;

			for (int i = 0; i < numberOfTrackings; i++)
			{
				Tracking t = new Tracking();
				t.PermaLink = "http://www.foo.com/" + i;
				t.RefererBlogName = "Trackback " + i;
				t.RefererExcerpt = "";
				t.RefererTitle = "Trackback " + i;
				t.TargetEntryId = entries[0].EntryId;
				t.TargetTitle = entries[0].Title;
				t.TrackingType = TrackingType.Trackback;

				blogService.AddTracking( t );
			}

			System.Threading.Thread.Sleep(2000);

			TrackingCollection trackingCollection  = blogService.GetTrackingsFor(entries[0].EntryId);

			Assert.IsTrue(trackingCollection.Count == numberOfTrackings);
		}
示例#21
0
        private static EntryCollection <FF9MIX_DATA> LoadSynthesis()
        {
            try
            {
                String inputPath = DataResources.Items.SynthesisFile;
                if (!File.Exists(inputPath))
                {
                    throw new FileNotFoundException($"[ff9mix] Cannot load synthesis info because a file does not exist: [{inputPath}].", inputPath);
                }

                FF9MIX_DATA[] items = CsvReader.Read <FF9MIX_DATA>(inputPath);
                if (items.Length < 64)
                {
                    throw new NotSupportedException($"You must set at least 64 synthesis info, but there {items.Length}. Any number of items will be available after a game stabilization.");
                }

                return(EntryCollection.CreateWithDefaultElement(items, i => i.Id));
            }
            catch (Exception ex)
            {
                Log.Error(ex, "[ff9mix] Load synthesis info failed.");
                UIManager.Input.ConfirmQuit();
                return(null);
            }
        }
示例#22
0
            internal void AddValue(ParseResult result, KeyValuesFlags flags)
            {
                if (result.Parser.ElementName.EndsWith(".String"))
                {
                    _value = ReadString(result, flags);
                    return;
                }

                AssertParser(result, ".Definition.List");

                if (result.Length == 0)
                {
                    return;
                }

                if (_subEntries == null)
                {
                    _subEntries = new Dictionary <string, EntryCollection>(StringComparer.InvariantCultureIgnoreCase);
                }

                foreach (var def in result)
                {
                    var key = ReadString(def[0], flags);

                    if (!_subEntries.TryGetValue(key, out var existing))
                    {
                        _subEntries.Add(key, existing = new EntryCollection());
                    }

                    existing.AddValue(def[1], flags);
                }
            }
示例#23
0
        public void EntryCollections_FilterAndMaxResults_OnlyReturnsOneEntry()
        {
            var entry1 = CreateEntry("public 2007.1", true, new DateTime(2007, 2, 2));
            var entry2 = CreateEntry("public 2006.1", true, new DateTime(2006, 2, 2));
            var entry3 = CreateEntry("not public 2006.1", false, new DateTime(2006, 2, 2));
            var entry4 = CreateEntry("public 2007.2", true, new DateTime(2007, 2, 2));
            var entry5 = CreateEntry("public 2006.2", true, new DateTime(2006, 2, 2));
            var entry6 = CreateEntry("not public 2006.2", false, new DateTime(2006, 2, 2));

            var collection = new EntryCollection(new Entry[] { entry1, entry2, entry3, entry4, entry5, entry6 });

            Predicate <Entry> filter = null;

            Predicate <Entry> isPublic = delegate(Entry e)
            {
                return(e.IsPublic);
            };

            filter += isPublic;

            Predicate <Entry> is2006Published = delegate(Entry e)
            {
                return(e.CreatedLocalTime.Year == 2006);
            };

            filter += is2006Published;

            // 2 items match the criteria (2,5), we only want 1 returned
            var filtered = EntryCollectionFilter.FindAll(collection, filter, 1);

            Assert.Single(filtered);
        }
示例#24
0
        public void TestTrackbackCreation()
        {
            EntryCollection entries = new EntryCollection();

            entries = blogService.GetEntriesForDay(DateTime.MaxValue.AddDays(-2), DateTimeZone.Utc, String.Empty, int.MaxValue, int.MaxValue, String.Empty);

            int numberOfTrackings = 3;

            for (int i = 0; i < numberOfTrackings; i++)
            {
                Tracking t = new Tracking();
                t.PermaLink       = "http://www.foo.com/" + i;
                t.RefererBlogName = "Trackback " + i;
                t.RefererExcerpt  = "";
                t.RefererTitle    = "Trackback " + i;
                t.TargetEntryId   = entries[0].EntryId;
                t.TargetTitle     = entries[0].Title;
                t.TrackingType    = TrackingType.Trackback;

                blogService.AddTracking(t);
            }

            System.Threading.Thread.Sleep(2000);

            TrackingCollection trackingCollection = blogService.GetTrackingsFor(entries[0].EntryId);

            Assert.IsTrue(trackingCollection.Count == numberOfTrackings);
        }
示例#25
0
        public IActionResult ArchiveAll()
        {
            var entries        = new EntryCollection();
            var languageFilter = httpContextAccessor.HttpContext.Request.Headers["Accept-Language"];
            var listofyears    = archiveManager.GetDaysWithEntries().Select(i => i.Year).Distinct();

            foreach (var year in listofyears)
            {
                entries.AddRange(
                    archiveManager.GetEntriesForYear(new DateTime(year, 1, 1), languageFilter).OrderByDescending(x => x.CreatedUtc));
            }

            var alvm = new ArchiveListViewModel();

            foreach (var i in entries.ToList().Select(entry => mapper.Map <PostViewModel>(entry)).ToList())
            {
                var index = int.Parse(string.Format("{0}{1}", i.CreatedDateTime.Year, string.Format("{0:00}", i.CreatedDateTime.Month)));

                if (alvm.MonthEntries.ContainsKey(index))
                {
                    alvm.MonthEntries[index].Add(i);
                }
                else
                {
                    var list = new List <PostViewModel>()
                    {
                        i
                    };
                    alvm.MonthEntries.Add(index, list);
                }
            }

            return(View(alvm));
        }
示例#26
0
        public static string CreateAMPSeoMetaInformation(EntryCollection weblogEntries, IBlogDataService dataService)
        {
            string metaTags = "\r\n";
            string blogPostDescription;
            string postImage = string.Empty;

            if (weblogEntries.Count >= 1)
            {
                Entry entry = weblogEntries[0];
                metaTags += string.Format(CanonicalLinkPattern, SiteUtilities.GetPermaLinkUrl(entry));

                blogPostDescription = entry.Content;

                try
                {
                    postImage = FindFirstImage(blogPostDescription);
                }
                catch (Exception ex)
                {
                    Trace.WriteLine("Exception looking for Images and Video: " + ex.ToString());
                    postImage = string.Empty;
                }

                metaTags += MetaSchemeOpenScript;
                metaTags += MetaSchemeContext;
                metaTags += MetaSchemeNewsType;
                metaTags += string.Format(MetaSchemeHeadline, entry.Title);
                metaTags += string.Format(MetaSchemeDatePublished, entry.CreatedUtc.ToString("yyyy-MM-dd"));
                metaTags += string.Format(MetaSchemeImage, postImage);
                metaTags += MetaSchemeCloseScript;
            }

            return(metaTags);
        }
示例#27
0
    private static EntryCollection <AA_DATA> LoadActions()
    {
        try
        {
            String inputPath = DataResources.Battle.ActionsFile;
            if (!File.Exists(inputPath))
            {
                throw new FileNotFoundException($"File with character actions not found: [{inputPath}]");
            }

            BattleActionEntry[] statusSets = CsvReader.Read <BattleActionEntry>(inputPath);
            if (statusSets.Length < BattleStatusEntry.SetsCount)
            {
                throw new NotSupportedException($"You must set {BattleStatusEntry.SetsCount} status sets, but there {statusSets.Length}.");
            }

            return(EntryCollection.CreateWithDefaultElement(statusSets, e => e.Id, e => e.ActionData));
        }
        catch (Exception ex)
        {
            Log.Error(ex, "[ff9level] Load base stats of characters failed.");
            UIManager.Input.ConfirmQuit();
            return(null);
        }
    }
示例#28
0
        public void FilterTest()
        {
            Entry entry1 = CreateEntry("public 2007", true, new DateTime(2007, 2, 2));
            Entry entry2 = CreateEntry("public 2006", true, new DateTime(2006, 2, 2));
            Entry entry3 = CreateEntry("not public 2006", false, new DateTime(2006, 2, 2));

            EntryCollection collection = new EntryCollection(new Entry[] { entry1, entry2, entry3 });

            Predicate<Entry> filter = null;

            Predicate<Entry> isPublic = delegate(Entry e)
            {
                return e.IsPublic;
            };

            filter += isPublic;

            Predicate<Entry> is2006Published = delegate(Entry e)
            {
                return e.CreatedLocalTime.Year == 2006;
            };

            filter += is2006Published;

            EntryCollection classic = EntryCollectionFilter.FindAll(collection, filter);
            List<Entry> generic = collection.FindAll(filter);

            Assert.AreNotEqual(classic.Count, generic.Count, "Number of items doesn't match.");
        }
示例#29
0
 protected void Submit_Click1(object sender, EventArgs e)
 {
     //Validate the data coming in
     if (Page.IsValid)
     {
         string firstName  = FirstName.Text;
         string lastName   = LastName.Text;
         string address1   = StreetAddress1.Text;
         string address2   = StreetAddress2.Text;
         string city       = City.Text;
         string province   = Province.Text;
         string postalCode = PostalCode.Text;
         string eMail      = EmailAddress.Text;
         //Validate the user checking the terms
         if (Terms.Checked)
         {
             //If yes: Create and load an entry, add to List, display List
             nCollection.Add(new NewCollection(firstName, lastName, address1, address2, city, province, postalCode, eMail));
             EntryCollection.DataSource = nCollection;
             EntryCollection.DataBind();
         }
         else
         {
             //If no: Message
             Message.Text = "Please agree to the terms of this contest";
         }
     }
 }
示例#30
0
文件: ff9buy.cs 项目: ArtReeX/memoria
        private static EntryCollection <ShopItems> LoadShopItems()
        {
            try
            {
                String inputPath = DataResources.Items.ShopItems;
                if (!File.Exists(inputPath))
                {
                    throw new FileNotFoundException($"File with shop items not found: [{inputPath}]");
                }

                ShopItems[] shopItems = CsvReader.Read <ShopItems>(inputPath);
                if (shopItems.Length < FF9BUY_SHOP_MAX)
                {
                    throw new NotSupportedException($"You must set an assortment for {FF9BUY_SHOP_MAX} shops, but there {shopItems.Length}.");
                }

                return(EntryCollection.CreateWithDefaultElement(shopItems, e => e.Id));
            }
            catch (Exception ex)
            {
                Log.Error(ex, "[ff9buy] Load shop items failed.");
                UIManager.Input.ConfirmQuit();
                return(null);
            }
        }
示例#31
0
        public static CategoryListViewModel Create(EntryCollection entries, string categoryName = "")
        {
            var viewModel = new CategoryListViewModel();

            foreach (var entry in entries)
            {
                var categories = entry.GetSplitCategories();

                foreach (var category in categories)
                {
                    var archiveItem = CategoryPostItem.CreateFromEntry(entry);
                    archiveItem.Category = category;
                    if (viewModel.Categories.ContainsKey(category))
                    {
                        viewModel.Categories[category].Add(archiveItem);
                        continue;
                    }

                    viewModel.Categories[category] = new List <CategoryPostItem> {
                        archiveItem
                    };
                }
            }

            return(viewModel);
        }
示例#32
0
    private static EntryCollection <IdMap> LoadBattleCommandTitles()
    {
        try
        {
            String inputPath = DataResources.Characters.CommandTitlesFile;
            if (!File.Exists(inputPath))
            {
                throw new FileNotFoundException($"[BattleHUD] Cannot load character command titles because a file does not exist: [{inputPath}].", inputPath);
            }

            IdMap[] maps = CsvReader.Read <IdMap>(inputPath);
            if (maps.Length < 192)
            {
                throw new NotSupportedException($"You must set titles for 192 battle commands, but there {maps.Length}.");
            }

            return(EntryCollection.CreateWithDefaultElement(maps, g => g.Id));
        }
        catch (Exception ex)
        {
            Log.Error(ex, "[BattleHUD] Load character command titles failed.");
            UIManager.Input.ConfirmQuit();
            return(null);
        }
    }
示例#33
0
文件: AppTest.cs 项目: plntxt/dasblog
		public void CreateApp()
		{
			EntryCollection entries = new EntryCollection();
			DayEntryCollection days = new DayEntryCollection();

			entries = blogService.GetEntriesForDay(DateTime.MaxValue.AddDays(-2), TimeZone.CurrentTimeZone, String.Empty, int.MaxValue, int.MaxValue, String.Empty);

			Assert.IsNotNull(entries);
		}
		public static IEntryCollection Wrap(this SearchResultCollection wrapped) {
			var result = new EntryCollection();
			if(wrapped != null) {
				foreach(SearchResult searchResult in wrapped) {
					result.Add(searchResult.Wrap());
				}
			}
			return result;
		}
示例#35
0
        public Account(string number, string description, IEnumerable<Entry> entries)
        {
            this.number = number;
              this.description = description;
              this.entries = new EntryCollection();

              foreach (var entry in entries)
              {
            this.AddEntry(entry);
              }
        }
示例#36
0
 public void VerifyContains()
 {
     Entry entry1, entry2;
     entry1 = BlogDataService.GetEntry("ebd3060-b3b0-4ab1-baea-cd12ae34a575");
     EntryCollection entries = new EntryCollection();
     entries.Add(entry1);
     Assert.IsTrue(entries.Contains(entry1), "Unexpectedly the entry did not exist.");
     entry2 = BlogDataService.GetEntry("ebd3060-b3b0-4ab1-baea-cd12ae34a575");
     // The entries returned are identical (ReferenceEquals)
     Assert.AreSame(entry1, entry2, "Unexpectedly and entirely different entry instance was returned.");
     Assert.IsTrue(entries.Contains(entry2), "Unexpectedly the entry did not exist.");
 }
示例#37
0
文件: Seo.cs 项目: priyanr/dasblog
        public static string CreateSeoMetaInformation(EntryCollection weblogEntries, IBlogDataService dataService)
        {
            string metaTags = "\r\n";
            string currentUrl = HttpContext.Current.Request.Url.AbsoluteUri;

            if (currentUrl.IndexOf("categoryview.aspx", StringComparison.OrdinalIgnoreCase) > -1 || currentUrl.IndexOf("default.aspx?month=", StringComparison.OrdinalIgnoreCase) > -1)
            {
                metaTags += MetaNoindexFollowPattern;
            }
            else if (currentUrl.IndexOf("permalink.aspx", StringComparison.OrdinalIgnoreCase) > -1)
            {
                if (weblogEntries.Count >= 1)
                {
                    Entry entry = weblogEntries[0];
                    metaTags = GetMetaTags(metaTags, entry);
                }
            }
            else if (currentUrl.IndexOf("commentview.aspx", StringComparison.OrdinalIgnoreCase) > -1 && !string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["guid"]))
            {
                Entry entry = dataService.GetEntry(HttpContext.Current.Request.QueryString["guid"]);
                if (entry != null)
                {
                    metaTags = GetMetaTags(metaTags, entry);
                }
            }
            else if (currentUrl.IndexOf("commentview.aspx", StringComparison.OrdinalIgnoreCase) > -1 && !string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["title"]))
            {
                Entry entry = dataService.GetEntry(HttpContext.Current.Request.QueryString["title"]);
                if (entry != null)
                {
                    metaTags = GetMetaTags(metaTags, entry);
                }
            }
            else if (currentUrl.IndexOf("default.aspx", StringComparison.OrdinalIgnoreCase) > -1)
            {
                var smt = new SeoMetaTags();
                smt = smt.GetMetaTags();
                if (smt != null)
                {
                    if (!string.IsNullOrEmpty(smt.MetaDescription))
                    {
                        metaTags += string.Format(MetaDescriptionTagPattern, smt.MetaDescription);
                    }

                    if (!string.IsNullOrEmpty(smt.MetaKeywords))
                    {
                        metaTags += string.Format(MetaKeywordTagPattern, smt.MetaKeywords);
                    }
                }
                metaTags += string.Format(CanonicalLinkPattern, SiteUtilities.GetBaseUrl());
            }
            return metaTags;
        }
示例#38
0
        public void MaxResultsTest()
        {
            Entry entry1 = CreateEntry("public 2007.1", true, new DateTime(2007, 2, 2));
            Entry entry2 = CreateEntry("public 2006.1", true, new DateTime(2006, 2, 2));
            Entry entry3 = CreateEntry("not public 2006.1", false, new DateTime(2006, 2, 2));
            Entry entry4 = CreateEntry("public 2007.2", true, new DateTime(2007, 2, 2));
            Entry entry5 = CreateEntry("public 2006.2", true, new DateTime(2006, 2, 2));
            Entry entry6 = CreateEntry("not public 2006.2", false, new DateTime(2006, 2, 2));

            EntryCollection collection = new EntryCollection(new Entry[] { entry1, entry2, entry3, entry4, entry5, entry6 });

            Predicate<Entry> filter = null;

            Predicate<Entry> isPublic = delegate(Entry e)
            {
                return e.IsPublic;
            };

            filter += isPublic;

            Predicate<Entry> is2006Published = delegate(Entry e)
            {
                return e.CreatedLocalTime.Year == 2006;
            };

            filter += is2006Published;

            // 2 items match the criteria (2,5), we only want 1 returned
            EntryCollection filtered = EntryCollectionFilter.FindAll(collection, filter,1);

            Assert.AreEqual(1, filtered.Count, "Number of results doesn't match.");

            // no predicate so all results should be returend but we only want 4
            EntryCollection maxResults = EntryCollectionFilter.FindAll(collection, null, 4);

            Assert.AreEqual(4, maxResults.Count, "Number of results doesn't match.");

        }
示例#39
0
		internal void Load(DataManager data)
		{
			if ( Loaded ) 
			{
				return;
			}

			lock(entriesLock)
			{
				if ( Loaded ) //SDH: standard thread-safe double check
				{
					return;
				}
				
				string fullPath = data.ResolvePath(FileName);
				FileStream fileStream = FileUtils.OpenForRead(fullPath);
				if ( fileStream != null )
				{
					try
					{
						XmlSerializer ser = new XmlSerializer(typeof(DayEntry),Data.NamespaceURI);
						using (StreamReader reader = new StreamReader(fileStream))
						{
							//XmlNamespaceUpgradeReader upg = new XmlNamespaceUpgradeReader( reader, "", Data.NamespaceURI );
                            DayEntry e = (DayEntry)ser.Deserialize(reader);
							Entries = e.Entries;
						}
					}
					catch(Exception e)
					{
						ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error,e);
					}
					finally
					{
						fileStream.Close();
					}
				}

				Entries.Sort((left,right) => right.CreatedUtc.CompareTo(left.CreatedUtc));
			
				Loaded = true;
			}
		}
示例#40
0
		protected override EntryCollection LoadEntries()
		{
			if (WeblogEntryId.Length == 0) 
			{
				Response.StatusCode = 404;
				Response.SuppressContent = true;
				Response.End();
				return null; //save us all the time	
			}


			EntryCollection entryCollection = new EntryCollection();
			Entry entry = DataService.GetEntry(WeblogEntryId);
            ILoggingDataService logService = this.LoggingService;
			if (entry != null)
			{
				entryCollection.Add(entry);

				if (NotModified(entryCollection))
				{
					Response.End();
					return null;
				}
			}
			
			return entryCollection;
		}
示例#41
0
		public void GetAllUserEntries_GetSecondPageWithTenUsersWithVirtualListViewSupportEnabled_ReturnsSeracherWithVirtualListViewRangeSetToLoadElventhEntyPlusNineAfterThat() {
			var searcher = A.Fake<IDirectorySearcher>();

			var entryCollection = new EntryCollection(A.CollectionOfFake<IEntry>(1));
			A.CallTo(() => searcherFactory.CreateSearcher(A<IEntry>.Ignored, SearchScope.Subtree, ldapConfig.Users)).Returns(searcher);
			A.CallTo(() => searcher.FindAll()).Returns(entryCollection);
			A.CallTo(() => ldapConfig.Server.VirtualListViewSupport).Returns(true);

			int totalRecords;
			adapter.GetAllUserEntries(1, 10, out totalRecords);

			Assert.AreEqual(0, searcher.VirtualListView.BeforeCount);
			Assert.AreEqual(9, searcher.VirtualListView.AfterCount);
			Assert.AreEqual(11, searcher.VirtualListView.Offset);

		}
示例#42
0
        EntryCollection IBlogDataService.GetEntriesForUser(string user)
        {
            Predicate<Entry> entryCriteria = null;
            EntryCollection entries = new EntryCollection();
            entryCriteria += EntryCollectionFilter.DefaultFilters.IsFromUser(user);

            DayEntryCollection dayEntries = InternalGetDayEntries(null, int.MaxValue);

            foreach (DayEntry dayEntry in dayEntries)
            {
                foreach (Entry entry in dayEntry.GetEntries(entryCriteria))
                    entries.Add(entry);
            }

            return entries;
        }
示例#43
0
		public void GetAllUserEntries_GetTheSecondPageOfTenInACollectionOfHundred_ReturnsCorrectRange() {
			var searcher = A.Fake<IDirectorySearcher>();

			var entryCollection = new EntryCollection(A.CollectionOfFake<IEntry>(100));
			A.CallTo(() => searcherFactory.CreateSearcher(A<IEntry>.Ignored, SearchScope.Subtree, ldapConfig.Users)).Returns(searcher);
			A.CallTo(() => searcher.FindAll()).Returns(entryCollection);

			int totalRecords;
			var result = adapter.GetAllUserEntries(1, 10, out totalRecords);

			Assert.AreSame(entryCollection.ElementAt(10), result.First());
			Assert.AreSame(entryCollection.ElementAt(19), result.Last());
		}
示例#44
0
        /// <summary>
        /// Logs an error to the application memory.
        /// </summary>
        /// <remarks>
        /// If the log is full then the oldest error entry is removed.
        /// </remarks>
        public override string Log(Error error)
        {
            if (error == null)
                throw new ArgumentNullException("error");

            //
            // Make a copy of the error to log since the source is mutable.
            // Assign a new GUID and create an entry for the error.
            //

            error = (Error) ((ICloneable) error).Clone();
            error.ApplicationName = this.ApplicationName;
            Guid newId = Guid.NewGuid();
            ErrorLogEntry entry = new ErrorLogEntry(this, newId.ToString(), error);

            _lock.AcquireWriterLock(Timeout.Infinite);

            try
            {
                if (_entries == null)
                {
                    _entries = new EntryCollection(_size);
                }

                _entries.Add(entry);
            }
            finally
            {
                _lock.ReleaseWriterLock();
            }

            return newId.ToString();
        }
示例#45
0
		public void GetAllRoles_AddTwoRolesThatWillBeReturnedFromAdapter_ReturnsRoleSortedAlphabetical() {
			var roleEntries = new EntryCollection();
			var roleEntry1 = A.Fake<IEntry>();
			var roleEntry2 = A.Fake<IEntry>();
			A.CallTo(() => roleEntry1.Name).Returns("role z");
			A.CallTo(() => roleEntry2.Name).Returns("role a");
			roleEntries.Add(roleEntry1);
			roleEntries.Add(roleEntry2);

			A.CallTo(() => container.GroupEntryAdapter.GetAllRoleEntries()).Returns(roleEntries);
			A.CallTo(() => container.GroupEntryAdapter.GetGroupName(A<IEntry>.Ignored)).ReturnsLazily(c => c.GetArgument<IEntry>(0).Name);

			var result = provider.GetAllRoles();

			Assert.AreEqual("role a", result[0]);
			Assert.AreEqual("role z", result[1]);
		}
示例#46
0
		public void GetRolesForUser_UsersMembershipAttributeIsNotConfigured_RetrunsRolesFromAllRolesComparedToUsersRoles() {
			var roleEntries = new EntryCollection();
			var roleEntry = A.Fake<IEntry>();
			A.CallTo(() => roleEntry.Name).Returns("role");
			roleEntries.Add(roleEntry);
			A.CallTo(() => providerConfig.LdapConfig.Groups.MembershipAttribute).Returns("rdnattribute");
			A.CallTo(() => container.GroupEntryAdapter.GetGroupsWithEntryAsMemebership(A<IEntry>.Ignored)).Returns(roleEntries);
			A.CallTo(() => container.GroupEntryAdapter.GetGroupEntry("role", true)).Returns(roleEntry);
			A.CallTo(() => container.GroupEntryAdapter.GetGroupName(A<IEntry>.Ignored)).ReturnsLazily(c => c.GetArgument<IEntry>(0).Name);
			A.CallTo(() => container.UserEntryAdapter.GetUsersFromEntry(roleEntry, "rdnattribute")).Returns(new[]{ "username" });

			var result = provider.GetRolesForUser("username");

			Assert.AreEqual("role", result[0]);
		}
示例#47
0
        private bool Build(DataManager data)
        {

            EntryCollection entriesCacheCopy = new EntryCollection();

            Dictionary<string, DateTime> entryIdToDateCopy = new Dictionary<string, DateTime>(StringComparer.InvariantCultureIgnoreCase);
            Dictionary<string, DateTime> compressedTitleToDateCopy = new Dictionary<string, DateTime>(StringComparer.InvariantCultureIgnoreCase);

            try
            {
                foreach (DayEntry day in data.Days)
                {
                    day.Load(data);

                    foreach (Entry entry in day.Entries)
                    {

                        // create a lite entry for faster searching 
                        Entry copy = entry.Clone();
                        copy.Content = "";
                        copy.Description = "";

                        copy.AttachmentsArray = null;
                        copy.CrosspostArray = null;

                        entriesCacheCopy.Add(copy);

                        entryIdToDateCopy.Add(copy.EntryId, copy.CreatedUtc.Date);

                        //SDH: Only the first title is kept, in case of duplicates
                        // TODO: should be able to fix this, but it's a bunch of work.
                        string compressedTitle = copy.CompressedTitle;
                        compressedTitle = compressedTitle.Replace("+", "");
                        if (compressedTitleToDateCopy.ContainsKey(compressedTitle) == false)
                        {
                            compressedTitleToDateCopy.Add(compressedTitle, copy.CreatedUtc.Date);
                        }
                    }
                }
            }

                //TODO: SDH: Temporary, as sometimes we get collection was modified from the EntryCollection...why does this happen? "Database" corruption? 
            // Misaligned Entries?
            catch (InvalidOperationException) //something wrong enumerating the entries?
            {
                //set flags to start over to prevent getting stuck...
                booting = true;
                changeNumber = 0;
                throw;
            }

            //try to be a little more "Atomic" as others have been enumerating this list...
            entryIDToDate.Clear();
            entryIDToDate = entryIdToDateCopy;

            compressedTitleToDate.Clear();
            compressedTitleToDate = compressedTitleToDateCopy;

            entriesCache = entriesCacheCopy;

            changeNumber = data.CurrentEntryChangeCount;

            return true;
        }
示例#48
0
        public static DateTime GetLatestModifedEntryDateTime(IBlogDataService dataService, EntryCollection entries)
        {
            // Check to see if we should send a HTTP 304 letting the RSS client
            // know that they have the latest version of the feed
            DateTime latest = DateTime.MinValue;

            // need to check to see if the last entry value doesn't exist
            // if it doesn't loop through posts to get the latest date
            if (dataService.GetLastEntryUpdate() == DateTime.MinValue)
            {
                foreach (Entry entry in entries)
                {
                    DateTime created = entry.ModifiedLocalTime;
                    if (created > latest) latest = created;
                }
            }
            else
            {
                latest = dataService.GetLastEntryUpdate().ToLocalTime();
            }

            // we need to check to see if a comment entry has occured
            // after the last entry update. If it has don't return 304
            DateTime latestComment = dataService.GetLastCommentUpdate();
            if ( ( latestComment != DateTime.MinValue ) && ( latest < latestComment.ToLocalTime() ) )
                latest = latestComment.ToLocalTime();

            return new DateTime(latest.Year, latest.Month, latest.Day, latest.Hour, latest.Minute, latest.Second);
        }
示例#49
0
文件: Utils.cs 项目: AArnott/dasblog
 public static DateTime GetLatestModifedEntryDateTime(IBlogDataService dataService, EntryCollection entries)
 {
     return SiteUtilities.GetLatestModifedEntryDateTime(dataService, entries);
 }
示例#50
0
            public void MapEntryCollection()
            {
                var domainEntry1 = new Entry(
                              account: "account number 1",
                              amountIn: 1m,
                              amountOut: 2m,
                              bookingDate: new DateTime(2012, 1, 1),
                              currency: "EUR",
                              description: "my description",
                              payee: "the payee",
                              valueDate: new DateTime(2012, 1, 16)) { IsNew = true };

                var domainEntry2 = new Entry(
                              account: "account number 2",
                              amountIn: 3m,
                              amountOut: 4m,
                              bookingDate: new DateTime(2012, 1, 3),
                              currency: "USD",
                              description: "my other description",
                              payee: "the other payee",
                              valueDate: new DateTime(2012, 1, 17)) { IsNew = true };

                var collection = new EntryCollection
                           {
                             domainEntry1,
                             domainEntry2
                           };

                Gateways.Xml.XmlEntryCollection xmlCollection = this.mapper.MapToXml(collection);

                Assert.AreEqual(2, xmlCollection.Count);
                Assert.AreEqual("account number 1", xmlCollection[0].Account);
                Assert.AreEqual("account number 2", xmlCollection[1].Account);
            }
示例#51
0
        // TODO:  Consider refactoring to use InternalGetDayEntries that takes delegates.  It is slightly more
        // complicated because this method uses CategoryCache().
        EntryCollection IBlogDataService.GetEntriesForCategory(string categoryName, string acceptLanguages)
        {
            CategoryCache cache = new CategoryCache();
            cache.Ensure(data);

            EntryCollection entryList = new EntryCollection();
            Entry entry;

            if (cache.UrlSafeCategories.ContainsKey(categoryName))
            {
                categoryName = cache.UrlSafeCategories[categoryName];
            }

            CategoryCacheEntry catEntry = cache.Entries[categoryName];
            if (catEntry != null)
            {
                foreach (CategoryCacheEntryDetail detail in catEntry.EntryDetails)
                {
                    DayEntry day = data.Days[detail.DayDateUtc];
                    if (day != null)
                    {
                        Predicate<Entry> entryCriteria = null;

                        if (acceptLanguages != null && acceptLanguages.Length > 0)
                        {
                            entryCriteria += EntryCollectionFilter.DefaultFilters.IsInAcceptedLanguagesOrMultiLingual(acceptLanguages);
                        }


                        day.Load(data);
                        entry = day.GetEntries(entryCriteria)[detail.EntryId];
                        if (entry != null)
                        {
                            entryList.Add(entry);
                        }
                    }
                }
            }
            entryList.Sort((left, right) => right.CreatedUtc.CompareTo(left.CreatedUtc));
            return entryList;
        }
示例#52
0
		public void GetAllUserEntries_GetSecondPageWithTenUsersWithVirtualListViewSupportEnabled_ReturnsUnmodifedListFromSearcher() {
			var searcher = A.Fake<IDirectorySearcher>();

			var entryCollection = new EntryCollection(A.CollectionOfFake<IEntry>(100));
			A.CallTo(() => searcherFactory.CreateSearcher(A<IEntry>.Ignored, SearchScope.Subtree, ldapConfig.Users)).Returns(searcher);
			A.CallTo(() => searcher.FindAll()).Returns(entryCollection);
			A.CallTo(() => ldapConfig.Server.VirtualListViewSupport).Returns(true);

			int totalRecords;
			var result = adapter.GetAllUserEntries(1, 10, out totalRecords);

			CollectionAssert.AreEqual(entryCollection, result);
		}
示例#53
0
		public void GetAllUserEntries_PageSizeLessThanOne_ArgumentOutOfRangeException() {
			var searcher = A.Fake<IDirectorySearcher>();

			var entryCollection = new EntryCollection(A.CollectionOfFake<IEntry>(1));
			A.CallTo(() => searcherFactory.CreateSearcher(A<IEntry>.Ignored, SearchScope.Subtree, ldapConfig.Users)).Returns(searcher);
			A.CallTo(() => searcher.FindAll()).Returns(entryCollection);

			int totalRecords;
			Assert.Throws(	Is.TypeOf<ArgumentOutOfRangeException>().And.Property("ParamName").EqualTo("pageSize"),
							() => adapter.GetAllUserEntries(0, 0, out totalRecords));

		}
示例#54
0
		public void GetAllRoles_GetOneRoleEntriyFromAdapter_ReturnsRoleWithSameNameAsInAdapter() {
			var roleEntries = new EntryCollection();
			var roleEntry = A.Fake<IEntry>();
			A.CallTo(() => roleEntry.Name).Returns("role");
			roleEntries.Add(roleEntry);

			A.CallTo(() => container.GroupEntryAdapter.GetAllRoleEntries()).Returns(roleEntries);
			A.CallTo(() => container.GroupEntryAdapter.GetGroupName(A<IEntry>.Ignored)).ReturnsLazily(c => c.GetArgument<IEntry>(0).Name);

			var result = provider.GetAllRoles();

			Assert.AreEqual("role", result[0]);
		}
示例#55
0
		public void GetAllUserEntries_SearcherReturnsNoEntries_ReturnsEmptyArray() {
			var searcher = A.Fake<IDirectorySearcher>();

			var entryCollection = new EntryCollection();
			A.CallTo(() => searcherFactory.CreateSearcher(A<IEntry>.Ignored, SearchScope.Subtree, ldapConfig.Users)).Returns(searcher);
			A.CallTo(() => searcher.FindAll()).Returns(entryCollection);

			int totalRecords;
			var result = adapter.GetAllUserEntries(0, 1, out totalRecords);

			CollectionAssert.IsEmpty(result);
		}
示例#56
0
		public void GetUsersInRole_NoRangeRetrievalSupportSoGetUserEntriesFromGroupMembershipAttribute_ReturnUserInRole() {
			var roleEntries = new EntryCollection();
			var roleEntry = A.Fake<IEntry>();
			A.CallTo(() => roleEntry.Name).Returns("role");
			roleEntries.Add(roleEntry);

			A.CallTo(() => providerConfig.LdapConfig.Groups.MembershipAttribute).Returns("rdnattribute");
			A.CallTo(() => container.GroupEntryAdapter.GetGroupEntry("role", true)).Returns(roleEntry);
			A.CallTo(() => container.GroupEntryAdapter.GetGroupName(A<IEntry>.Ignored)).ReturnsLazily(c => c.GetArgument<IEntry>(0).Name);
			A.CallTo(() => container.UserEntryAdapter.GetUsersFromEntry(roleEntry, "rdnattribute")).Returns(new[]{ "username" });

			var result = provider.GetUsersInRole("role");

			Assert.AreEqual("username", result[0]);			
		}
示例#57
0
		public void GetAllUserEntries_GetACollectionOfHundred_ReturnsHundredTotalRecors() {
			var searcher = A.Fake<IDirectorySearcher>();

			var entryCollection = new EntryCollection(A.CollectionOfFake<IEntry>(100));
			A.CallTo(() => searcherFactory.CreateSearcher(A<IEntry>.Ignored, SearchScope.Subtree, ldapConfig.Users)).Returns(searcher);
			A.CallTo(() => searcher.FindAll()).Returns(entryCollection);

			int totalRecords;
			adapter.GetAllUserEntries(0, 1, out totalRecords);

			Assert.AreEqual(100, totalRecords);
		}
示例#58
0
		public void GetRolesForUser_AddTwoRoles_ReturnRolesSortedAlphabetial() {
			var roleEntries = new EntryCollection();
			var roleEntry1 = A.Fake<IEntry>();
			var roleEntry2 = A.Fake<IEntry>();
			A.CallTo(() => roleEntry1.Name).Returns("role z");
			A.CallTo(() => roleEntry2.Name).Returns("role a");
			roleEntries.Add(roleEntry1);
			roleEntries.Add(roleEntry2);
			A.CallTo(() => providerConfig.LdapConfig.Groups.MembershipAttribute).Returns("rdnattribute");
			A.CallTo(() => container.GroupEntryAdapter.GetGroupsWithEntryAsMemebership(A<IEntry>.Ignored)).Returns(roleEntries);
			A.CallTo(() => container.GroupEntryAdapter.GetGroupEntry("role z", true)).Returns(roleEntry1);
			A.CallTo(() => container.GroupEntryAdapter.GetGroupEntry("role a", true)).Returns(roleEntry2);
			A.CallTo(() => container.GroupEntryAdapter.GetGroupName(A<IEntry>.Ignored)).ReturnsLazily(c => c.GetArgument<IEntry>(0).Name);
			A.CallTo(() => container.UserEntryAdapter.GetUsersFromEntry(A<IEntry>.Ignored, "rdnattribute")).Returns(new[]{ "username" });

			var result = provider.GetRolesForUser("username");

			Assert.AreEqual("role a", result[0]);
			Assert.AreEqual("role z", result[1]);
		}
示例#59
0
		public void GetAllUserEntries_GetAllUsersWithVirtualListViewSupportEnabled_ReturnsTotalRecordsFromVirtualListView() {
			var searcher = A.Fake<IDirectorySearcher>();

			var entryCollection = new EntryCollection(A.CollectionOfFake<IEntry>(1));
			A.CallTo(() => searcherFactory.CreateSearcher(A<IEntry>.Ignored, SearchScope.Subtree, ldapConfig.Users)).Returns(searcher);
			A.CallTo(() => searcher.FindAll()).Returns(entryCollection);
			A.CallTo(() => ldapConfig.Server.VirtualListViewSupport).Returns(true);
			adapter.VirtualListViewTotalCount = 100;

			int totalRecords;
			adapter.GetAllUserEntries(1, 10, out totalRecords);

			Assert.AreEqual(100, totalRecords);
		}
示例#60
0
        /// <summary>
        /// Returns an EntryCollection whose entries all fit the criteria
        /// specified by include.
        /// </summary>
        /// <param name="dayEntryCriteria">A delegate that specifies which days should be included.</param>
        /// <param name="entryCriteria">A delegate that specifies which entries should be included.</param>
        /// <param name="maxDays">The maximum number of days to include.</param>
        /// <param name="maxEntries">The maximum number of entries to return.</param>
        /// <returns></returns>
        public EntryCollection /*IBlogDataService*/ GetEntries(
            Predicate<DayEntry> dayEntryCriteria,
            Predicate<Entry> entryCriteria,
            int maxDays, int maxEntries)
        {
            EntryCollection entries = new EntryCollection();
            DayEntryCollection days = this.InternalGetDayEntries(dayEntryCriteria, maxDays);
            int entryCount = 0;

            foreach (DayEntry day in days)
            {
                day.Load(data);

                foreach (Entry entry in day.GetEntries(entryCriteria))
                {
                    if (entryCount < maxEntries)
                    {
                        entries.Add(entry);
                        entryCount++;
                    }
                    else
                    {
                        break;
                    }
                }
                if (entryCount >= maxEntries)
                {
                    break;
                }
            }
            return entries;
        }