public void TestForNamingConventionsViolations()
        {
            var allTestFixtures = TypeInfo.For<TestNamingConventionTests>().Assembly.GetTypes().Where(x => TypeInfo.For(x).GetCustomAttributes(false).Any(y => y.GetType() == typeof(TestFixtureAttribute)));
            var allAssembliesUnderTest = new[] {TypeInfo.For<IBuildSystem>().Assembly};
            var allClassesUnderTest = allAssembliesUnderTest.SelectMany(x => x.GetTypes().Select(y => y.FullName)).ToArray();

            var problems = new List<string>();
            foreach (var type in allTestFixtures)
            {
                var testCategory = ((TestFixtureAttribute)TypeInfo.For(type).GetCustomAttributes(false).Single(x => x.GetType() == typeof(TestFixtureAttribute))).Category;

                if (testCategory == null)
                {
                    problems.Add($"The test fixture {type.Name} has no category.");
                    continue;
                }
                
                if (testCategory == TestCategory.GeneralTest ||
                    testCategory == TestCategory.UnitTest)
                {
                    if (!type.Name.EndsWith("Tests"))
                        problems.Add($"The text fixture {type.Name} does not follow the tests naming convention.");
                }

                if (TypeInfo.For(type).GetCustomAttributes(false).All(x => x.GetType() != typeof(HasNoMatchingNamespaceClass)))
                {
                    if (testCategory != TestCategory.UnitTest)
                        continue;

                    var removeEnd = new Func<string, string, string>((str, toRemove) => str.EndsWith(toRemove) ? str.Substring(0, str.Length - toRemove.Length) : str);

                    var expectedTypeName = removeEnd(type.Name, "Tests");
                    var expectedFullName = removeEnd((type.Namespace ?? "").Replace(".Tests.", "."), ".Tests") + "." + expectedTypeName;
                    if (!allClassesUnderTest.Contains(expectedFullName))
                    {
                        var sb = new StringBuilder();
                        sb.AppendLine("Trying_to_run_not_existing_app_should_raise_a_exception fixture has no corresponding tested class.");
                        sb.AppendLine($"  Test fixture:          {type.FullName}");
                        sb.AppendLine($"  Expected tested class: {expectedFullName}");

                        var possibleTypes = allAssembliesUnderTest.SelectMany(x => x.GetTypes()).Where(x => x.Name == expectedTypeName).Select(x => x.FullName).ToArray();
                        if (possibleTypes.Any())
                            sb.AppendLine("  Possible location:     " + string.Join("; ", possibleTypes));


                        sb.AppendLine();
                        problems.Add(sb.ToString());
                    }
                        
                }
            }

            if (problems.Any())
            {
                var sb = new StringBuilder();
                foreach (var problem in problems)
                    sb.Append(problem);
                Assert.Fail(sb.ToString());
            }
        }
 public void TestSelectMany()
 {
     var it = new A { Property = new[] { new B { a = 1, b = "pwic" } } };
     var them = new[] { it };
     Assert.AreEqual(them.SelectMany(x => x.Property, (x, p) => p.a).Count(x => x == 1),
         them.AsQueryable().SelectMany(typeof(A), typeof(B), typeof(int), (Expression<Func<A, IEnumerable<B>>>)(x => x.Property), (Expression<Func<A, B, int>>)((x, p) => p.a)).Cast<int>().Count(x => x == 1));
 }
Example #3
0
        public TypeResolver()
        {
            var typeSpecTypes = new[]
            {
                typeof(DictionaryTypeSpec),
                typeof(EnumerableTypeSpec),
                typeof(EnumTypeSpec),
                typeof(RuntimeTypeSpec),
                typeof(QueryResultType)
            };
            this.typeFactories =
                typeSpecTypes
                    .SelectMany(
                        x =>
                            x.GetMethod("GetFactory", BindingFlags.Static | BindingFlags.Public)
                             .WrapAsEnumerable()
                             .Where(y => y != null && y.DeclaringType == x))
                    .Select(m => (ITypeFactory)m.Invoke(null, null))
                    .OrderBy(x => x.Priority)
                    .ToList();

            this.primitiveNameTypeMap = new Lazy<Dictionary<string, TypeSpec>>(() =>
                                                                                   TypeUtils.GetNativeTypes()
                                                                                            .Select(FromType)
                                                                                            .ToDictionary(x => x.Name, x => x,
                                                                                                          StringComparer.OrdinalIgnoreCase));
        }
Example #4
0
        static Baufile()
        {
            FileSystem.EnsureDirectoryCreated(directory);
            var bin = Path.Combine(directory, "bin");
            FileSystem.EnsureDirectoryCreated(bin);

            var assemblyDirectories = new[]
            {
            #if DEBUG
                @"..\..\..\..\Bau\bin\Debug",
                @"..\..\..\..\Bau.Exec\bin\Debug",
            #else
                @"..\..\..\..\Bau\bin\Release",
                @"..\..\..\..\Bau.Exec\bin\Release",
            #endif
            };

            foreach (var source in assemblyDirectories.SelectMany(bauOutputPath =>
                System.IO.Directory.GetFiles(bauOutputPath, "*.dll", SearchOption.TopDirectoryOnly)))
            {
                var destination = Path.Combine(bin, Path.GetFileName(source));
                if (!File.Exists(destination) || File.GetLastWriteTimeUtc(source) > File.GetLastWriteTimeUtc(destination))
                {
                    File.Copy(source, destination, true);
                }
            }
        }
        private static byte[] LocateIconOnFileSystem()
        {
            if (rootPathProvider == null)
            {
                return null;
            }

            var extensions = new[] { "ico", "png" };

            var locatedFavIcon = extensions.SelectMany(EnumerateFiles).FirstOrDefault();
            if (locatedFavIcon == null)
            {
                return null;
            }

            try
            {
                return File.ReadAllBytes(locatedFavIcon);
            }
            catch (Exception e)
            {
                if (!traceConfiguration.Enabled)
                {
                    throw new InvalidDataException("Unable to load favicon", e);
                }

                return null;
            }
        }
Example #6
0
        public void SelectMany()
        {
            var fullNames = new [] { "Anne Williams", "John Fred Smith", "Sue Green" };

            var result = fullNames.SelectMany(name => name.Split());

            result.Print("|");
        }
 public void Then_ToJoinString_Should_produce_valid_string_with_separator()
 {
     // Arrange
     var ar = new[] { new int[] { }, new[] { 1 }, new[] { 2, 3 } };
     // Act
     var s = ar.SelectMany(a=>(IEnumerable<int>)(a)).ToJoinedString(",");
     // Assert
     Assert.AreEqual(s,"1,2,3");
 }
        public MeetingSubject[] GetSubjects()
        {
            var groups = new [] {
                new MeetupGroupSettings() { Identifier = "umbraco-odense", DefaultCity = "Odense", DefaultTags = new [] {"umbraco", "web", "c#" } },
                new MeetupGroupSettings() { Identifier = "dwodense", DefaultCity = "Odense", DefaultTags = new [] {"web", "design", "javascript" } },
            };

            return groups.SelectMany(GetSubject).ToArray();
        }
 /// <summary>
 /// Loads custom elements from the standard library assembly and any additional assemblies passed.
 /// </summary>
 internal static void Init( params Assembly[] additionalAssemblies )
 {
     var assemblies = new[] { Assembly.GetExecutingAssembly() }.Concat( additionalAssemblies );
     elements.AddRange(
         assemblies.SelectMany( i => i.CreateInstancesOfImplementations<ControlCssElementCreator>().SelectMany( creator => creator.CreateCssElements() ) ) );
     var duplicateElementNames = elements.Select( i => i.Name ).GetDuplicates().ToArray();
     if( duplicateElementNames.Any() )
         throw new ApplicationException( "Duplicate elements exist: " + StringTools.ConcatenateWithDelimiter( ", ", duplicateElementNames ) + "." );
 }
        public void Analize_AllSvos_MatchAttribute()
        {
            var assemblies = new[] { typeof(Date).Assembly, typeof(Qowaiv.Web.InternetMediaType).Assembly };

            var svos = assemblies.SelectMany(assembly => assembly.GetTypes())
               .Where(tp => QowaivType.IsSingleValueObject(tp))
               .OrderBy(tp => tp.Namespace)
               .ThenBy(tp => tp.Name)
               .ToArray();

            var exp = new []
            {
                typeof(Date),
                typeof(EmailAddress),
                typeof(Gender),
                typeof(HouseNumber),
                typeof(LocalDateTime),
                typeof(Month),
                typeof(Percentage),
                typeof(PostalCode),
                typeof(Uuid),
                typeof(WeekDate),
                typeof(Year),
                typeof(Qowaiv.Financial.Amount),
                typeof(Qowaiv.Financial.BankIdentifierCode),
                typeof(Qowaiv.Financial.Currency),
                typeof(Qowaiv.Financial.InternationalBankAccountNumber),
                typeof(Qowaiv.Financial.Money),
                typeof(Qowaiv.Globalization.Country),
                typeof(Qowaiv.IO.StreamSize),
                typeof(Qowaiv.Security.Cryptography.CryptographicSeed),
                typeof(Qowaiv.Sql.Timestamp),
                typeof(Qowaiv.Statistics.Elo),
                typeof(Qowaiv.Web.InternetMediaType)
            };

            foreach (var svo in svos)
            {
                Console.WriteLine(svo);
            }

            CollectionAssert.AreEqual(exp, svos);

            foreach (var svo in svos)
            {
                var attr = QowaivType.GetSingleValueObjectAttribute(svo);

                SvoAssert.UnderlyingTypeMatches(svo, attr);
                SvoAssert.ParseMatches(svo, attr);
                SvoAssert.TryParseMatches(svo, attr);
                SvoAssert.IsValidMatches(svo, attr);
                SvoAssert.EmptyAndUnknownMatches(svo, attr);
                SvoAssert.ImplementsInterfaces(svo);
                SvoAssert.AttributesMatches(svo);
            }
        }
Example #11
0
 public override Point[] OnGetPossibleMoves()
 {
     var tmp = new[] { -1, 0, 1 };
     var moves = tmp.SelectMany(x => tmp.Select(y => Point.Create(x, y)))
        .Where(p => p != Point.Create(0, 0))
        .Select(p => this.Point + p)
        .ValidateRange(8)
        .Where(p => base.Board[p.X, p.Y] == null || base.Board[p.X, p.Y].Color != this.Color);
     return moves.ToArray();
 }
        public ValidationViewModel()
        {
            // null is success(have no error), string is error message
            ValidationData = new ReactiveProperty<string>()
                .SetValidateNotifyError((string s) => !string.IsNullOrEmpty(s) && s.Cast<char>().All(Char.IsUpper) ? null : "not all uppercase");

            // async validation
            // first argument is self observable sequence
            // null is success(have no error), IEnumerable is error messages
            ValidationNotify = new ReactiveProperty<string>("foo!", ReactivePropertyMode.RaiseLatestValueOnSubscribe)
                .SetValidateNotifyError(self => self
                    .Delay(TimeSpan.FromSeconds(3)) // asynchronous validation...
                    .Select(s => string.IsNullOrEmpty(s) ? null : "not empty string"));

            // both validation
            ValidationBoth = new ReactiveProperty<string>()
                .SetValidateNotifyError(s => !string.IsNullOrEmpty(s) && s.Cast<char>().All(Char.IsLower) ? null : "not all lowercase")
                .SetValidateNotifyError(self => self
                    .Delay(TimeSpan.FromSeconds(1)) // asynchronous validation...
                    .Select(s => string.IsNullOrEmpty(s) || s.Length <= 5 ? null : (IEnumerable)new[] { "length 5" }));

            // Validation result is pushed to ObserveErrors
            var errors = new[]
                {
                    ValidationData.ObserveErrorChanged,
                    ValidationBoth.ObserveErrorChanged,
                    ValidationNotify.ObserveErrorChanged
                }
                .CombineLatest();

            // Use OfType, choose error source
            ErrorInfo = errors
                .SelectMany(x => x)
                .Where(x => x != null)
                .Select(x => x.OfType<string>())
                .Select(x => x.FirstOrDefault())
                .ToReactiveProperty();

            // Validation is view initialized not run in default.
            // If want to validate on view initialize,
            // use ReactivePropertyMode.RaiseLatestValueOnSubscribe to ReactiveProperty
            // that mode is validate values on initialize.
            NextCommand =
                new[]
                {
                    ValidationData.ObserveHasErrors,
                    ValidationBoth.ObserveHasErrors,
                    ValidationNotify.ObserveHasErrors
                }
                .CombineLatestValuesAreAllFalse()
                .ToReactiveCommand();
            this.AlertMessage = NextCommand.Select(_ => "Can go to next!").ToReactiveProperty(
                initialValue: "Can go to next!",
                mode: ReactivePropertyMode.None);
        }
Example #13
0
        /// <summary>
        /// Searches the PATH for an executable.
        /// </summary>
        /// <param name="filename">Name of file to search along path.</param>
        /// <returns>Full path to executable if found, null otherwise.</returns>
        public static string SearchPathForExecutable(string filename)
        {
            string[] pathEnvironment = Environment.GetEnvironmentVariable("PATH").Split(';');
            string[] extensionEnvironment = Environment.GetEnvironmentVariable("PATHEXT").Split(';');

            var paths = new[] { Environment.CurrentDirectory }.Concat(pathEnvironment);
            var extensions = new[] { String.Empty }.Concat(extensionEnvironment.Where(e => e.StartsWith(".")));

            var combinations = paths.SelectMany(x => extensions, (path, extension) => Path.Combine(path, filename + extension));
            return combinations.FirstOrDefault(File.Exists);
        }
        private static IEnumerable<Type> GetClassLevelInterceptorTypes(object handler)
        {
            var classHierarchy = new[] {handler.GetType()}.DepthFirst(t => new[] {t.BaseType}.NotNull()).ToArray();

            var classLevelInterceptorTypes = classHierarchy
                .SelectMany(t => t.GetCustomAttributes<InterceptorAttribute>())
                .Select(attr => attr.InterceptorType)
                .ToArray();

            return classLevelInterceptorTypes;
        }
Example #15
0
        public void AddingTimeSlicesShouldBeFastUsingMemoryStore()
        {
            var random = new Random();
            //50 branches 
            var network = RouteHelperTest.GetSnakeNetwork(false, 50);
            //10 offsets
            var offsets = new[] { 0, 10, 20, 30, 40, 50, 60, 70, 80, 90 };

            //500 locations
            var locations = offsets.SelectMany(o => network.Branches, (o, b) => new NetworkLocation(b, o)).ToList();

            var values = (from o in locations
                          select (double)random.Next(100) / 10).ToList();

            //setup the coverage with fixed size locations
            var networkCoverage = new NetworkCoverage() { IsTimeDependent = true, Network = network };
            networkCoverage.Locations.FixedSize = 500;
            networkCoverage.Locations.SetValues(locations.OrderBy(l => l));

            var startTime = new DateTime(2000, 1, 1);
            // add 10000 slices in time..
            var times = from i in Enumerable.Range(1, 1000)
                        select startTime.AddDays(i);

            int outputTimeStepIndex = 0;
            //write like a flowmodel ..
            TestHelper.AssertIsFasterThan(2000, () =>
                                                    {
                                                        foreach (var t in times)
                                                        {
                                                            //high performance writing. Using indexes instead of values.
                                                            var locationsIndexFilter =
                                                                new VariableIndexRangeFilter(networkCoverage.Locations,
                                                                                             0,
                                                                                             networkCoverage.Locations.
                                                                                                 FixedSize - 1);
                                                            //current timestep starts at 1 and is increased before outputvalues are set now..hence -2 to get a 0 for the 1st
                                                            //int timeIndex = currentTimeStep - 1;

                                                            var timeIndexFilter =
                                                                new VariableIndexRangeFilter(networkCoverage.Time,
                                                                                             outputTimeStepIndex);

                                                            networkCoverage.Time.AddValues(new[] { t });
                                                            networkCoverage.SetValues(values,
                                                                                      new[]
                                                                                          {
                                                                                              locationsIndexFilter,
                                                                                              timeIndexFilter
                                                                                          });
                                                            outputTimeStepIndex++;
                                                        }
                                                    });
        }
        public void Should_match_parameterized_action_path_with_request_path()
        {
            // Given
            var request = new Request("GET", "/fake/child/route");
            var modules = new[] { new FakeNancyModuleWithBasePath() };
            var descriptions = modules.SelectMany(x => x.GetRouteDescription(request));

            // When
            var route = this.resolver.GetRoute(request, descriptions);

            // Then
            route.ShouldNotBeOfType<NoMatchingRouteFoundRoute>();
        }
        public void Should_be_case_insensitive_when_matching(string path)
        {
            // Given
            var request = new Request("GET", path);

            var modules = new[] { new FakeNancyModuleWithBasePath() };
            var descriptions = modules.SelectMany(x => x.GetRouteDescription(request));

            // When
            var route = this.resolver.GetRoute(request, descriptions);

            // Then
            route.ShouldNotBeOfType<NoMatchingRouteFoundRoute>();
        }
        public void Should_match_on_combination_of_module_base_path_and_action_path_when_module_defines_base_path()
        {
            // Given
            var request = new Request("GET", "/fake/route/with/some/parts");

            var modules = new[] { new FakeNancyModuleWithBasePath() };
            var descriptions = modules.SelectMany(x => x.GetRouteDescription(request));

            // When
            var route = this.resolver.GetRoute(request, descriptions);

            // Then
            route.ShouldNotBeOfType<NoMatchingRouteFoundRoute>();
        }
Example #19
0
        static void Main()
        {
            var container = new Container();

            var appDomainDirectory = AppDomain.CurrentDomain.BaseDirectory;
            var assembliesToLoad = new List<string>();
            foreach (var fileName in Directory.EnumerateFiles(appDomainDirectory).Select(s => s.Replace(appDomainDirectory, string.Empty)))
            {
                if (fileName.StartsWith("Banking") && fileName.EndsWith(".dll"))
                {
                    assembliesToLoad.Add(fileName);
                }
            }

            var assemblies = new[] { Assembly.GetExecutingAssembly() }.ToList();
            assemblies.AddRange(assembliesToLoad.Select(Assembly.LoadFrom));
            var types = assemblies.SelectMany(a => a.GetTypes());

            foreach (var type in types)
            {
                if (type.IsClass && type.GetInterfaces().Any() && !type.IsNested)
                {
                    foreach (var @interface in type.GetInterfaces())
                    {
                        if (@interface.FullName.StartsWith("Banking"))
                        {
                            try
                            {
                                container.Register(@interface, type);
                            }
                            catch (Exception) { }
                        }
                    }
                }
            }

            container.Verify();

            if (!File.Exists("datastore.txt"))
            {
                File.Create("datastore.txt").Close();
            }

            ApplicationFacade.Configure(container.GetInstance<AccountBalanceController>, container.GetInstance<HomeController>);

            var controller = container.GetInstance<HomeController>();

            controller.GetHomeView();
        }
Example #20
0
 public byte[] GetData()
 {
     var chunks = new[]
         {
             Int32Single.Create(bbox.Min.x),
             Int32Single.Create(bbox.Min.y),
             Int32Single.Create(bbox.Min.z),
             Int32Single.Create(bbox.Max.x),
             Int32Single.Create(bbox.Max.y),
             Int32Single.Create(bbox.Max.z),
             Int32Single.Create(primitive),
             Int32Single.Create(skipIndex)
         };
     return chunks.SelectMany(item => item.GetBytes()).ToArray();
 }
Example #21
0
        public IList<FileInfo> GetAssemblies()
        {
            var executingAssmDirs = new[]
            {
                new Uri(Assembly.GetExecutingAssembly().GetName().CodeBase).LocalPath.ToUpper(),
                new Uri(Assembly.GetCallingAssembly().GetName().CodeBase).LocalPath.ToUpper()
            };

            var assemblyFiles = executingAssmDirs.SelectMany(
                dir =>
                    (new DirectoryInfo(Path.GetDirectoryName(dir))).GetFiles("td.veritas.*.dll")
                        .Concat((new DirectoryInfo(Path.GetDirectoryName(dir)).GetFiles("td.veritas.*.exe"))));

            return assemblyFiles.ToList();
        }
        public IEnumerable<IMongoQuery> EnumerateQueries()
        {
            var sides = new[] { "both", "right", "left" };
            var sideTypes = new[] { "parallel", "diagonal", "perpendicular", "marked" };

            var tagsQueries = sides.SelectMany(side => sideTypes.Select(sideType => Tuple.Create(side, sideType)))
                .Select(combo => Query.EQ("Tags.parking:lane:" + combo.Item1, combo.Item2)).ToArray();

            return new[]
            {
                Query.EQ("Tags.amenity", "parking_space"),
                Query.EQ("Tags.amenity", "parking"),
                Query.EQ("Tags.site", "parking")
            }.Concat(tagsQueries);
        }
        public void EntityReferenceLinkReaderAtomTest()
        {
            // extra attributes on the <uri> element
            var linkElementPayloads = new[]
            {
                // The spec behavior - the element is in the OData namespace
                new
                {
                    PayloadElement = PayloadBuilder.DeferredLink("http://odata.org/link"),
                    Template = "<m:ref id=\"http://odata.org/link\"/>",
                },
                // The backward compatibility behavior - the element is in the OData metadata namespace
                new
                {
                    PayloadElement = PayloadBuilder.DeferredLink("http://odata.org/link"),
                    Template = "<m:ref id=\"http://odata.org/link\" />",
                },
            };

            string[] attributes = new string[]
            {
                "foo='bar'",
                "m:foo='bar'",
                "foo=''",
                "lang='invalid'",
            };

            IEnumerable<PayloadReaderTestDescriptor> testDescriptors = linkElementPayloads.SelectMany(linkPayload =>
                attributes.Select(attribute =>
                {
                    var payloadElement = linkPayload.PayloadElement.DeepCopy();
                    string xmlRepresentation = string.Format(CultureInfo.InvariantCulture, linkPayload.Template, attribute);
                    payloadElement = payloadElement.XmlRepresentation(xmlRepresentation);

                    return new PayloadReaderTestDescriptor(this.Settings)
                    {
                        PayloadElement = payloadElement
                    };
                }));

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.ReaderTestConfigurationProvider.AtomFormatConfigurations,
                (testDescriptor, testConfiguration) =>
                {
                    testDescriptor.RunTest(testConfiguration);
                });
        }
        public IEnumerable<string> GetConfigurableBootstrapperMembers()
        {
            var ignoreList = new[]
            {
                "AfterRequest", "BeforeRequest", "IsValid", "ModuleKeyGenerator",
                "BindingDefaults"
            };

            var typesToReflect =
                new[] { typeof(NancyBootstrapperBase<>), typeof(NancyInternalConfiguration) };

            return typesToReflect
                .SelectMany(x => x.GetProperties(BindingFlags.Public | BindingFlags.Instance))
                .Select(x => x.Name)
                .Where(x => !ignoreList.Contains(x, StringComparer.OrdinalIgnoreCase));
        }
Example #25
0
        public static string FindInSearchPath(string fileName)
        {
            bool hasExt = fileName.IndexOf('.') > 0;

            var paths = new[] { Environment.CurrentDirectory }
              .Concat(Environment.GetEnvironmentVariable("PATH").Split(';'));

            var extensions = Environment.GetEnvironmentVariable("PATHEXT").Split(';')
                               .Where(e => e.StartsWith(".") );

            var combinations = hasExt ?
                paths.Select((path)=> Path.Combine(path, fileName)) :
                paths.SelectMany(x => extensions,
                    (path, extension) => Path.Combine(path, fileName + extension));

            return combinations.FirstOrDefault(File.Exists);
        }
Example #26
0
		public void AddRowsShouldSetChildren()
		{
			Invoke(() =>
			{
				var rows = new [] {
					new TableRow(new Label(), new TextBox()),
					new TableRow(new Label(), new TextBox())
				};

				var layout = new TableLayout();
				foreach (var row in rows)
					layout.Rows.Add(row);


				CollectionAssert.AreEqual(rows.SelectMany(r => r.Cells).Select(r => r.Control), layout.Children);
			});
		}
    static void Main()
    {
        var students =
        new[] {
            new { Name = "Pesho", Courses = new string[] {".NET", "PHP" }},
            new { Name = "Pesho", Courses = new string[] {"Java", "PHP" , "SQL"}},
            new { Name = "Pesho", Courses = new string[] {"Java", "PHP" }},
            new { Name = "Pesho", Courses = new string[] {".NET", "Java" }}
        };

        var courses = students.SelectMany(s => s.Courses).Distinct().OrderBy(c => c);

        foreach (var c in courses)
        {
            Console.WriteLine(c);
        }
    }
	public static void Main() {
		int[] arr1 = new[] { 1, 2, 3 };
		int[] arr2 = new[] { 1, 2, 3 };

		var query = arr1.SelectMany (i => arr2, (i, j) => new {
	i,
	j
}).Where (_ => _.i >= _.j).Select (_1 => new {
	_1,
	k = _1.i + _1.j
}).Select (_2 => "i = " + _2._1.i + ", j = " + _2._1.j + ", k = " + _2.k);

		var sb = new StringBuilder();
		foreach (var x in query)
			sb.AppendLine(x);

		Console.WriteLine(sb.ToString());
	}
Example #29
0
        public static void RegisterRoutes(IUnityContainer container)
        {
            var httpConfiguration = container.Resolve<HttpConfiguration>();
            var moduleInitializerOptions = container.Resolve<IModuleInitializerOptions>();
            var routePrefix = moduleInitializerOptions.RoutePrefix;

            var xmlCommentsDirectoryPaths = new[]
            {
                moduleInitializerOptions.VirtualRoot + "/App_Data/Modules",
                moduleInitializerOptions.VirtualRoot + "/bin"
            };
            var xmlCommentsFilePaths = xmlCommentsDirectoryPaths.SelectMany(GetXmlFilesPaths).ToArray();

            // Add separate swagger generator for platform
            EnableSwagger("VirtoCommerce.Platform", httpConfiguration, container, routePrefix, xmlCommentsFilePaths, false, Assembly.GetExecutingAssembly());

            // Add separate swagger generator for each installed module
            foreach (var module in container.Resolve<IModuleCatalog>().Modules.OfType<ManifestModuleInfo>().Where(m => m.ModuleInstance != null))
            {
                EnableSwagger(module.ModuleName, httpConfiguration, container, routePrefix, xmlCommentsFilePaths, module.UseFullTypeNameInSwagger, module.ModuleInstance.GetType().Assembly);
            }

            // Add full swagger generator
            httpConfiguration.EnableSwagger(routePrefix + "docs/{apiVersion}", c =>
            {
                Func<TagsFilter> tagsFilterFactory = () => new TagsFilter(container.Resolve<IModuleCatalog>(), container.Resolve<ISettingsManager>());

                c.SingleApiVersion("v1", "VirtoCommerce Solution REST API documentation");
                c.UseFullTypeNameInSchemaIds();
                c.DocumentFilter(tagsFilterFactory);
                c.OperationFilter(tagsFilterFactory);
                ApplyCommonSwaggerConfiguration(c, container, string.Empty, xmlCommentsFilePaths);
            })
            .EnableSwaggerUi(routePrefix + "docs/ui/{*assetPath}", c =>
            {
                var assembly = Assembly.GetExecutingAssembly();
                const string resourcePrefix = "VirtoCommerce.Platform.Web.Swagger.UI.";

                c.CustomAsset("index", assembly, resourcePrefix + "index.html");
                c.CustomAsset("images/logo_small-png", assembly, resourcePrefix + "logo_small.png");
                c.CustomAsset("css/vc-css", assembly, resourcePrefix + "vc.css");
                c.CustomAsset("swagger-ui-min-js", assembly, resourcePrefix + "swagger-ui.min.js");
            });
        }
        private static IEnumerable<Type> GetMethodLevelInterceptorTypes(object handler, object message)
        {
            var messageType = message.GetType();

            var method = handler.GetType().GetMethods()
                                .Where(m => string.Compare(m.Name, "Handle", StringComparison.OrdinalIgnoreCase) == 0)
                                .Where(m => m.GetParameters().Count() == 1)
                                .Where(m => m.GetParameters().First().ParameterType == messageType)
                                .Single();

            var methodHierarchy = new[] {method}.DepthFirst(m => new[] {m.GetBaseDefinition()}.NotNull()).ToArray();

            var methodLevelInterceptorTypes = methodHierarchy
                .SelectMany(m => m.GetCustomAttributes<InterceptorAttribute>())
                .Select(attr => attr.InterceptorType)
                .ToArray();

            return methodLevelInterceptorTypes;
        }