public string[] GenerateSql(IStructureSchema structureSchema, IndexesTableNames names, IndexesTableStatuses statuses)
		{
			if(statuses.AllExists)
				return new string[0];

			var structureTableName = structureSchema.GetStructureTableName();
			var sqlTemplateNameSuffix = GetSqlTemplateNameSuffix(structureSchema.IdAccessor.IdType);
			var generators = new Func<string>[]
			{
				() => !statuses.IntegersTableExists 
					? GenerateSqlFor("CreateIntegersIndexes", sqlTemplateNameSuffix, structureTableName, names.IntegersTableName) 
					: string.Empty,
				() => !statuses.FractalsTableExists 
					? GenerateSqlFor("CreateFractalsIndexes", sqlTemplateNameSuffix, structureTableName, names.FractalsTableName) 
					: string.Empty,
				() => !statuses.BooleansTableExists 
					? GenerateSqlFor("CreateBooleansIndexes", sqlTemplateNameSuffix, structureTableName, names.BooleansTableName) 
					: string.Empty,
				() => !statuses.DatesTableExists 
					? GenerateSqlFor("CreateDatesIndexes", sqlTemplateNameSuffix, structureTableName, names.DatesTableName) 
					: string.Empty,
				() => !statuses.GuidsTableExists 
					? GenerateSqlFor("CreateGuidsIndexes", sqlTemplateNameSuffix, structureTableName, names.GuidsTableName) 
					: string.Empty,
				() => !statuses.StringsTableExists 
					? GenerateSqlFor("CreateStringsIndexes", sqlTemplateNameSuffix, structureTableName, names.StringsTableName) 
					: string.Empty,
				() => !statuses.TextsTableExists 
					? GenerateSqlFor("CreateTextsIndexes", sqlTemplateNameSuffix, structureTableName, names.TextsTableName) 
					: string.Empty
			};

			return generators.Select(generator => generator()).Where(s => !string.IsNullOrWhiteSpace(s)).ToArray();
		}
Example #2
0
        public static void Cozy()
        {
            Console.WriteLine("\n-----------------------------------------------");
            Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName);
            Console.WriteLine("-----------------------------------------------");

            //匿名类在使用linq做数据处理的时候非常有用

            //例如有一个Model类型是和数据库某张表的结构完全一致,但在UI上面需要呈现的数据不需要那么多
            //或者需要两个字段拼接成一个绑定UI上面,匿名类的用处就体现出来了

            //创建一个List<Model>的数据源
            var dataSource = new Func<List<Model>>(() =>
            {
                return Enumerable.Range(0, 20).Select(x => new Model
                {
                    Id = x,
                    FirstName = string.Format("FirstName{0}", x),
                    LastName = string.Format("LastName{0}", x)
                }).ToList();
            })();

            //通过Select()返回一个List<AnonymousType>对象,打印出来
            dataSource.Select(x => new {Number = x.Id, Name = x.FirstName + x.LastName , 年龄 = x.Age}).ToList().ForEach(x =>            
                Console.WriteLine("编号:{0} \t姓名:{1}  \t年龄:{2}", x.Number, x.Name, x.年龄));
        }
Example #3
0
        public override object CalculateResult()
        {
            var operations = new Func<Fraction, Fraction, Fraction>[]
            {
                (a, b) => a + b,
                (a, b) => a - b,
                (a, b) => a * b,
                (a, b) => a / b,
            };

            return new Range(1, 9, true)
                .GetCombinations(4)
                .Select(digits => digits
                    .GetPermutations()
                    .Select(p => new
                    {
                        a = p[0],
                        b = p[1],
                        c = p[2],
                        d = p[3],
                    })
                    .SelectMany(p => new Range(3)
                        .Aggregate(new[] { Enumerable.Empty<Func<Fraction, Fraction, Fraction>>() }.AsEnumerable(),
                            (a, i) =>
                                a.SelectMany(s => operations
                                    .Select(o => s.AppendItem(o))),
                            a => a
                                .Select(s => s
                                    .ToArray())
                                .ToArray())
                        .Select(o => new
                        {
                            x = o[0],
                            y = o[1],
                            z = o[2],
                        })
                        .SelectMany(o => new[]
                        {
                            o.x(o.y(o.z(p.a, p.b), p.c), p.d),
                            o.x(o.y(p.a, p.b), o.z(p.c, p.d)),
                            o.x(o.y(p.a, o.z(p.b, p.c)), p.d),
                            o.x(p.a, o.y(o.z(p.b, p.c), p.d)),
                            o.x(p.a, o.y(p.b, o.z(p.c, p.d)))
                        }))
                    .Let(r => new
                    {
                        Digits = digits,
                        Count = r
                            .Where(v => v > 0 && v.IsInteger)
                            .Distinct()
                            .OrderBy(v => v)
                            .ToMemorableEnumerable()
                            .TakeWhile(e => !e.HasPreviousValue || e.Value == e.PreviousValue + 1)
                            .Count()
                    }))
                .WithMax(x => x.Count)
                .Digits
                .StringJoin("");
        }
Example #4
0
        public static void NounsSearch()
        {
            var voc = Program.DefaultVocabulary;
            var mainWords = voc.GetAllInfos().Where(s => s.PartOfSpeach == "V").Select(s=> s.Stem);
            var searcher = new Symptoms(voc, mainWords, "S");

            var questionList = Program.DefaultQuestionList;

            var symptoms = new Func<List<InvertedIndexUnit>>(()=> searcher
                .GetSymptomsIndex(questionList.GetAllQuestions().Select(item => Tuple.Create(item.Id, item.WholeText)))
                .ToList()).DetectTime("nouns found");
            File.WriteAllLines("nouns_verbs.txt", symptoms.Select(s => s.ToStringCount()));
        }
Example #5
0
        /// <summary>
        /// Class constructor.
        /// </summary>
        static JsonReaderUtils()
        {
            var readSizes = new int[][]
            {
                new int[] { Int32.MaxValue },
                new int[] { 1 },
                new int[] { 1, 7, 101 }
            };

            Func<TextReader, AssertionHandler, JsonReader>[] creatorFuncs = new Func<TextReader, AssertionHandler, JsonReader>[]
            {
                (textReader, assert) => new JsonReader(textReader, assert, ODataFormat.Json, isIeee754Compatible: true),
                (textReader, assert) => new BufferingJsonReader(textReader, ODataConstants.DefaultMaxRecursionDepth, assert, ODataFormat.Json, isIeee754Compatible: true),
                (textReader, assert) => 
                {
                    BufferingJsonReader reader = new BufferingJsonReader(textReader, ODataConstants.DefaultMaxRecursionDepth, assert, ODataFormat.Json, isIeee754Compatible: true);
                    reader.StartBuffering();
                    return reader;
                },
            };

            allTestConfigurations = readSizes.SelectMany(rs =>
                creatorFuncs.Select(f => new JsonReaderTestConfiguration { ReadSizes = rs, JsonReaderCreatorFunc = f }));
        }
        public static bool IsConform(IEquationBuilder subject)
        {
            var callingTests = new Action<IEquationBuilder>[] {
                s => s.Value(0),
                s => s.Literal("x"),
                s => s.Add(),
                s => s.Divide(),
                s => s.Divide(b => { }),
                s => s.Parentheses(b => { })
            };

            Func<Action<IEquationBuilder>, bool> callingTestWrapper = test => {
                var passed = true;
                try
                {
                    test(subject);
                }
                catch (RuntimeBinderException)
                {
                    passed = false;
                }
                return passed;
            };

            var searchingTest = new Func<IEquationBuilder, MethodInfo>[]
                {
                    s => s.GetType().GetMethod("CreateItem", new Type[] { typeof(IIdentifier) }),
                    s => s.GetType().GetMethod("CreateItem", new Type[] { typeof(IIdentifier), typeof(IItem).MakeByRefType() })
                };

            Func<Func<IEquationBuilder, MethodInfo>, bool> searchingTestWrapper = test => test(subject) != null;

            return callingTests.Select(callingTestWrapper)
                .Concat(searchingTest.Select(searchingTestWrapper))
                .All(result => result == true);
        }
        // [ConditionalFact] Currently disabled due to GitHub issue #266
        public async Task Can_use_sequence_end_to_end_from_multiple_contexts_concurrently_async()
        {
            var serviceProvider = new ServiceCollection()
                .AddEntityFrameworkSqlServer()
                .BuildServiceProvider();

            using (var context = new BronieContext(serviceProvider, "ManyBronies"))
            {
                context.Database.EnsureDeleted();
                context.Database.EnsureCreated();
            }

            const int threadCount = 50;

            var tests = new Func<Task>[threadCount];
            for (var i = 0; i < threadCount; i++)
            {
                var closureProvider = serviceProvider;
                tests[i] = () => AddEntitiesAsync(closureProvider, "ManyBronies");
            }

            var tasks = tests.Select(Task.Run).ToArray();

            foreach (var t in tasks)
            {
                await t;
            }

            using (var context = new BronieContext(serviceProvider, "ManyBronies"))
            {
                var pegasuses = await context.Pegasuses.ToListAsync();

                for (var i = 0; i < 50; i++)
                {
                    Assert.Equal(threadCount, pegasuses.Count(p => p.Name == "Rainbow Dash " + i));
                    Assert.Equal(threadCount, pegasuses.Count(p => p.Name == "Fluttershy " + i));
                }
            }
        }
        public async Task Multiple_threads_can_use_the_same_generator_async()
        {
            var configMock = new Mock<DbContextConfiguration>();
            configMock.Setup(m => m.Connection).Returns(new Mock<RelationalConnection>().Object);

            var entryMock = new Mock<StateEntry>();
            entryMock.Setup(m => m.Configuration).Returns(configMock.Object);

            var executor = new FakeSqlStatementExecutor(10);
            var generator = new SqlServerSequenceValueGenerator(executor, "Foo", 10);

            const int threadCount = 50;
            const int valueCount = 35;

            var tests = new Func<Task>[threadCount];
            var generatedValues = new List<long>[threadCount];
            for (var i = 0; i < tests.Length; i++)
            {
                var testNumber = i;
                generatedValues[testNumber] = new List<long>();
                tests[testNumber] = async () =>
                    {
                        for (var j = 0; j < valueCount; j++)
                        {
                            generatedValues[testNumber].Add((long)await generator.NextAsync(entryMock.Object, CreateProperty(typeof(long))));
                        }
                    };
            }

            var tasks = tests.Select(Task.Run).ToArray();

            foreach (var t in tasks)
            {
                await t;
            }

            // Check that each value was generated once and only once
            var checks = new bool[threadCount * valueCount];
            foreach (var values in generatedValues)
            {
                Assert.Equal(valueCount, values.Count);
                foreach (var value in values)
                {
                    checks[value] = true;
                }
            }

            Assert.True(checks.All(c => c));
        }
Example #9
0
        private bool TryDetectFramework(string content, PathType pathType, ChutzpahTestSettingsFile chutzpahTestSettings, out IFrameworkDefinition definition)
        {
            var strategies = new Func<IFrameworkDefinition>[]
            {
                // Check chutzpah settings
                () => frameworkDefinitions.FirstOrDefault(x => x.FrameworkKey.Equals(chutzpahTestSettings.Framework, StringComparison.OrdinalIgnoreCase)),

                // Check if we see an explicit reference to a framework file (e.g. <reference path="qunit.js" />)
                () => frameworkDefinitions.FirstOrDefault(x => x.FileUsesFramework(content, false, pathType)),

                // Check using basic heuristic like looking for test( or module( for QUnit
                () => frameworkDefinitions.FirstOrDefault(x => x.FileUsesFramework(content, true, pathType))
            };

            definition = strategies.Select(x => x()).FirstOrDefault(x => x != null);
            return definition != null;
        }
        public void AtomResourceCollectionMetadataTest()
        {
            var testCases = new[]
            {
                // No title specified - an empty one is used as it's required by the spec.
                new
                {
                    CustomizeMetadata = (Action<ODataEntitySetInfo>)(collection => {
                        AtomResourceCollectionMetadata metadata = collection.Atom();
                    }),
                    Xml = "<Collection><title xmlns='http://www.w3.org/2005/Atom'/></Collection>"
                },
                // Simple title (other titles are tested in AtomTextConstructMetadataTests)
                new
                {
                    CustomizeMetadata = (Action<ODataEntitySetInfo>)(collection => {
                        AtomResourceCollectionMetadata metadata = collection.Atom();
                        metadata.Title = new AtomTextConstruct { Text = "collection title" };
                    }),
                    Xml = "<Collection><title type='text' xmlns='http://www.w3.org/2005/Atom'>collection title</title></Collection>"
                },
                // With accept
                new
                {
                    CustomizeMetadata = (Action<ODataEntitySetInfo>)(collection => {
                        AtomResourceCollectionMetadata metadata = collection.Atom();
                        metadata.Title = "collection title";
                        metadata.Accept = "mime/type";
                    }),
                    Xml = "<Collection><title type='text' xmlns='http://www.w3.org/2005/Atom'>collection title</title><accept xmlns='http://www.w3.org/2007/app'>mime/type</accept></Collection>"
                },
                // With empty accept
                new
                {
                    CustomizeMetadata = (Action<ODataEntitySetInfo>)(collection => {
                        AtomResourceCollectionMetadata metadata = collection.Atom();
                        metadata.Title = "collection title";
                        metadata.Accept = string.Empty;
                    }),
                    Xml = "<Collection><title type='text' xmlns='http://www.w3.org/2005/Atom'>collection title</title><accept xmlns='http://www.w3.org/2007/app'></accept></Collection>"
                },
                // With categories
                new
                {
                    CustomizeMetadata = (Action<ODataEntitySetInfo>)(collection => {
                        AtomResourceCollectionMetadata metadata = collection.Atom();
                        metadata.Title = "collection title";
                        metadata.Categories = new AtomCategoriesMetadata();
                    }),
                    Xml = "<Collection><title type='text' xmlns='http://www.w3.org/2005/Atom'>collection title</title><categories xmlns='http://www.w3.org/2007/app' /></Collection>"
                },
                // With accept and categories
                new
                {
                    CustomizeMetadata = (Action<ODataEntitySetInfo>)(collection => {
                        AtomResourceCollectionMetadata metadata = collection.Atom();
                        metadata.Title = "collection title";
                        metadata.Accept = "mime/type";
                        metadata.Categories = new AtomCategoriesMetadata();
                    }),
                    Xml = "<Collection><title type='text' xmlns='http://www.w3.org/2005/Atom'>collection title</title><accept xmlns='http://www.w3.org/2007/app'>mime/type</accept><categories xmlns='http://www.w3.org/2007/app' /></Collection>"
                },
            };

            Func<ODataEntitySetInfo>[] collectionCreators = new Func<ODataEntitySetInfo>[]
            {
                () => new ODataEntitySetInfo { Url = new Uri("http://odata.org/url") },
                () => { var collection = new ODataEntitySetInfo { Url = new Uri("http://odata.org/url") }; collection.SetAnnotation(new AtomResourceCollectionMetadata()); return collection; }
            };
            var testDescriptors = testCases.SelectMany(testCase =>
                collectionCreators.Select(collectionCreator =>
                {
                    ODataEntitySetInfo collection = collectionCreator();
                    testCase.CustomizeMetadata(collection);
                    ODataServiceDocument serviceDocument = new ODataServiceDocument { EntitySets = new[] { collection } };
                    return new PayloadWriterTestDescriptor<ODataServiceDocument>(
                        this.Settings,
                        new[] { serviceDocument },
                        tc => new AtomWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                        {
                            Xml = testCase.Xml,
                            FragmentExtractor = result =>
                                new XElement("Collection",
                                    result
                                        .Element(TestAtomConstants.AtomPublishingXNamespace + TestAtomConstants.AtomPublishingWorkspaceElementName)
                                        .Element(TestAtomConstants.AtomPublishingXNamespace + TestAtomConstants.AtomPublishingCollectionElementName)
                                        .Elements())
                        });
                }));

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.WriterTestConfigurationProvider.AtomFormatConfigurations.Where(tc => !tc.IsRequest),
                (testDescriptor, testConfiguration) =>
                {
                    testConfiguration = testConfiguration.Clone();
                    testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                    TestWriterUtils.WriteAndVerifyTopLevelContent(
                        testDescriptor,
                        testConfiguration,
                        (messageWriter) => messageWriter.WriteServiceDocument(testDescriptor.PayloadItems.Single()),
                        this.Assert,
                        baselineLogger: this.Logger);
                });
        }
Example #11
0
        /// <summary>
        /// Look for Visual Studio
        /// </summary>
        /// <param name="runningInVisualStudio">True if running in Visual Studio</param>
        /// <returns>Path to Visual Studio install root.</returns>
        private static string GetVisualStudioPath(out bool runningInVisualStudio)
        {
            var processNameCommandLine = s_getProcessFromCommandLine();
            var processNameCurrentProcess = s_getProcessFromRunningProcess();

            // Check to see if we're running inside of Visual Studio
            runningInVisualStudio = IsProcessInList(processNameCommandLine, s_visualStudioProcess) ||
                                    IsProcessInList(processNameCurrentProcess, s_visualStudioProcess);

            // Define the order in which we will look for Visual Studio. Stop when the first instance
            // is found.
            var possibleLocations = new Func<string>[]
            {
                () => TryGetVsFromProcess(processNameCommandLine),
                () => TryGetVsFromProcess(processNameCurrentProcess),
                () => TryGetVsFromEnvironment(),
                () => TryGetVsFromInstalled(),
                () => TryGetVsFromMSBuildLocation(processNameCommandLine),
                () => TryGetVsFromMSBuildLocation(processNameCurrentProcess)
            };

            return possibleLocations.Select(location => location()).FirstOrDefault(path => !string.IsNullOrEmpty(path));
        }
        private bool TryDetectFramework(PathInfo path, ChutzpahTestSettingsFile chutzpahTestSettings, out IFrameworkDefinition definition)
        {
            // TODO: Deprecate the fallback approach
            Lazy<string> fileText = new Lazy<string>(() =>
            {
                string firstTestFileText;
                if (path.Type == PathType.Url)
                {
                    firstTestFileText = httpClient.GetContent(path.FullPath);
                }
                else
                {
                    firstTestFileText = fileSystem.GetText(path.FullPath);
                }

                return firstTestFileText;
            });


            var strategies = new Func<IFrameworkDefinition>[]
            {
                // Check chutzpah settings
                () => frameworkDefinitions.FirstOrDefault(x => x.FrameworkKey.Equals(chutzpahTestSettings.Framework, StringComparison.OrdinalIgnoreCase)),

                // Check if we see an explicit reference to a framework file (e.g. <reference path="qunit.js" />)
                () => frameworkDefinitions.FirstOrDefault(x => x.FileUsesFramework(fileText.Value, false, path.Type)),

                // Check using basic heuristic like looking for test( or module( for QUnit
                () => frameworkDefinitions.FirstOrDefault(x => x.FileUsesFramework(fileText.Value, true, path.Type))
            };

            definition = strategies.Select(x => x()).FirstOrDefault(x => x != null);
            return definition != null;
        }
Example #13
0
 private static IEnumerable<string> CreateTokensIterator(TextReader self, TextReaderRocksOptions options, Func<char?, char, bool>[] categories)
 {
     try {
         var cats = categories.Select (
                 c => Lambda.F ((StringBuilder buf, char ch) =>
                     c (buf.Length == 0 ? ((char?) null) : (char?) buf [buf.Length-1], ch)));
         foreach (var t in Chars (self).Tokens (
                     new StringBuilder (),
                     (buf, c) => buf.Append (c),
                     buf => {
                         var r = buf.ToString ();
                         buf.Length = 0;
                         return Tuple.Create (r, buf);
                     },
                     cats.ToArray ()))
             yield return t;
     } finally {
         if ((options & TextReaderRocksOptions.CloseReader) != 0) {
             self.Close ();
             self.Dispose ();
         }
     }
 }
Example #14
0
		private Func<Task> createMultiTask(Func<Task>[] taskRunners)
		{
			return () =>
			{
				var tasks = taskRunners.Select(fn => fn());
				return Task.WhenAll(tasks);
			};
		}
Example #15
0
 /// <summary>
 /// 引数に指定された基底と重みの線形結合を取る。
 /// </summary>
 public static Func<double, double> LinearCombination(Func<double, double>[] basis, double[] weights)
 {
     Debug.Assert(basis.Length == weights.Length, "There are not enough basis or weights for linear combination!");
     return x => basis.Select((b, i) => weights[i] * b(x)).Sum();
 }
        public void EntryMetadataWriterTest()
        {
            const string testPublished = "2010-10-20T20:10:00Z";
            AtomTextConstruct testRights = new AtomTextConstruct { Text = "Copyright Data Fx team." };
            AtomTextConstruct testSummary = new AtomTextConstruct { Text = "Test summary." };
            AtomTextConstruct testTitle = new AtomTextConstruct { Text = "Test title" };
            const string testUpdated = "2010-11-01T00:04:00Z";
            const string testIcon = "http://odata.org/icon";
            const string testSourceId = "http://odata.org/id/random";
            const string testLogo = "http://odata.org/logo";
            AtomTextConstruct testSubtitle = new AtomTextConstruct { Text = "Test subtitle." };

            const string testAuthorName = "Test Author 1";
            const string testAuthorEmail = "[email protected]";
            const string testAuthorUri = "http://odata.org/authors/1";

            var testAuthors = new AtomPersonMetadata[]
                {
                    new AtomPersonMetadata()
                    {
                        Email = testAuthorEmail,
                        Name = testAuthorName,
                        Uri = new Uri(testAuthorUri)
                    }
                };

            var testAuthors2 = new AtomPersonMetadata[0];

            const string testCategoryTerm = "Test category 1 term";
            const string testCategoryLabel = "Test category 1 label";
            const string testCategoryScheme = "http://odata.org/categories/1";

            var testCategories = new AtomCategoryMetadata[]
                {
                    new AtomCategoryMetadata()
                    {
                        Term = testCategoryTerm,
                        Label = testCategoryLabel,
                        Scheme = testCategoryScheme
                    }
                };

            const string testContributorName = "Test Contributor 1";
            const string testContributorEmail = "[email protected]";
            const string testContributorUri = "http://odata.org/contributors/1";

            var testContributors = new AtomPersonMetadata[]
                {
                    new AtomPersonMetadata()
                    {
                        Email = testContributorEmail,
                        Name = testContributorName,
                        Uri = new Uri(testContributorUri)
                    }
                };

            const string testGeneratorName = "Test generator";
            const string testGeneratorUri = "http://odata.org/generator";
            const string testGeneratorVersion = "3.0";

            var testGenerator = new AtomGeneratorMetadata()
                {
                    Name = testGeneratorName,
                    Uri = new Uri(testGeneratorUri),
                    Version = testGeneratorVersion
                };

            const string testLinkRelation = "http://odata.org/links/1";
            const string testLinkTitle = "Test link 1";
            const string testLinkHref = "http://odata.org/links/1";
            const string testLinkHrefLang = "de-AT";
            int? testLinkLength = 999;
            const string testLinkMediaType = "image/png";

            var testLinks = new AtomLinkMetadata[] 
                {
                    new AtomLinkMetadata()
                    {
                        Relation = testLinkRelation,
                        Title = testLinkTitle,
                        Href = new Uri(testLinkHref),
                        HrefLang = testLinkHrefLang,
                        Length = testLinkLength,
                        MediaType = testLinkMediaType
                    }
                };

            AtomFeedMetadata testSource = new AtomFeedMetadata()
            {
                Authors = testAuthors,
                Categories = testCategories,
                Contributors = testContributors,
                Generator = testGenerator,
                Icon = new Uri(testIcon),
                SourceId = new Uri(testSourceId),
                Links = testLinks,
                Logo = new Uri(testLogo),
                Rights = testRights,
                Subtitle = testSubtitle,
                Title = testTitle,
                Updated = DateTimeOffset.Parse(testUpdated)
            };

            Func<string, Func<XElement, XElement>> fragmentExtractor = (localName) => (e) => e.Element(TestAtomConstants.AtomXNamespace + localName);

            // TODO, ckerer: specify an Id via metadata if the entry does not specify one; we first have to decide what rules
            //               we want to apply to merging of metadata and ODataLib OM data.
            var testCases = new[] {
                new { // specify an author via metadata
                    CustomizeMetadata = new Action<AtomEntryMetadata>(metadata => metadata.Authors = testAuthors),
                    Xml = string.Join(
                        "$(NL)",
                        @"<author xmlns=""" + TestAtomConstants.AtomNamespace + @""">",
                        @"  <name>" + testAuthorName + @"</name>",
                        @"  <uri>" + testAuthorUri + @"</uri>",
                        @"  <email>" + testAuthorEmail + @"</email>",
                        @"</author>"),
                    Extractor = fragmentExtractor(TestAtomConstants.AtomAuthorElementName)
                },
                new { // specify an empty author array via metadata
                    CustomizeMetadata = new Action<AtomEntryMetadata>(metadata => metadata.Authors = testAuthors2),
                    Xml = string.Join(
                        "$(NL)",
                        @"<author xmlns=""" + TestAtomConstants.AtomNamespace + @""">",
                        @"  <name />",
                        @"</author>"),
                    Extractor = fragmentExtractor(TestAtomConstants.AtomAuthorElementName)
                },
                new { // specify no authors via metadata
                    CustomizeMetadata = new Action<AtomEntryMetadata>(metadata => metadata.Authors = null),
                    Xml = string.Join(
                        "$(NL)",
                        @"<author xmlns=""" + TestAtomConstants.AtomNamespace + @""">",
                        @"$(Indent)<name />",
                        @"</author>"),
                    Extractor = fragmentExtractor(TestAtomConstants.AtomAuthorElementName)
                },
                new { // specify a category via metadata
                    CustomizeMetadata = new Action<AtomEntryMetadata>(metadata => metadata.Categories = testCategories),
                    Xml = @"<category term=""" + testCategoryTerm + @""" scheme=""" + testCategoryScheme + @""" label=""" + testCategoryLabel + @""" xmlns=""" + TestAtomConstants.AtomNamespace + @""" />",
                    Extractor = fragmentExtractor(TestAtomConstants.AtomCategoryElementName)
                },
                new { // specify a contributor via metadata
                    CustomizeMetadata = new Action<AtomEntryMetadata>(metadata => metadata.Contributors = testContributors),
                    Xml = string.Join(
                        "$(NL)",
                        @"<contributor xmlns=""" + TestAtomConstants.AtomNamespace + @""">",
                        @"  <name>" + testContributorName + @"</name>",
                        @"  <uri>" + testContributorUri + @"</uri>",
                        @"  <email>" + testContributorEmail + @"</email>",
                        @"</contributor>"),
                    Extractor = fragmentExtractor(TestAtomConstants.AtomContributorElementName)
                },
                new { // specify a link via metadata
                    CustomizeMetadata = new Action<AtomEntryMetadata>(metadata => metadata.Links = testLinks),
                    Xml = @"<link rel=""" + testLinkRelation + @""" type = """ + testLinkMediaType + @""" title=""" + testLinkTitle + @""" href=""" + testLinkHref + @""" hreflang=""" + testLinkHrefLang + @""" length=""" + testLinkLength + @"""  xmlns=""" + TestAtomConstants.AtomNamespace + @"""/>",
                    Extractor = new Func<XElement, XElement>(
                            (e) => e.Elements(TestAtomConstants.AtomXNamespace + TestAtomConstants.AtomLinkElementName)
                                    .Where(l => l.Attribute(TestAtomConstants.AtomLinkRelationAttributeName).Value != TestAtomConstants.AtomSelfRelationAttributeValue)
                                    .Single())
                },
                new { // specify a published date via metadata
                    CustomizeMetadata = new Action<AtomEntryMetadata>(metadata => metadata.Published = DateTimeOffset.Parse(testPublished)),
                    Xml = @"<published xmlns=""" + TestAtomConstants.AtomNamespace + @""">" + testPublished + @"</published>",
                    Extractor = fragmentExtractor(TestAtomConstants.AtomPublishedElementName)
                },
                new { // specify rights via metadata
                    CustomizeMetadata = new Action<AtomEntryMetadata>(metadata => metadata.Rights = testRights),
                    Xml = @"<rights type=""text"" xmlns=""" + TestAtomConstants.AtomNamespace + @""">" + testRights.Text + @"</rights>",
                    Extractor = fragmentExtractor(TestAtomConstants.AtomRightsElementName)
                },
                new { // specify a source via metadata
                    CustomizeMetadata = new Action<AtomEntryMetadata>(metadata => metadata.Source = testSource),
                    Xml = string.Join(
                        "$(NL)",
                        @"<source xmlns=""" + TestAtomConstants.AtomNamespace + @""">",
                        @"  <id>" + testSourceId + "</id>",
                        @"  <title type=""text"">" + testTitle.Text + @"</title>",
                        @"  <subtitle type=""text"">" + testSubtitle.Text + @"</subtitle>",
                        @"  <updated>" + testUpdated + @"</updated>",
                        @"  <link rel=""" + testLinkRelation + @""" type = """ + testLinkMediaType + @""" title=""" + testLinkTitle + @""" href=""" + testLinkHref + @""" hreflang=""" + testLinkHrefLang + @""" length=""" + testLinkLength + @"""/>",
                        @"  <category term=""" + testCategoryTerm + @""" scheme=""" + testCategoryScheme + @""" label=""" + testCategoryLabel + @""" />",
                        @"  <logo>" + testLogo + @"</logo>",
                        @"  <rights type=""text"">" + testRights.Text + @"</rights>",
                        @"  <contributor>",
                        @"    <name>" + testContributorName + @"</name>",
                        @"    <uri>" + testContributorUri + @"</uri>",
                        @"    <email>" + testContributorEmail + @"</email>",
                        @"  </contributor>",
                        @"  <generator uri=""" + testGeneratorUri + @""" version=""" +testGeneratorVersion + @""">" + testGeneratorName + @"</generator>",
                        @"  <icon>" + testIcon + @"</icon>",
                        @"  <author>",
                        @"    <name>" + testAuthorName + @"</name>",
                        @"    <uri>" + testAuthorUri + @"</uri>",
                        @"    <email>" + testAuthorEmail + @"</email>",
                        @"  </author>",
                        @"</source>"),
                    Extractor = fragmentExtractor(TestAtomConstants.AtomSourceElementName)
                },
                new { // specify default feed metadata as source
                    CustomizeMetadata = new Action<AtomEntryMetadata>(metadata => metadata.Source = new AtomFeedMetadata()),
                    Xml = string.Join(
                        "$(NL)",
                        @"<source xmlns=""" + TestAtomConstants.AtomNamespace + @""">",
                        @"  <id />",
                        @"  <title />",
                        @"  <updated />",
                        @"</source>"),
                    Extractor = new Func<XElement, XElement>(result => {
                        var source = fragmentExtractor(TestAtomConstants.AtomSourceElementName)(result);
                        // Remove the value of updates as it can't be reliably predicted
                        source.Element(TestAtomConstants.AtomXNamespace + TestAtomConstants.AtomUpdatedElementName).Nodes().Remove();
                        return source;
                    })
                },
                new { // specify a summary via metadata
                    CustomizeMetadata = new Action<AtomEntryMetadata>(metadata => metadata.Summary = testSummary),
                    Xml = @"<summary type=""text"" xmlns=""" + TestAtomConstants.AtomNamespace + @""">" + testSummary.Text + @"</summary>",
                    Extractor = fragmentExtractor(TestAtomConstants.AtomSummaryElementName)
                },
                new { // specify a title via metadata
                    CustomizeMetadata = new Action<AtomEntryMetadata>(metadata => metadata.Title = testTitle),
                    Xml = @"<title type=""text"" xmlns=""" + TestAtomConstants.AtomNamespace + @""">" + testTitle.Text + @"</title>",
                    Extractor = fragmentExtractor(TestAtomConstants.AtomTitleElementName)
                },
                new { // specify an updated date via metadata
                    CustomizeMetadata = new Action<AtomEntryMetadata>(metadata => metadata.Updated = DateTimeOffset.Parse(testUpdated)),
                    Xml = @"<updated xmlns=""" + TestAtomConstants.AtomNamespace + @""">" + testUpdated + @"</updated>",
                    Extractor = fragmentExtractor(TestAtomConstants.AtomUpdatedElementName)
                },
            };

            // Convert test cases to test descriptions
            IEnumerable<Func<ODataEntry>> entryCreators = new Func<ODataEntry>[]
                {
                    () => ObjectModelUtils.CreateDefaultEntry(),
                    () => ObjectModelUtils.CreateDefaultEntryWithAtomMetadata(),
                };
            var testDescriptors = testCases.SelectMany(testCase =>
                entryCreators.Select(entryCreator =>
                {
                    ODataEntry entry = entryCreator();
                    AtomEntryMetadata metadata = entry.Atom();
                    this.Assert.IsNotNull(metadata, "Expected default entry metadata on a default entry.");
                    testCase.CustomizeMetadata(metadata);
                    return new PayloadWriterTestDescriptor<ODataItem>(this.Settings, entry, testConfiguration =>
                        new AtomWriterTestExpectedResults(this.Settings.ExpectedResultSettings) { Xml = testCase.Xml, FragmentExtractor = testCase.Extractor });
                }));

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors.PayloadCases(WriterPayloads.EntryPayloads),
                this.WriterTestConfigurationProvider.AtomFormatConfigurations,
                (testDescriptor, testConfiguration) =>
                {
                    testConfiguration = testConfiguration.Clone();
                    testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                    TestWriterUtils.WriteAndVerifyODataPayload(testDescriptor, testConfiguration, this.Assert, this.Logger);
                });
        }
Example #17
0
		public Gender DetectByRules(string name, Func<string, Gender>[] rules)
		{
			if (name.Length < 2)
				return Gender.Unknown;
			foreach (var gender in rules.Select(rule => rule.Invoke(name)).Where(gender => gender != Gender.Unknown))
			{
				return gender;
			}
			return Gender.Unknown;
		}
Example #18
0
        public void CollectionExtensions_Delegation_Resolve()
        {
            var targetArr = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

            var target = new Func<int>[10];

            for (int i = 0; i < 10; i++)
            {
                var idx = i;
                target[i] = () => targetArr[idx];
            }

            var result = target.Select(x => x).Resolve();


            for (int i = 0; i < 10; i++)
            {
                targetArr[i] *= 2;
            }

            result = target.Select(x => x).Resolve();

            foreach (var items in Enumerable.Range(0, 10).Zip(result, Tuple.Create))
                Assert.AreEqual(items.Item1 * 2, items.Item2);
        }
Example #19
0
        public void SelectSelect_SourceIsAnArray_ExecutionIsDefered()
        {
            bool funcCalled = false;
            Func<int>[] source = new Func<int>[] { () => { funcCalled = true; return 1; } };

            IEnumerable<int> query = source.Select(d => d).Select(d => d());
            Assert.False(funcCalled);
        }
        public void NavigationLinkMetadataWriterTest()
        {
            string testRelation = "http://docs.oasis-open.org/odata/ns/related/SampleLinkName";
            string testIncorrectRelation = "http://odata.org/relation/1";
            string testTitle = "SampleLinkName";
            string testIncorrectTitle = "Test link 1";
            string testHref = "http://odata.org/link";
            string testIncorrectHref = "http://odata.org/links/1";
            string testHrefLang = "de-AT";
            int? testLength = 999;
            string testMediaType = "application/atom+xml;type=feed";
            string testIncorrectMediaType = "image/png";

            var testCases = new[]
                {
                    new 
                    {
                        CustomizeLink = new Action<ODataNavigationLink>(
                            (link) =>
                                {
                                    AtomLinkMetadata metadata = link.Atom();
                                    metadata.Relation = testRelation;
                                    metadata.Title = testTitle;
                                    metadata.Href = new Uri(testHref);
                                    metadata.HrefLang = testHrefLang;
                                    metadata.Length = testLength;
                                    metadata.MediaType = testMediaType;
                                    link.Url = metadata.Href;
                                }),
                        Xml = @"<link rel=""" + testRelation + @""" type = """ + testMediaType + @""" title=""" + testTitle + @""" href=""" + testHref + @""" hreflang=""" + testHrefLang + @""" length=""" + testLength.Value + @"""  xmlns=""" + TestAtomConstants.AtomNamespace + @""" />",
                        ExpectedException = (ExpectedException)null
                    },
                    new 
                    {
                        CustomizeLink = new Action<ODataNavigationLink>(
                            (link) =>
                                {
                                    AtomLinkMetadata metadata = link.Atom();
                                    metadata.Relation = testRelation;
                                    metadata.Title = testTitle;
                                    metadata.Href = new Uri(testIncorrectHref);
                                    metadata.HrefLang = testHrefLang;
                                    metadata.Length = testLength;
                                    metadata.MediaType = testMediaType;
                                }),
                        Xml = (string)null,
                        ExpectedException = ODataExpectedExceptions.ODataException("ODataAtomWriterMetadataUtils_LinkHrefsMustMatch", "http://odata.org/link", "http://odata.org/links/1"),
                    },
                    new 
                    {
                        CustomizeLink = new Action<ODataNavigationLink>(
                            (link) =>
                                {
                                    AtomLinkMetadata metadata = link.Atom();
                                    metadata.Relation = testIncorrectRelation;
                                    metadata.Title = testTitle;
                                    metadata.Href = new Uri(testHref);
                                    metadata.HrefLang = testHrefLang;
                                    metadata.Length = testLength;
                                    metadata.MediaType = testMediaType;
                                }),
                        Xml = (string)null,
                        ExpectedException = ODataExpectedExceptions.ODataException("ODataAtomWriterMetadataUtils_LinkRelationsMustMatch", "http://docs.oasis-open.org/odata/ns/related/SampleLinkName", "http://odata.org/relation/1"),
                    },
                    new 
                    {
                        CustomizeLink = new Action<ODataNavigationLink>(
                            (link) =>
                                {
                                    AtomLinkMetadata metadata = link.Atom();
                                    metadata.Relation = testRelation;
                                    metadata.Title = testTitle;
                                    metadata.Href = new Uri(testHref);
                                    metadata.HrefLang = testHrefLang;
                                    metadata.Length = testLength;
                                    metadata.MediaType = testIncorrectMediaType;
                                }),
                        Xml = (string)null,
                        ExpectedException = ODataExpectedExceptions.ODataException("ODataAtomWriterMetadataUtils_LinkMediaTypesMustMatch", "application/atom+xml;type=feed", "image/png"),
                    },
                    new 
                    {
                        CustomizeLink = new Action<ODataNavigationLink>(
                            (link) =>
                                {
                                    AtomLinkMetadata metadata = link.Atom();
                                    metadata.Relation = testRelation;
                                    metadata.Title = testIncorrectTitle;
                                    metadata.Href = new Uri(testHref);
                                    metadata.HrefLang = testHrefLang;
                                    metadata.Length = testLength;
                                    metadata.MediaType = testMediaType;
                                }),
                        Xml = (string)null,
                        ExpectedException = ODataExpectedExceptions.ODataException("ODataAtomWriterMetadataUtils_LinkTitlesMustMatch", "SampleLinkName", "Test link 1"),
                    },
                    new 
                    {
                        CustomizeLink = new Action<ODataNavigationLink>(
                            (link) =>
                                {
                                    AtomLinkMetadata metadata = link.Atom();
                                    metadata.Relation = testRelation;
                                    metadata.Title = null;
                                    metadata.Href = new Uri(testHref);
                                    metadata.HrefLang = null;
                                    metadata.Length = null;
                                    metadata.MediaType = null;
                                }),
                        Xml = @"<link rel=""" + testRelation + @""" type = """ + testMediaType + @""" title=""" + testTitle + @""" href=""" + testHref + @""" xmlns=""" + TestAtomConstants.AtomNamespace + @""" />",
                        ExpectedException = (ExpectedException)null
                    },
                };

            Func<XElement, XElement> fragmentExtractor = (e) => e;

            // Convert test cases to test descriptions
            Func<ODataNavigationLink>[] linkCreators = new Func<ODataNavigationLink>[]
            {
                () => ObjectModelUtils.CreateDefaultCollectionLink(),
                () => { var link = ObjectModelUtils.CreateDefaultCollectionLink(); link.SetAnnotation(new AtomLinkMetadata()); return link; }
            };
            var testDescriptors = testCases.SelectMany(testCase =>
                linkCreators.Select(linkCreator =>
                {
                    ODataNavigationLink link = linkCreator();
                    testCase.CustomizeLink(link);
                    return new PayloadWriterTestDescriptor<ODataItem>(this.Settings, link, testConfiguration =>
                        new AtomWriterTestExpectedResults(this.Settings.ExpectedResultSettings) { Xml = testCase.Xml, ExpectedException2 = testCase.ExpectedException, FragmentExtractor = fragmentExtractor });
                }));

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors.PayloadCases(WriterPayloads.NavigationLinkPayloads),
                this.WriterTestConfigurationProvider.AtomFormatConfigurations,
                (testDescriptor, testConfiguration) =>
                {
                    testConfiguration = testConfiguration.Clone();
                    testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                    TestWriterUtils.WriteAndVerifyODataPayload(testDescriptor.DeferredLinksToEntityReferenceLinksInRequest(testConfiguration), testConfiguration, this.Assert, this.Logger);
                });
        }